/brz/remove-bazaar

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

« back to all changes in this revision

Viewing changes to bzrlib/repository.py

  • Committer: Martin von Gagern
  • Date: 2010-04-20 08:47:38 UTC
  • mfrom: (5167 +trunk)
  • mto: This revision was merged to the branch mainline in revision 5195.
  • Revision ID: martin.vgagern@gmx.net-20100420084738-ygymnqmdllzrhpfn
merge trunk

Show diffs side-by-side

added added

removed removed

Lines of Context:
1
 
# Copyright (C) 2005, 2006, 2007, 2008 Canonical Ltd
 
1
# Copyright (C) 2005-2010 Canonical Ltd
2
2
#
3
3
# This program is free software; you can redistribute it and/or modify
4
4
# it under the terms of the GNU General Public License as published by
12
12
#
13
13
# You should have received a copy of the GNU General Public License
14
14
# along with this program; if not, write to the Free Software
15
 
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
16
 
 
17
 
from cStringIO import StringIO
 
15
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
18
16
 
19
17
from bzrlib.lazy_import import lazy_import
20
18
lazy_import(globals(), """
 
19
import cStringIO
21
20
import re
22
21
import time
23
22
 
24
23
from bzrlib import (
25
24
    bzrdir,
26
25
    check,
 
26
    chk_map,
 
27
    config,
27
28
    debug,
28
29
    errors,
 
30
    fetch as _mod_fetch,
 
31
    fifo_cache,
29
32
    generate_ids,
30
33
    gpg,
31
34
    graph,
 
35
    inventory,
 
36
    inventory_delta,
32
37
    lazy_regex,
33
38
    lockable_files,
34
39
    lockdir,
35
40
    lru_cache,
36
41
    osutils,
37
 
    registry,
38
 
    remote,
39
42
    revision as _mod_revision,
 
43
    static_tuple,
40
44
    symbol_versioning,
41
 
    transactions,
 
45
    trace,
42
46
    tsort,
43
47
    ui,
 
48
    versionedfile,
44
49
    )
45
50
from bzrlib.bundle import serializer
46
51
from bzrlib.revisiontree import RevisionTree
47
52
from bzrlib.store.versioned import VersionedFileStore
48
 
from bzrlib.store.text import TextStore
49
53
from bzrlib.testament import Testament
50
 
from bzrlib.util import bencode
51
54
""")
52
55
 
53
 
from bzrlib.decorators import needs_read_lock, needs_write_lock
 
56
from bzrlib.decorators import needs_read_lock, needs_write_lock, only_raises
54
57
from bzrlib.inter import InterObject
55
 
from bzrlib.inventory import Inventory, InventoryDirectory, ROOT_ID
56
 
from bzrlib.symbol_versioning import (
57
 
        deprecated_method,
58
 
        one_one,
59
 
        one_two,
60
 
        one_three,
61
 
        one_six,
62
 
        )
63
 
from bzrlib.trace import mutter, mutter_callsite, note, warning
 
58
from bzrlib.inventory import (
 
59
    Inventory,
 
60
    InventoryDirectory,
 
61
    ROOT_ID,
 
62
    entry_factory,
 
63
    )
 
64
from bzrlib.lock import _RelockDebugMixin
 
65
from bzrlib import registry
 
66
from bzrlib.trace import (
 
67
    log_exception_quietly, note, mutter, mutter_callsite, warning)
64
68
 
65
69
 
66
70
# Old formats display a warning, but only once
70
74
class CommitBuilder(object):
71
75
    """Provides an interface to build up a commit.
72
76
 
73
 
    This allows describing a tree to be committed without needing to 
 
77
    This allows describing a tree to be committed without needing to
74
78
    know the internals of the format of the repository.
75
79
    """
76
 
    
 
80
 
77
81
    # all clients should supply tree roots.
78
82
    record_root_entry = True
79
83
    # the default CommitBuilder does not manage trees whose root is versioned.
107
111
 
108
112
        self._revprops = {}
109
113
        if revprops is not None:
 
114
            self._validate_revprops(revprops)
110
115
            self._revprops.update(revprops)
111
116
 
112
117
        if timestamp is None:
121
126
 
122
127
        self._generate_revision_if_needed()
123
128
        self.__heads = graph.HeadsCache(repository.get_graph()).heads
 
129
        self._basis_delta = []
 
130
        # API compatibility, older code that used CommitBuilder did not call
 
131
        # .record_delete(), which means the delta that is computed would not be
 
132
        # valid. Callers that will call record_delete() should call
 
133
        # .will_record_deletes() to indicate that.
 
134
        self._recording_deletes = False
 
135
        # memo'd check for no-op commits.
 
136
        self._any_changes = False
 
137
 
 
138
    def any_changes(self):
 
139
        """Return True if any entries were changed.
 
140
        
 
141
        This includes merge-only changes. It is the core for the --unchanged
 
142
        detection in commit.
 
143
 
 
144
        :return: True if any changes have occured.
 
145
        """
 
146
        return self._any_changes
 
147
 
 
148
    def _validate_unicode_text(self, text, context):
 
149
        """Verify things like commit messages don't have bogus characters."""
 
150
        if '\r' in text:
 
151
            raise ValueError('Invalid value for %s: %r' % (context, text))
 
152
 
 
153
    def _validate_revprops(self, revprops):
 
154
        for key, value in revprops.iteritems():
 
155
            # We know that the XML serializers do not round trip '\r'
 
156
            # correctly, so refuse to accept them
 
157
            if not isinstance(value, basestring):
 
158
                raise ValueError('revision property (%s) is not a valid'
 
159
                                 ' (unicode) string: %r' % (key, value))
 
160
            self._validate_unicode_text(value,
 
161
                                        'revision property (%s)' % (key,))
124
162
 
125
163
    def commit(self, message):
126
164
        """Make the actual commit.
127
165
 
128
166
        :return: The revision id of the recorded revision.
129
167
        """
 
168
        self._validate_unicode_text(message, 'commit message')
130
169
        rev = _mod_revision.Revision(
131
170
                       timestamp=self._timestamp,
132
171
                       timezone=self._timezone,
155
194
        deserializing the inventory, while we already have a copy in
156
195
        memory.
157
196
        """
 
197
        if self.new_inventory is None:
 
198
            self.new_inventory = self.repository.get_inventory(
 
199
                self._new_revision_id)
158
200
        return RevisionTree(self.repository, self.new_inventory,
159
 
                            self._new_revision_id)
 
201
            self._new_revision_id)
160
202
 
161
203
    def finish_inventory(self):
162
 
        """Tell the builder that the inventory is finished."""
163
 
        if self.new_inventory.root is None:
164
 
            raise AssertionError('Root entry should be supplied to'
165
 
                ' record_entry_contents, as of bzr 0.10.')
166
 
            self.new_inventory.add(InventoryDirectory(ROOT_ID, '', None))
167
 
        self.new_inventory.revision_id = self._new_revision_id
168
 
        self.inv_sha1 = self.repository.add_inventory(
169
 
            self._new_revision_id,
170
 
            self.new_inventory,
171
 
            self.parents
172
 
            )
 
204
        """Tell the builder that the inventory is finished.
 
205
 
 
206
        :return: The inventory id in the repository, which can be used with
 
207
            repository.get_inventory.
 
208
        """
 
209
        if self.new_inventory is None:
 
210
            # an inventory delta was accumulated without creating a new
 
211
            # inventory.
 
212
            basis_id = self.basis_delta_revision
 
213
            # We ignore the 'inventory' returned by add_inventory_by_delta
 
214
            # because self.new_inventory is used to hint to the rest of the
 
215
            # system what code path was taken
 
216
            self.inv_sha1, _ = self.repository.add_inventory_by_delta(
 
217
                basis_id, self._basis_delta, self._new_revision_id,
 
218
                self.parents)
 
219
        else:
 
220
            if self.new_inventory.root is None:
 
221
                raise AssertionError('Root entry should be supplied to'
 
222
                    ' record_entry_contents, as of bzr 0.10.')
 
223
                self.new_inventory.add(InventoryDirectory(ROOT_ID, '', None))
 
224
            self.new_inventory.revision_id = self._new_revision_id
 
225
            self.inv_sha1 = self.repository.add_inventory(
 
226
                self._new_revision_id,
 
227
                self.new_inventory,
 
228
                self.parents
 
229
                )
 
230
        return self._new_revision_id
173
231
 
174
232
    def _gen_revision_id(self):
175
233
        """Return new revision-id."""
178
236
 
179
237
    def _generate_revision_if_needed(self):
180
238
        """Create a revision id if None was supplied.
181
 
        
 
239
 
182
240
        If the repository can not support user-specified revision ids
183
241
        they should override this function and raise CannotSetRevisionId
184
242
        if _new_revision_id is not None.
212
270
        # _new_revision_id
213
271
        ie.revision = self._new_revision_id
214
272
 
 
273
    def _require_root_change(self, tree):
 
274
        """Enforce an appropriate root object change.
 
275
 
 
276
        This is called once when record_iter_changes is called, if and only if
 
277
        the root was not in the delta calculated by record_iter_changes.
 
278
 
 
279
        :param tree: The tree which is being committed.
 
280
        """
 
281
        # NB: if there are no parents then this method is not called, so no
 
282
        # need to guard on parents having length.
 
283
        entry = entry_factory['directory'](tree.path2id(''), '',
 
284
            None)
 
285
        entry.revision = self._new_revision_id
 
286
        self._basis_delta.append(('', '', entry.file_id, entry))
 
287
 
215
288
    def _get_delta(self, ie, basis_inv, path):
216
289
        """Get a delta against the basis inventory for ie."""
217
290
        if ie.file_id not in basis_inv:
218
291
            # add
219
 
            return (None, path, ie.file_id, ie)
 
292
            result = (None, path, ie.file_id, ie)
 
293
            self._basis_delta.append(result)
 
294
            return result
220
295
        elif ie != basis_inv[ie.file_id]:
221
296
            # common but altered
222
297
            # TODO: avoid tis id2path call.
223
 
            return (basis_inv.id2path(ie.file_id), path, ie.file_id, ie)
 
298
            result = (basis_inv.id2path(ie.file_id), path, ie.file_id, ie)
 
299
            self._basis_delta.append(result)
 
300
            return result
224
301
        else:
225
302
            # common, unaltered
226
303
            return None
227
304
 
 
305
    def get_basis_delta(self):
 
306
        """Return the complete inventory delta versus the basis inventory.
 
307
 
 
308
        This has been built up with the calls to record_delete and
 
309
        record_entry_contents. The client must have already called
 
310
        will_record_deletes() to indicate that they will be generating a
 
311
        complete delta.
 
312
 
 
313
        :return: An inventory delta, suitable for use with apply_delta, or
 
314
            Repository.add_inventory_by_delta, etc.
 
315
        """
 
316
        if not self._recording_deletes:
 
317
            raise AssertionError("recording deletes not activated.")
 
318
        return self._basis_delta
 
319
 
 
320
    def record_delete(self, path, file_id):
 
321
        """Record that a delete occured against a basis tree.
 
322
 
 
323
        This is an optional API - when used it adds items to the basis_delta
 
324
        being accumulated by the commit builder. It cannot be called unless the
 
325
        method will_record_deletes() has been called to inform the builder that
 
326
        a delta is being supplied.
 
327
 
 
328
        :param path: The path of the thing deleted.
 
329
        :param file_id: The file id that was deleted.
 
330
        """
 
331
        if not self._recording_deletes:
 
332
            raise AssertionError("recording deletes not activated.")
 
333
        delta = (path, None, file_id, None)
 
334
        self._basis_delta.append(delta)
 
335
        self._any_changes = True
 
336
        return delta
 
337
 
 
338
    def will_record_deletes(self):
 
339
        """Tell the commit builder that deletes are being notified.
 
340
 
 
341
        This enables the accumulation of an inventory delta; for the resulting
 
342
        commit to be valid, deletes against the basis MUST be recorded via
 
343
        builder.record_delete().
 
344
        """
 
345
        self._recording_deletes = True
 
346
        try:
 
347
            basis_id = self.parents[0]
 
348
        except IndexError:
 
349
            basis_id = _mod_revision.NULL_REVISION
 
350
        self.basis_delta_revision = basis_id
 
351
 
228
352
    def record_entry_contents(self, ie, parent_invs, path, tree,
229
353
        content_summary):
230
354
        """Record the content of ie from tree into the commit if needed.
235
359
        :param parent_invs: The inventories of the parent revisions of the
236
360
            commit.
237
361
        :param path: The path the entry is at in the tree.
238
 
        :param tree: The tree which contains this entry and should be used to 
 
362
        :param tree: The tree which contains this entry and should be used to
239
363
            obtain content.
240
364
        :param content_summary: Summary data from the tree about the paths
241
365
            content - stat, length, exec, sha/link target. This is only
282
406
        if ie.revision is not None:
283
407
            if not self._versioned_root and path == '':
284
408
                # repositories that do not version the root set the root's
285
 
                # revision to the new commit even when no change occurs, and
286
 
                # this masks when a change may have occurred against the basis,
287
 
                # so calculate if one happened.
 
409
                # revision to the new commit even when no change occurs (more
 
410
                # specifically, they do not record a revision on the root; and
 
411
                # the rev id is assigned to the root during deserialisation -
 
412
                # this masks when a change may have occurred against the basis.
 
413
                # To match this we always issue a delta, because the revision
 
414
                # of the root will always be changing.
288
415
                if ie.file_id in basis_inv:
289
416
                    delta = (basis_inv.id2path(ie.file_id), path,
290
417
                        ie.file_id, ie)
291
418
                else:
292
419
                    # add
293
420
                    delta = (None, path, ie.file_id, ie)
 
421
                self._basis_delta.append(delta)
294
422
                return delta, False, None
295
423
            else:
296
424
                # we don't need to commit this, because the caller already
345
473
            if content_summary[2] is None:
346
474
                raise ValueError("Files must not have executable = None")
347
475
            if not store:
348
 
                if (# if the file length changed we have to store:
349
 
                    parent_entry.text_size != content_summary[1] or
350
 
                    # if the exec bit has changed we have to store:
 
476
                # We can't trust a check of the file length because of content
 
477
                # filtering...
 
478
                if (# if the exec bit has changed we have to store:
351
479
                    parent_entry.executable != content_summary[2]):
352
480
                    store = True
353
481
                elif parent_entry.text_sha1 == content_summary[3]:
372
500
            ie.executable = content_summary[2]
373
501
            file_obj, stat_value = tree.get_file_with_stat(ie.file_id, path)
374
502
            try:
375
 
                lines = file_obj.readlines()
 
503
                text = file_obj.read()
376
504
            finally:
377
505
                file_obj.close()
378
506
            try:
379
507
                ie.text_sha1, ie.text_size = self._add_text_to_weave(
380
 
                    ie.file_id, lines, heads, nostore_sha)
 
508
                    ie.file_id, text, heads, nostore_sha)
381
509
                # Let the caller know we generated a stat fingerprint.
382
510
                fingerprint = (ie.text_sha1, stat_value)
383
511
            except errors.ExistingContent:
395
523
                # carry over:
396
524
                ie.revision = parent_entry.revision
397
525
                return self._get_delta(ie, basis_inv, path), False, None
398
 
            lines = []
399
 
            self._add_text_to_weave(ie.file_id, lines, heads, None)
 
526
            self._add_text_to_weave(ie.file_id, '', heads, None)
400
527
        elif kind == 'symlink':
401
528
            current_link_target = content_summary[3]
402
529
            if not store:
410
537
                ie.symlink_target = parent_entry.symlink_target
411
538
                return self._get_delta(ie, basis_inv, path), False, None
412
539
            ie.symlink_target = current_link_target
413
 
            lines = []
414
 
            self._add_text_to_weave(ie.file_id, lines, heads, None)
 
540
            self._add_text_to_weave(ie.file_id, '', heads, None)
415
541
        elif kind == 'tree-reference':
416
542
            if not store:
417
543
                if content_summary[3] != parent_entry.reference_revision:
422
548
                ie.revision = parent_entry.revision
423
549
                return self._get_delta(ie, basis_inv, path), False, None
424
550
            ie.reference_revision = content_summary[3]
425
 
            lines = []
426
 
            self._add_text_to_weave(ie.file_id, lines, heads, None)
 
551
            if ie.reference_revision is None:
 
552
                raise AssertionError("invalid content_summary for nested tree: %r"
 
553
                    % (content_summary,))
 
554
            self._add_text_to_weave(ie.file_id, '', heads, None)
427
555
        else:
428
556
            raise NotImplementedError('unknown kind')
429
557
        ie.revision = self._new_revision_id
 
558
        self._any_changes = True
430
559
        return self._get_delta(ie, basis_inv, path), True, fingerprint
431
560
 
432
 
    def _add_text_to_weave(self, file_id, new_lines, parents, nostore_sha):
433
 
        # Note: as we read the content directly from the tree, we know its not
434
 
        # been turned into unicode or badly split - but a broken tree
435
 
        # implementation could give us bad output from readlines() so this is
436
 
        # not a guarantee of safety. What would be better is always checking
437
 
        # the content during test suite execution. RBC 20070912
438
 
        parent_keys = tuple((file_id, parent) for parent in parents)
439
 
        return self.repository.texts.add_lines(
440
 
            (file_id, self._new_revision_id), parent_keys, new_lines,
441
 
            nostore_sha=nostore_sha, random_id=self.random_revid,
442
 
            check_content=False)[0:2]
 
561
    def record_iter_changes(self, tree, basis_revision_id, iter_changes,
 
562
        _entry_factory=entry_factory):
 
563
        """Record a new tree via iter_changes.
 
564
 
 
565
        :param tree: The tree to obtain text contents from for changed objects.
 
566
        :param basis_revision_id: The revision id of the tree the iter_changes
 
567
            has been generated against. Currently assumed to be the same
 
568
            as self.parents[0] - if it is not, errors may occur.
 
569
        :param iter_changes: An iter_changes iterator with the changes to apply
 
570
            to basis_revision_id. The iterator must not include any items with
 
571
            a current kind of None - missing items must be either filtered out
 
572
            or errored-on beefore record_iter_changes sees the item.
 
573
        :param _entry_factory: Private method to bind entry_factory locally for
 
574
            performance.
 
575
        :return: A generator of (file_id, relpath, fs_hash) tuples for use with
 
576
            tree._observed_sha1.
 
577
        """
 
578
        # Create an inventory delta based on deltas between all the parents and
 
579
        # deltas between all the parent inventories. We use inventory delta's 
 
580
        # between the inventory objects because iter_changes masks
 
581
        # last-changed-field only changes.
 
582
        # Working data:
 
583
        # file_id -> change map, change is fileid, paths, changed, versioneds,
 
584
        # parents, names, kinds, executables
 
585
        merged_ids = {}
 
586
        # {file_id -> revision_id -> inventory entry, for entries in parent
 
587
        # trees that are not parents[0]
 
588
        parent_entries = {}
 
589
        ghost_basis = False
 
590
        try:
 
591
            revtrees = list(self.repository.revision_trees(self.parents))
 
592
        except errors.NoSuchRevision:
 
593
            # one or more ghosts, slow path.
 
594
            revtrees = []
 
595
            for revision_id in self.parents:
 
596
                try:
 
597
                    revtrees.append(self.repository.revision_tree(revision_id))
 
598
                except errors.NoSuchRevision:
 
599
                    if not revtrees:
 
600
                        basis_revision_id = _mod_revision.NULL_REVISION
 
601
                        ghost_basis = True
 
602
                    revtrees.append(self.repository.revision_tree(
 
603
                        _mod_revision.NULL_REVISION))
 
604
        # The basis inventory from a repository 
 
605
        if revtrees:
 
606
            basis_inv = revtrees[0].inventory
 
607
        else:
 
608
            basis_inv = self.repository.revision_tree(
 
609
                _mod_revision.NULL_REVISION).inventory
 
610
        if len(self.parents) > 0:
 
611
            if basis_revision_id != self.parents[0] and not ghost_basis:
 
612
                raise Exception(
 
613
                    "arbitrary basis parents not yet supported with merges")
 
614
            for revtree in revtrees[1:]:
 
615
                for change in revtree.inventory._make_delta(basis_inv):
 
616
                    if change[1] is None:
 
617
                        # Not present in this parent.
 
618
                        continue
 
619
                    if change[2] not in merged_ids:
 
620
                        if change[0] is not None:
 
621
                            basis_entry = basis_inv[change[2]]
 
622
                            merged_ids[change[2]] = [
 
623
                                # basis revid
 
624
                                basis_entry.revision,
 
625
                                # new tree revid
 
626
                                change[3].revision]
 
627
                            parent_entries[change[2]] = {
 
628
                                # basis parent
 
629
                                basis_entry.revision:basis_entry,
 
630
                                # this parent 
 
631
                                change[3].revision:change[3],
 
632
                                }
 
633
                        else:
 
634
                            merged_ids[change[2]] = [change[3].revision]
 
635
                            parent_entries[change[2]] = {change[3].revision:change[3]}
 
636
                    else:
 
637
                        merged_ids[change[2]].append(change[3].revision)
 
638
                        parent_entries[change[2]][change[3].revision] = change[3]
 
639
        else:
 
640
            merged_ids = {}
 
641
        # Setup the changes from the tree:
 
642
        # changes maps file_id -> (change, [parent revision_ids])
 
643
        changes= {}
 
644
        for change in iter_changes:
 
645
            # This probably looks up in basis_inv way to much.
 
646
            if change[1][0] is not None:
 
647
                head_candidate = [basis_inv[change[0]].revision]
 
648
            else:
 
649
                head_candidate = []
 
650
            changes[change[0]] = change, merged_ids.get(change[0],
 
651
                head_candidate)
 
652
        unchanged_merged = set(merged_ids) - set(changes)
 
653
        # Extend the changes dict with synthetic changes to record merges of
 
654
        # texts.
 
655
        for file_id in unchanged_merged:
 
656
            # Record a merged version of these items that did not change vs the
 
657
            # basis. This can be either identical parallel changes, or a revert
 
658
            # of a specific file after a merge. The recorded content will be
 
659
            # that of the current tree (which is the same as the basis), but
 
660
            # the per-file graph will reflect a merge.
 
661
            # NB:XXX: We are reconstructing path information we had, this
 
662
            # should be preserved instead.
 
663
            # inv delta  change: (file_id, (path_in_source, path_in_target),
 
664
            #   changed_content, versioned, parent, name, kind,
 
665
            #   executable)
 
666
            try:
 
667
                basis_entry = basis_inv[file_id]
 
668
            except errors.NoSuchId:
 
669
                # a change from basis->some_parents but file_id isn't in basis
 
670
                # so was new in the merge, which means it must have changed
 
671
                # from basis -> current, and as it hasn't the add was reverted
 
672
                # by the user. So we discard this change.
 
673
                pass
 
674
            else:
 
675
                change = (file_id,
 
676
                    (basis_inv.id2path(file_id), tree.id2path(file_id)),
 
677
                    False, (True, True),
 
678
                    (basis_entry.parent_id, basis_entry.parent_id),
 
679
                    (basis_entry.name, basis_entry.name),
 
680
                    (basis_entry.kind, basis_entry.kind),
 
681
                    (basis_entry.executable, basis_entry.executable))
 
682
                changes[file_id] = (change, merged_ids[file_id])
 
683
        # changes contains tuples with the change and a set of inventory
 
684
        # candidates for the file.
 
685
        # inv delta is:
 
686
        # old_path, new_path, file_id, new_inventory_entry
 
687
        seen_root = False # Is the root in the basis delta?
 
688
        inv_delta = self._basis_delta
 
689
        modified_rev = self._new_revision_id
 
690
        for change, head_candidates in changes.values():
 
691
            if change[3][1]: # versioned in target.
 
692
                # Several things may be happening here:
 
693
                # We may have a fork in the per-file graph
 
694
                #  - record a change with the content from tree
 
695
                # We may have a change against < all trees  
 
696
                #  - carry over the tree that hasn't changed
 
697
                # We may have a change against all trees
 
698
                #  - record the change with the content from tree
 
699
                kind = change[6][1]
 
700
                file_id = change[0]
 
701
                entry = _entry_factory[kind](file_id, change[5][1],
 
702
                    change[4][1])
 
703
                head_set = self._heads(change[0], set(head_candidates))
 
704
                heads = []
 
705
                # Preserve ordering.
 
706
                for head_candidate in head_candidates:
 
707
                    if head_candidate in head_set:
 
708
                        heads.append(head_candidate)
 
709
                        head_set.remove(head_candidate)
 
710
                carried_over = False
 
711
                if len(heads) == 1:
 
712
                    # Could be a carry-over situation:
 
713
                    parent_entry_revs = parent_entries.get(file_id, None)
 
714
                    if parent_entry_revs:
 
715
                        parent_entry = parent_entry_revs.get(heads[0], None)
 
716
                    else:
 
717
                        parent_entry = None
 
718
                    if parent_entry is None:
 
719
                        # The parent iter_changes was called against is the one
 
720
                        # that is the per-file head, so any change is relevant
 
721
                        # iter_changes is valid.
 
722
                        carry_over_possible = False
 
723
                    else:
 
724
                        # could be a carry over situation
 
725
                        # A change against the basis may just indicate a merge,
 
726
                        # we need to check the content against the source of the
 
727
                        # merge to determine if it was changed after the merge
 
728
                        # or carried over.
 
729
                        if (parent_entry.kind != entry.kind or
 
730
                            parent_entry.parent_id != entry.parent_id or
 
731
                            parent_entry.name != entry.name):
 
732
                            # Metadata common to all entries has changed
 
733
                            # against per-file parent
 
734
                            carry_over_possible = False
 
735
                        else:
 
736
                            carry_over_possible = True
 
737
                        # per-type checks for changes against the parent_entry
 
738
                        # are done below.
 
739
                else:
 
740
                    # Cannot be a carry-over situation
 
741
                    carry_over_possible = False
 
742
                # Populate the entry in the delta
 
743
                if kind == 'file':
 
744
                    # XXX: There is still a small race here: If someone reverts the content of a file
 
745
                    # after iter_changes examines and decides it has changed,
 
746
                    # we will unconditionally record a new version even if some
 
747
                    # other process reverts it while commit is running (with
 
748
                    # the revert happening after iter_changes did it's
 
749
                    # examination).
 
750
                    if change[7][1]:
 
751
                        entry.executable = True
 
752
                    else:
 
753
                        entry.executable = False
 
754
                    if (carry_over_possible and
 
755
                        parent_entry.executable == entry.executable):
 
756
                            # Check the file length, content hash after reading
 
757
                            # the file.
 
758
                            nostore_sha = parent_entry.text_sha1
 
759
                    else:
 
760
                        nostore_sha = None
 
761
                    file_obj, stat_value = tree.get_file_with_stat(file_id, change[1][1])
 
762
                    try:
 
763
                        text = file_obj.read()
 
764
                    finally:
 
765
                        file_obj.close()
 
766
                    try:
 
767
                        entry.text_sha1, entry.text_size = self._add_text_to_weave(
 
768
                            file_id, text, heads, nostore_sha)
 
769
                        yield file_id, change[1][1], (entry.text_sha1, stat_value)
 
770
                    except errors.ExistingContent:
 
771
                        # No content change against a carry_over parent
 
772
                        # Perhaps this should also yield a fs hash update?
 
773
                        carried_over = True
 
774
                        entry.text_size = parent_entry.text_size
 
775
                        entry.text_sha1 = parent_entry.text_sha1
 
776
                elif kind == 'symlink':
 
777
                    # Wants a path hint?
 
778
                    entry.symlink_target = tree.get_symlink_target(file_id)
 
779
                    if (carry_over_possible and
 
780
                        parent_entry.symlink_target == entry.symlink_target):
 
781
                        carried_over = True
 
782
                    else:
 
783
                        self._add_text_to_weave(change[0], '', heads, None)
 
784
                elif kind == 'directory':
 
785
                    if carry_over_possible:
 
786
                        carried_over = True
 
787
                    else:
 
788
                        # Nothing to set on the entry.
 
789
                        # XXX: split into the Root and nonRoot versions.
 
790
                        if change[1][1] != '' or self.repository.supports_rich_root():
 
791
                            self._add_text_to_weave(change[0], '', heads, None)
 
792
                elif kind == 'tree-reference':
 
793
                    if not self.repository._format.supports_tree_reference:
 
794
                        # This isn't quite sane as an error, but we shouldn't
 
795
                        # ever see this code path in practice: tree's don't
 
796
                        # permit references when the repo doesn't support tree
 
797
                        # references.
 
798
                        raise errors.UnsupportedOperation(tree.add_reference,
 
799
                            self.repository)
 
800
                    reference_revision = tree.get_reference_revision(change[0])
 
801
                    entry.reference_revision = reference_revision
 
802
                    if (carry_over_possible and
 
803
                        parent_entry.reference_revision == reference_revision):
 
804
                        carried_over = True
 
805
                    else:
 
806
                        self._add_text_to_weave(change[0], '', heads, None)
 
807
                else:
 
808
                    raise AssertionError('unknown kind %r' % kind)
 
809
                if not carried_over:
 
810
                    entry.revision = modified_rev
 
811
                else:
 
812
                    entry.revision = parent_entry.revision
 
813
            else:
 
814
                entry = None
 
815
            new_path = change[1][1]
 
816
            inv_delta.append((change[1][0], new_path, change[0], entry))
 
817
            if new_path == '':
 
818
                seen_root = True
 
819
        self.new_inventory = None
 
820
        if len(inv_delta):
 
821
            # This should perhaps be guarded by a check that the basis we
 
822
            # commit against is the basis for the commit and if not do a delta
 
823
            # against the basis.
 
824
            self._any_changes = True
 
825
        if not seen_root:
 
826
            # housekeeping root entry changes do not affect no-change commits.
 
827
            self._require_root_change(tree)
 
828
        self.basis_delta_revision = basis_revision_id
 
829
 
 
830
    def _add_text_to_weave(self, file_id, new_text, parents, nostore_sha):
 
831
        parent_keys = tuple([(file_id, parent) for parent in parents])
 
832
        return self.repository.texts._add_text(
 
833
            (file_id, self._new_revision_id), parent_keys, new_text,
 
834
            nostore_sha=nostore_sha, random_id=self.random_revid)[0:2]
443
835
 
444
836
 
445
837
class RootCommitBuilder(CommitBuilder):
446
838
    """This commitbuilder actually records the root id"""
447
 
    
 
839
 
448
840
    # the root entry gets versioned properly by this builder.
449
841
    _versioned_root = True
450
842
 
457
849
        :param tree: The tree that is being committed.
458
850
        """
459
851
 
 
852
    def _require_root_change(self, tree):
 
853
        """Enforce an appropriate root object change.
 
854
 
 
855
        This is called once when record_iter_changes is called, if and only if
 
856
        the root was not in the delta calculated by record_iter_changes.
 
857
 
 
858
        :param tree: The tree which is being committed.
 
859
        """
 
860
        # versioned roots do not change unless the tree found a change.
 
861
 
460
862
 
461
863
######################################################################
462
864
# Repositories
463
865
 
464
 
class Repository(object):
 
866
 
 
867
class Repository(_RelockDebugMixin):
465
868
    """Repository holding history for one or more branches.
466
869
 
467
870
    The repository holds and retrieves historical information including
469
872
    which views a particular line of development through that history.
470
873
 
471
874
    The Repository builds on top of some byte storage facilies (the revisions,
472
 
    signatures, inventories and texts attributes) and a Transport, which
473
 
    respectively provide byte storage and a means to access the (possibly
 
875
    signatures, inventories, texts and chk_bytes attributes) and a Transport,
 
876
    which respectively provide byte storage and a means to access the (possibly
474
877
    remote) disk.
475
878
 
476
879
    The byte storage facilities are addressed via tuples, which we refer to
477
880
    as 'keys' throughout the code base. Revision_keys, inventory_keys and
478
881
    signature_keys are all 1-tuples: (revision_id,). text_keys are two-tuples:
479
 
    (file_id, revision_id). We use this interface because it allows low
480
 
    friction with the underlying code that implements disk indices, network
481
 
    encoding and other parts of bzrlib.
 
882
    (file_id, revision_id). chk_bytes uses CHK keys - a 1-tuple with a single
 
883
    byte string made up of a hash identifier and a hash value.
 
884
    We use this interface because it allows low friction with the underlying
 
885
    code that implements disk indices, network encoding and other parts of
 
886
    bzrlib.
482
887
 
483
888
    :ivar revisions: A bzrlib.versionedfile.VersionedFiles instance containing
484
889
        the serialised revisions for the repository. This can be used to obtain
503
908
        The result of trying to insert data into the repository via this store
504
909
        is undefined: it should be considered read-only except for implementors
505
910
        of repositories.
 
911
    :ivar chk_bytes: A bzrlib.versionedfile.VersionedFiles instance containing
 
912
        any data the repository chooses to store or have indexed by its hash.
 
913
        The result of trying to insert data into the repository via this store
 
914
        is undefined: it should be considered read-only except for implementors
 
915
        of repositories.
506
916
    :ivar _transport: Transport for file access to repository, typically
507
917
        pointing to .bzr/repository.
508
918
    """
518
928
        r'.* revision="(?P<revision_id>[^"]+)"'
519
929
        )
520
930
 
521
 
    def abort_write_group(self):
 
931
    def abort_write_group(self, suppress_errors=False):
522
932
        """Commit the contents accrued within the current write group.
523
933
 
 
934
        :param suppress_errors: if true, abort_write_group will catch and log
 
935
            unexpected errors that happen during the abort, rather than
 
936
            allowing them to propagate.  Defaults to False.
 
937
 
524
938
        :seealso: start_write_group.
525
939
        """
526
940
        if self._write_group is not self.get_transaction():
527
941
            # has an unlock or relock occured ?
528
 
            raise errors.BzrError('mismatched lock context and write group.')
529
 
        self._abort_write_group()
 
942
            if suppress_errors:
 
943
                mutter(
 
944
                '(suppressed) mismatched lock context and write group. %r, %r',
 
945
                self._write_group, self.get_transaction())
 
946
                return
 
947
            raise errors.BzrError(
 
948
                'mismatched lock context and write group. %r, %r' %
 
949
                (self._write_group, self.get_transaction()))
 
950
        try:
 
951
            self._abort_write_group()
 
952
        except Exception, exc:
 
953
            self._write_group = None
 
954
            if not suppress_errors:
 
955
                raise
 
956
            mutter('abort_write_group failed')
 
957
            log_exception_quietly()
 
958
            note('bzr: ERROR (ignored): %s', exc)
530
959
        self._write_group = None
531
960
 
532
961
    def _abort_write_group(self):
533
962
        """Template method for per-repository write group cleanup.
534
 
        
535
 
        This is called during abort before the write group is considered to be 
 
963
 
 
964
        This is called during abort before the write group is considered to be
536
965
        finished and should cleanup any internal state accrued during the write
537
966
        group. There is no requirement that data handed to the repository be
538
967
        *not* made available - this is not a rollback - but neither should any
544
973
 
545
974
    def add_fallback_repository(self, repository):
546
975
        """Add a repository to use for looking up data not held locally.
547
 
        
 
976
 
548
977
        :param repository: A repository.
549
978
        """
550
979
        if not self._format.supports_external_lookups:
551
980
            raise errors.UnstackableRepositoryFormat(self._format, self.base)
 
981
        if self.is_locked():
 
982
            # This repository will call fallback.unlock() when we transition to
 
983
            # the unlocked state, so we make sure to increment the lock count
 
984
            repository.lock_read()
552
985
        self._check_fallback_repository(repository)
553
986
        self._fallback_repositories.append(repository)
554
987
        self.texts.add_fallback_versioned_files(repository.texts)
555
988
        self.inventories.add_fallback_versioned_files(repository.inventories)
556
989
        self.revisions.add_fallback_versioned_files(repository.revisions)
557
990
        self.signatures.add_fallback_versioned_files(repository.signatures)
 
991
        if self.chk_bytes is not None:
 
992
            self.chk_bytes.add_fallback_versioned_files(repository.chk_bytes)
558
993
 
559
994
    def _check_fallback_repository(self, repository):
560
995
        """Check that this repository can fallback to repository safely.
561
996
 
562
997
        Raise an error if not.
563
 
        
 
998
 
564
999
        :param repository: A repository to fallback to.
565
1000
        """
566
1001
        return InterRepository._assert_same_model(self, repository)
567
1002
 
568
1003
    def add_inventory(self, revision_id, inv, parents):
569
1004
        """Add the inventory inv to the repository as revision_id.
570
 
        
 
1005
 
571
1006
        :param parents: The revision ids of the parents that revision_id
572
1007
                        is known to have and are in the repository already.
573
1008
 
584
1019
                % (inv.revision_id, revision_id))
585
1020
        if inv.root is None:
586
1021
            raise AssertionError()
587
 
        inv_lines = self._serialise_inventory_to_lines(inv)
 
1022
        return self._add_inventory_checked(revision_id, inv, parents)
 
1023
 
 
1024
    def _add_inventory_checked(self, revision_id, inv, parents):
 
1025
        """Add inv to the repository after checking the inputs.
 
1026
 
 
1027
        This function can be overridden to allow different inventory styles.
 
1028
 
 
1029
        :seealso: add_inventory, for the contract.
 
1030
        """
 
1031
        inv_lines = self._serializer.write_inventory_to_lines(inv)
588
1032
        return self._inventory_add_lines(revision_id, parents,
589
1033
            inv_lines, check_content=False)
590
1034
 
 
1035
    def add_inventory_by_delta(self, basis_revision_id, delta, new_revision_id,
 
1036
                               parents, basis_inv=None, propagate_caches=False):
 
1037
        """Add a new inventory expressed as a delta against another revision.
 
1038
 
 
1039
        See the inventory developers documentation for the theory behind
 
1040
        inventory deltas.
 
1041
 
 
1042
        :param basis_revision_id: The inventory id the delta was created
 
1043
            against. (This does not have to be a direct parent.)
 
1044
        :param delta: The inventory delta (see Inventory.apply_delta for
 
1045
            details).
 
1046
        :param new_revision_id: The revision id that the inventory is being
 
1047
            added for.
 
1048
        :param parents: The revision ids of the parents that revision_id is
 
1049
            known to have and are in the repository already. These are supplied
 
1050
            for repositories that depend on the inventory graph for revision
 
1051
            graph access, as well as for those that pun ancestry with delta
 
1052
            compression.
 
1053
        :param basis_inv: The basis inventory if it is already known,
 
1054
            otherwise None.
 
1055
        :param propagate_caches: If True, the caches for this inventory are
 
1056
          copied to and updated for the result if possible.
 
1057
 
 
1058
        :returns: (validator, new_inv)
 
1059
            The validator(which is a sha1 digest, though what is sha'd is
 
1060
            repository format specific) of the serialized inventory, and the
 
1061
            resulting inventory.
 
1062
        """
 
1063
        if not self.is_in_write_group():
 
1064
            raise AssertionError("%r not in write group" % (self,))
 
1065
        _mod_revision.check_not_reserved_id(new_revision_id)
 
1066
        basis_tree = self.revision_tree(basis_revision_id)
 
1067
        basis_tree.lock_read()
 
1068
        try:
 
1069
            # Note that this mutates the inventory of basis_tree, which not all
 
1070
            # inventory implementations may support: A better idiom would be to
 
1071
            # return a new inventory, but as there is no revision tree cache in
 
1072
            # repository this is safe for now - RBC 20081013
 
1073
            if basis_inv is None:
 
1074
                basis_inv = basis_tree.inventory
 
1075
            basis_inv.apply_delta(delta)
 
1076
            basis_inv.revision_id = new_revision_id
 
1077
            return (self.add_inventory(new_revision_id, basis_inv, parents),
 
1078
                    basis_inv)
 
1079
        finally:
 
1080
            basis_tree.unlock()
 
1081
 
591
1082
    def _inventory_add_lines(self, revision_id, parents, lines,
592
1083
        check_content=True):
593
1084
        """Store lines in inv_vf and return the sha1 of the inventory."""
594
1085
        parents = [(parent,) for parent in parents]
595
 
        return self.inventories.add_lines((revision_id,), parents, lines,
 
1086
        result = self.inventories.add_lines((revision_id,), parents, lines,
596
1087
            check_content=check_content)[0]
 
1088
        self.inventories._access.flush()
 
1089
        return result
597
1090
 
598
1091
    def add_revision(self, revision_id, rev, inv=None, config=None):
599
1092
        """Add rev to the revision store as revision_id.
636
1129
        self.revisions.add_lines(key, parents, osutils.split_lines(text))
637
1130
 
638
1131
    def all_revision_ids(self):
639
 
        """Returns a list of all the revision ids in the repository. 
 
1132
        """Returns a list of all the revision ids in the repository.
640
1133
 
641
1134
        This is conceptually deprecated because code should generally work on
642
1135
        the graph reachable from a particular revision, and ignore any other
648
1141
        return self._all_revision_ids()
649
1142
 
650
1143
    def _all_revision_ids(self):
651
 
        """Returns a list of all the revision ids in the repository. 
 
1144
        """Returns a list of all the revision ids in the repository.
652
1145
 
653
 
        These are in as much topological order as the underlying store can 
 
1146
        These are in as much topological order as the underlying store can
654
1147
        present.
655
1148
        """
656
1149
        raise NotImplementedError(self._all_revision_ids)
675
1168
        # The old API returned a list, should this actually be a set?
676
1169
        return parent_map.keys()
677
1170
 
 
1171
    def _check_inventories(self, checker):
 
1172
        """Check the inventories found from the revision scan.
 
1173
        
 
1174
        This is responsible for verifying the sha1 of inventories and
 
1175
        creating a pending_keys set that covers data referenced by inventories.
 
1176
        """
 
1177
        bar = ui.ui_factory.nested_progress_bar()
 
1178
        try:
 
1179
            self._do_check_inventories(checker, bar)
 
1180
        finally:
 
1181
            bar.finished()
 
1182
 
 
1183
    def _do_check_inventories(self, checker, bar):
 
1184
        """Helper for _check_inventories."""
 
1185
        revno = 0
 
1186
        keys = {'chk_bytes':set(), 'inventories':set(), 'texts':set()}
 
1187
        kinds = ['chk_bytes', 'texts']
 
1188
        count = len(checker.pending_keys)
 
1189
        bar.update("inventories", 0, 2)
 
1190
        current_keys = checker.pending_keys
 
1191
        checker.pending_keys = {}
 
1192
        # Accumulate current checks.
 
1193
        for key in current_keys:
 
1194
            if key[0] != 'inventories' and key[0] not in kinds:
 
1195
                checker._report_items.append('unknown key type %r' % (key,))
 
1196
            keys[key[0]].add(key[1:])
 
1197
        if keys['inventories']:
 
1198
            # NB: output order *should* be roughly sorted - topo or
 
1199
            # inverse topo depending on repository - either way decent
 
1200
            # to just delta against. However, pre-CHK formats didn't
 
1201
            # try to optimise inventory layout on disk. As such the
 
1202
            # pre-CHK code path does not use inventory deltas.
 
1203
            last_object = None
 
1204
            for record in self.inventories.check(keys=keys['inventories']):
 
1205
                if record.storage_kind == 'absent':
 
1206
                    checker._report_items.append(
 
1207
                        'Missing inventory {%s}' % (record.key,))
 
1208
                else:
 
1209
                    last_object = self._check_record('inventories', record,
 
1210
                        checker, last_object,
 
1211
                        current_keys[('inventories',) + record.key])
 
1212
            del keys['inventories']
 
1213
        else:
 
1214
            return
 
1215
        bar.update("texts", 1)
 
1216
        while (checker.pending_keys or keys['chk_bytes']
 
1217
            or keys['texts']):
 
1218
            # Something to check.
 
1219
            current_keys = checker.pending_keys
 
1220
            checker.pending_keys = {}
 
1221
            # Accumulate current checks.
 
1222
            for key in current_keys:
 
1223
                if key[0] not in kinds:
 
1224
                    checker._report_items.append('unknown key type %r' % (key,))
 
1225
                keys[key[0]].add(key[1:])
 
1226
            # Check the outermost kind only - inventories || chk_bytes || texts
 
1227
            for kind in kinds:
 
1228
                if keys[kind]:
 
1229
                    last_object = None
 
1230
                    for record in getattr(self, kind).check(keys=keys[kind]):
 
1231
                        if record.storage_kind == 'absent':
 
1232
                            checker._report_items.append(
 
1233
                                'Missing %s {%s}' % (kind, record.key,))
 
1234
                        else:
 
1235
                            last_object = self._check_record(kind, record,
 
1236
                                checker, last_object, current_keys[(kind,) + record.key])
 
1237
                    keys[kind] = set()
 
1238
                    break
 
1239
 
 
1240
    def _check_record(self, kind, record, checker, last_object, item_data):
 
1241
        """Check a single text from this repository."""
 
1242
        if kind == 'inventories':
 
1243
            rev_id = record.key[0]
 
1244
            inv = self._deserialise_inventory(rev_id,
 
1245
                record.get_bytes_as('fulltext'))
 
1246
            if last_object is not None:
 
1247
                delta = inv._make_delta(last_object)
 
1248
                for old_path, path, file_id, ie in delta:
 
1249
                    if ie is None:
 
1250
                        continue
 
1251
                    ie.check(checker, rev_id, inv)
 
1252
            else:
 
1253
                for path, ie in inv.iter_entries():
 
1254
                    ie.check(checker, rev_id, inv)
 
1255
            if self._format.fast_deltas:
 
1256
                return inv
 
1257
        elif kind == 'chk_bytes':
 
1258
            # No code written to check chk_bytes for this repo format.
 
1259
            checker._report_items.append(
 
1260
                'unsupported key type chk_bytes for %s' % (record.key,))
 
1261
        elif kind == 'texts':
 
1262
            self._check_text(record, checker, item_data)
 
1263
        else:
 
1264
            checker._report_items.append(
 
1265
                'unknown key type %s for %s' % (kind, record.key))
 
1266
 
 
1267
    def _check_text(self, record, checker, item_data):
 
1268
        """Check a single text."""
 
1269
        # Check it is extractable.
 
1270
        # TODO: check length.
 
1271
        if record.storage_kind == 'chunked':
 
1272
            chunks = record.get_bytes_as(record.storage_kind)
 
1273
            sha1 = osutils.sha_strings(chunks)
 
1274
            length = sum(map(len, chunks))
 
1275
        else:
 
1276
            content = record.get_bytes_as('fulltext')
 
1277
            sha1 = osutils.sha_string(content)
 
1278
            length = len(content)
 
1279
        if item_data and sha1 != item_data[1]:
 
1280
            checker._report_items.append(
 
1281
                'sha1 mismatch: %s has sha1 %s expected %s referenced by %s' %
 
1282
                (record.key, sha1, item_data[1], item_data[2]))
 
1283
 
678
1284
    @staticmethod
679
1285
    def create(a_bzrdir):
680
1286
        """Construct the current default format repository in a_bzrdir."""
701
1307
        self._reconcile_does_inventory_gc = True
702
1308
        self._reconcile_fixes_text_parents = False
703
1309
        self._reconcile_backsup_inventory = True
704
 
        # not right yet - should be more semantically clear ? 
705
 
        # 
706
 
        # TODO: make sure to construct the right store classes, etc, depending
707
 
        # on whether escaping is required.
708
 
        self._warn_if_deprecated()
709
1310
        self._write_group = None
710
1311
        # Additional places to query for data.
711
1312
        self._fallback_repositories = []
712
 
        # What order should fetch operations request streams in?
713
 
        # The default is unordered as that is the cheapest for an origin to
714
 
        # provide.
715
 
        self._fetch_order = 'unordered'
716
 
        # Does this repository use deltas that can be fetched as-deltas ?
717
 
        # (E.g. knits, where the knit deltas can be transplanted intact.
718
 
        # We default to False, which will ensure that enough data to get
719
 
        # a full text out of any fetch stream will be grabbed.
720
 
        self._fetch_uses_deltas = False
721
 
        # Should fetch trigger a reconcile after the fetch? Only needed for
722
 
        # some repository formats that can suffer internal inconsistencies.
723
 
        self._fetch_reconcile = False
 
1313
        # An InventoryEntry cache, used during deserialization
 
1314
        self._inventory_entry_cache = fifo_cache.FIFOCache(10*1024)
 
1315
        # Is it safe to return inventory entries directly from the entry cache,
 
1316
        # rather copying them?
 
1317
        self._safe_to_return_from_cache = False
724
1318
 
725
1319
    def __repr__(self):
726
 
        return '%s(%r)' % (self.__class__.__name__,
727
 
                           self.base)
 
1320
        if self._fallback_repositories:
 
1321
            return '%s(%r, fallback_repositories=%r)' % (
 
1322
                self.__class__.__name__,
 
1323
                self.base,
 
1324
                self._fallback_repositories)
 
1325
        else:
 
1326
            return '%s(%r)' % (self.__class__.__name__,
 
1327
                               self.base)
 
1328
 
 
1329
    def _has_same_fallbacks(self, other_repo):
 
1330
        """Returns true if the repositories have the same fallbacks."""
 
1331
        my_fb = self._fallback_repositories
 
1332
        other_fb = other_repo._fallback_repositories
 
1333
        if len(my_fb) != len(other_fb):
 
1334
            return False
 
1335
        for f, g in zip(my_fb, other_fb):
 
1336
            if not f.has_same_location(g):
 
1337
                return False
 
1338
        return True
728
1339
 
729
1340
    def has_same_location(self, other):
730
1341
        """Returns a boolean indicating if this repository is at the same
757
1368
        This causes caching within the repository obejct to start accumlating
758
1369
        data during reads, and allows a 'write_group' to be obtained. Write
759
1370
        groups must be used for actual data insertion.
760
 
        
 
1371
 
761
1372
        :param token: if this is already locked, then lock_write will fail
762
1373
            unless the token matches the existing lock.
763
1374
        :returns: a token if this instance supports tokens, otherwise None.
773
1384
 
774
1385
        XXX: this docstring is duplicated in many places, e.g. lockable_files.py
775
1386
        """
 
1387
        locked = self.is_locked()
776
1388
        result = self.control_files.lock_write(token=token)
777
 
        for repo in self._fallback_repositories:
778
 
            # Writes don't affect fallback repos
779
 
            repo.lock_read()
780
 
        self._refresh_data()
 
1389
        if not locked:
 
1390
            self._warn_if_deprecated()
 
1391
            self._note_lock('w')
 
1392
            for repo in self._fallback_repositories:
 
1393
                # Writes don't affect fallback repos
 
1394
                repo.lock_read()
 
1395
            self._refresh_data()
781
1396
        return result
782
1397
 
783
1398
    def lock_read(self):
 
1399
        locked = self.is_locked()
784
1400
        self.control_files.lock_read()
785
 
        for repo in self._fallback_repositories:
786
 
            repo.lock_read()
787
 
        self._refresh_data()
 
1401
        if not locked:
 
1402
            self._warn_if_deprecated()
 
1403
            self._note_lock('r')
 
1404
            for repo in self._fallback_repositories:
 
1405
                repo.lock_read()
 
1406
            self._refresh_data()
788
1407
 
789
1408
    def get_physical_lock_status(self):
790
1409
        return self.control_files.get_physical_lock_status()
792
1411
    def leave_lock_in_place(self):
793
1412
        """Tell this repository not to release the physical lock when this
794
1413
        object is unlocked.
795
 
        
 
1414
 
796
1415
        If lock_write doesn't return a token, then this method is not supported.
797
1416
        """
798
1417
        self.control_files.leave_in_place()
866
1485
        :param using: If True, list only branches using this repository.
867
1486
        """
868
1487
        if using and not self.is_shared():
869
 
            try:
870
 
                return [self.bzrdir.open_branch()]
871
 
            except errors.NotBranchError:
872
 
                return []
 
1488
            return self.bzrdir.list_branches()
873
1489
        class Evaluator(object):
874
1490
 
875
1491
            def __init__(self):
884
1500
                    except errors.NoRepositoryPresent:
885
1501
                        pass
886
1502
                    else:
887
 
                        return False, (None, repository)
 
1503
                        return False, ([], repository)
888
1504
                self.first_call = False
889
 
                try:
890
 
                    value = (bzrdir.open_branch(), None)
891
 
                except errors.NotBranchError:
892
 
                    value = (None, None)
 
1505
                value = (bzrdir.list_branches(), None)
893
1506
                return True, value
894
1507
 
895
 
        branches = []
896
 
        for branch, repository in bzrdir.BzrDir.find_bzrdirs(
 
1508
        ret = []
 
1509
        for branches, repository in bzrdir.BzrDir.find_bzrdirs(
897
1510
                self.bzrdir.root_transport, evaluate=Evaluator()):
898
 
            if branch is not None:
899
 
                branches.append(branch)
 
1511
            if branches is not None:
 
1512
                ret.extend(branches)
900
1513
            if not using and repository is not None:
901
 
                branches.extend(repository.find_branches())
902
 
        return branches
 
1514
                ret.extend(repository.find_branches())
 
1515
        return ret
903
1516
 
904
1517
    @needs_read_lock
905
1518
    def search_missing_revision_ids(self, other, revision_id=None, find_ghosts=True):
906
1519
        """Return the revision ids that other has that this does not.
907
 
        
 
1520
 
908
1521
        These are returned in topological order.
909
1522
 
910
1523
        revision_id: only return revision ids included by revision_id.
912
1525
        return InterRepository.get(other, self).search_missing_revision_ids(
913
1526
            revision_id, find_ghosts)
914
1527
 
915
 
    @deprecated_method(one_two)
916
 
    @needs_read_lock
917
 
    def missing_revision_ids(self, other, revision_id=None, find_ghosts=True):
918
 
        """Return the revision ids that other has that this does not.
919
 
        
920
 
        These are returned in topological order.
921
 
 
922
 
        revision_id: only return revision ids included by revision_id.
923
 
        """
924
 
        keys =  self.search_missing_revision_ids(
925
 
            other, revision_id, find_ghosts).get_keys()
926
 
        other.lock_read()
927
 
        try:
928
 
            parents = other.get_graph().get_parent_map(keys)
929
 
        finally:
930
 
            other.unlock()
931
 
        return tsort.topo_sort(parents)
932
 
 
933
1528
    @staticmethod
934
1529
    def open(base):
935
1530
        """Open the repository rooted at base.
942
1537
 
943
1538
    def copy_content_into(self, destination, revision_id=None):
944
1539
        """Make a complete copy of the content in self into destination.
945
 
        
946
 
        This is a destructive operation! Do not use it on existing 
 
1540
 
 
1541
        This is a destructive operation! Do not use it on existing
947
1542
        repositories.
948
1543
        """
949
1544
        return InterRepository.get(self, destination).copy_content(revision_id)
952
1547
        """Commit the contents accrued within the current write group.
953
1548
 
954
1549
        :seealso: start_write_group.
 
1550
        
 
1551
        :return: it may return an opaque hint that can be passed to 'pack'.
955
1552
        """
956
1553
        if self._write_group is not self.get_transaction():
957
1554
            # has an unlock or relock occured ?
958
1555
            raise errors.BzrError('mismatched lock context %r and '
959
1556
                'write group %r.' %
960
1557
                (self.get_transaction(), self._write_group))
961
 
        self._commit_write_group()
 
1558
        result = self._commit_write_group()
962
1559
        self._write_group = None
 
1560
        return result
963
1561
 
964
1562
    def _commit_write_group(self):
965
1563
        """Template method for per-repository write group cleanup.
966
 
        
967
 
        This is called before the write group is considered to be 
 
1564
 
 
1565
        This is called before the write group is considered to be
968
1566
        finished and should ensure that all data handed to the repository
969
 
        for writing during the write group is safely committed (to the 
 
1567
        for writing during the write group is safely committed (to the
970
1568
        extent possible considering file system caching etc).
971
1569
        """
972
1570
 
973
 
    def fetch(self, source, revision_id=None, pb=None, find_ghosts=False):
 
1571
    def suspend_write_group(self):
 
1572
        raise errors.UnsuspendableWriteGroup(self)
 
1573
 
 
1574
    def get_missing_parent_inventories(self, check_for_missing_texts=True):
 
1575
        """Return the keys of missing inventory parents for revisions added in
 
1576
        this write group.
 
1577
 
 
1578
        A revision is not complete if the inventory delta for that revision
 
1579
        cannot be calculated.  Therefore if the parent inventories of a
 
1580
        revision are not present, the revision is incomplete, and e.g. cannot
 
1581
        be streamed by a smart server.  This method finds missing inventory
 
1582
        parents for revisions added in this write group.
 
1583
        """
 
1584
        if not self._format.supports_external_lookups:
 
1585
            # This is only an issue for stacked repositories
 
1586
            return set()
 
1587
        if not self.is_in_write_group():
 
1588
            raise AssertionError('not in a write group')
 
1589
 
 
1590
        # XXX: We assume that every added revision already has its
 
1591
        # corresponding inventory, so we only check for parent inventories that
 
1592
        # might be missing, rather than all inventories.
 
1593
        parents = set(self.revisions._index.get_missing_parents())
 
1594
        parents.discard(_mod_revision.NULL_REVISION)
 
1595
        unstacked_inventories = self.inventories._index
 
1596
        present_inventories = unstacked_inventories.get_parent_map(
 
1597
            key[-1:] for key in parents)
 
1598
        parents.difference_update(present_inventories)
 
1599
        if len(parents) == 0:
 
1600
            # No missing parent inventories.
 
1601
            return set()
 
1602
        if not check_for_missing_texts:
 
1603
            return set(('inventories', rev_id) for (rev_id,) in parents)
 
1604
        # Ok, now we have a list of missing inventories.  But these only matter
 
1605
        # if the inventories that reference them are missing some texts they
 
1606
        # appear to introduce.
 
1607
        # XXX: Texts referenced by all added inventories need to be present,
 
1608
        # but at the moment we're only checking for texts referenced by
 
1609
        # inventories at the graph's edge.
 
1610
        key_deps = self.revisions._index._key_dependencies
 
1611
        key_deps.satisfy_refs_for_keys(present_inventories)
 
1612
        referrers = frozenset(r[0] for r in key_deps.get_referrers())
 
1613
        file_ids = self.fileids_altered_by_revision_ids(referrers)
 
1614
        missing_texts = set()
 
1615
        for file_id, version_ids in file_ids.iteritems():
 
1616
            missing_texts.update(
 
1617
                (file_id, version_id) for version_id in version_ids)
 
1618
        present_texts = self.texts.get_parent_map(missing_texts)
 
1619
        missing_texts.difference_update(present_texts)
 
1620
        if not missing_texts:
 
1621
            # No texts are missing, so all revisions and their deltas are
 
1622
            # reconstructable.
 
1623
            return set()
 
1624
        # Alternatively the text versions could be returned as the missing
 
1625
        # keys, but this is likely to be less data.
 
1626
        missing_keys = set(('inventories', rev_id) for (rev_id,) in parents)
 
1627
        return missing_keys
 
1628
 
 
1629
    def refresh_data(self):
 
1630
        """Re-read any data needed to to synchronise with disk.
 
1631
 
 
1632
        This method is intended to be called after another repository instance
 
1633
        (such as one used by a smart server) has inserted data into the
 
1634
        repository. It may not be called during a write group, but may be
 
1635
        called at any other time.
 
1636
        """
 
1637
        if self.is_in_write_group():
 
1638
            raise errors.InternalBzrError(
 
1639
                "May not refresh_data while in a write group.")
 
1640
        self._refresh_data()
 
1641
 
 
1642
    def resume_write_group(self, tokens):
 
1643
        if not self.is_write_locked():
 
1644
            raise errors.NotWriteLocked(self)
 
1645
        if self._write_group:
 
1646
            raise errors.BzrError('already in a write group')
 
1647
        self._resume_write_group(tokens)
 
1648
        # so we can detect unlock/relock - the write group is now entered.
 
1649
        self._write_group = self.get_transaction()
 
1650
 
 
1651
    def _resume_write_group(self, tokens):
 
1652
        raise errors.UnsuspendableWriteGroup(self)
 
1653
 
 
1654
    def fetch(self, source, revision_id=None, pb=None, find_ghosts=False,
 
1655
            fetch_spec=None):
974
1656
        """Fetch the content required to construct revision_id from source.
975
1657
 
976
 
        If revision_id is None all content is copied.
 
1658
        If revision_id is None and fetch_spec is None, then all content is
 
1659
        copied.
 
1660
 
 
1661
        fetch() may not be used when the repository is in a write group -
 
1662
        either finish the current write group before using fetch, or use
 
1663
        fetch before starting the write group.
 
1664
 
977
1665
        :param find_ghosts: Find and copy revisions in the source that are
978
1666
            ghosts in the target (and not reachable directly by walking out to
979
1667
            the first-present revision in target from revision_id).
 
1668
        :param revision_id: If specified, all the content needed for this
 
1669
            revision ID will be copied to the target.  Fetch will determine for
 
1670
            itself which content needs to be copied.
 
1671
        :param fetch_spec: If specified, a SearchResult or
 
1672
            PendingAncestryResult that describes which revisions to copy.  This
 
1673
            allows copying multiple heads at once.  Mutually exclusive with
 
1674
            revision_id.
980
1675
        """
 
1676
        if fetch_spec is not None and revision_id is not None:
 
1677
            raise AssertionError(
 
1678
                "fetch_spec and revision_id are mutually exclusive.")
 
1679
        if self.is_in_write_group():
 
1680
            raise errors.InternalBzrError(
 
1681
                "May not fetch while in a write group.")
981
1682
        # fast path same-url fetch operations
982
 
        if self.has_same_location(source):
 
1683
        # TODO: lift out to somewhere common with RemoteRepository
 
1684
        # <https://bugs.edge.launchpad.net/bzr/+bug/401646>
 
1685
        if (self.has_same_location(source)
 
1686
            and fetch_spec is None
 
1687
            and self._has_same_fallbacks(source)):
983
1688
            # check that last_revision is in 'from' and then return a
984
1689
            # no-operation.
985
1690
            if (revision_id is not None and
991
1696
        # IncompatibleRepositories when asked to fetch.
992
1697
        inter = InterRepository.get(source, self)
993
1698
        return inter.fetch(revision_id=revision_id, pb=pb,
994
 
            find_ghosts=find_ghosts)
 
1699
            find_ghosts=find_ghosts, fetch_spec=fetch_spec)
995
1700
 
996
1701
    def create_bundle(self, target, base, fileobj, format=None):
997
1702
        return serializer.write_bundle(self, target, base, fileobj, format)
1000
1705
                           timezone=None, committer=None, revprops=None,
1001
1706
                           revision_id=None):
1002
1707
        """Obtain a CommitBuilder for this repository.
1003
 
        
 
1708
 
1004
1709
        :param branch: Branch to commit to.
1005
1710
        :param parents: Revision ids of the parents of the new revision.
1006
1711
        :param config: Configuration to use.
1010
1715
        :param revprops: Optional dictionary of revision properties.
1011
1716
        :param revision_id: Optional revision id.
1012
1717
        """
 
1718
        if self._fallback_repositories:
 
1719
            raise errors.BzrError("Cannot commit from a lightweight checkout "
 
1720
                "to a stacked branch. See "
 
1721
                "https://bugs.launchpad.net/bzr/+bug/375013 for details.")
1013
1722
        result = self._commit_builder_class(self, parents, config,
1014
1723
            timestamp, timezone, committer, revprops, revision_id)
1015
1724
        self.start_write_group()
1016
1725
        return result
1017
1726
 
 
1727
    @only_raises(errors.LockNotHeld, errors.LockBroken)
1018
1728
    def unlock(self):
1019
1729
        if (self.control_files._lock_count == 1 and
1020
1730
            self.control_files._lock_mode == 'w'):
1024
1734
                raise errors.BzrError(
1025
1735
                    'Must end write groups before releasing write locks.')
1026
1736
        self.control_files.unlock()
1027
 
        for repo in self._fallback_repositories:
1028
 
            repo.unlock()
 
1737
        if self.control_files._lock_count == 0:
 
1738
            self._inventory_entry_cache.clear()
 
1739
            for repo in self._fallback_repositories:
 
1740
                repo.unlock()
1029
1741
 
1030
1742
    @needs_read_lock
1031
1743
    def clone(self, a_bzrdir, revision_id=None):
1066
1778
 
1067
1779
    def _start_write_group(self):
1068
1780
        """Template method for per-repository write group startup.
1069
 
        
1070
 
        This is called before the write group is considered to be 
 
1781
 
 
1782
        This is called before the write group is considered to be
1071
1783
        entered.
1072
1784
        """
1073
1785
 
1094
1806
                dest_repo = a_bzrdir.open_repository()
1095
1807
        return dest_repo
1096
1808
 
 
1809
    def _get_sink(self):
 
1810
        """Return a sink for streaming into this repository."""
 
1811
        return StreamSink(self)
 
1812
 
 
1813
    def _get_source(self, to_format):
 
1814
        """Return a source for streaming from this repository."""
 
1815
        return StreamSource(self, to_format)
 
1816
 
1097
1817
    @needs_read_lock
1098
1818
    def has_revision(self, revision_id):
1099
1819
        """True if this repository has a copy of the revision."""
1122
1842
    @needs_read_lock
1123
1843
    def get_revision_reconcile(self, revision_id):
1124
1844
        """'reconcile' helper routine that allows access to a revision always.
1125
 
        
 
1845
 
1126
1846
        This variant of get_revision does not cross check the weave graph
1127
1847
        against the revision one as get_revision does: but it should only
1128
1848
        be used by reconcile, or reconcile-alike commands that are correcting
1132
1852
 
1133
1853
    @needs_read_lock
1134
1854
    def get_revisions(self, revision_ids):
1135
 
        """Get many revisions at once."""
 
1855
        """Get many revisions at once.
 
1856
        
 
1857
        Repositories that need to check data on every revision read should 
 
1858
        subclass this method.
 
1859
        """
1136
1860
        return self._get_revisions(revision_ids)
1137
1861
 
1138
1862
    @needs_read_lock
1139
1863
    def _get_revisions(self, revision_ids):
1140
1864
        """Core work logic to get many revisions without sanity checks."""
1141
 
        for rev_id in revision_ids:
1142
 
            if not rev_id or not isinstance(rev_id, basestring):
1143
 
                raise errors.InvalidRevisionId(revision_id=rev_id, branch=self)
 
1865
        revs = {}
 
1866
        for revid, rev in self._iter_revisions(revision_ids):
 
1867
            if rev is None:
 
1868
                raise errors.NoSuchRevision(self, revid)
 
1869
            revs[revid] = rev
 
1870
        return [revs[revid] for revid in revision_ids]
 
1871
 
 
1872
    def _iter_revisions(self, revision_ids):
 
1873
        """Iterate over revision objects.
 
1874
 
 
1875
        :param revision_ids: An iterable of revisions to examine. None may be
 
1876
            passed to request all revisions known to the repository. Note that
 
1877
            not all repositories can find unreferenced revisions; for those
 
1878
            repositories only referenced ones will be returned.
 
1879
        :return: An iterator of (revid, revision) tuples. Absent revisions (
 
1880
            those asked for but not available) are returned as (revid, None).
 
1881
        """
 
1882
        if revision_ids is None:
 
1883
            revision_ids = self.all_revision_ids()
 
1884
        else:
 
1885
            for rev_id in revision_ids:
 
1886
                if not rev_id or not isinstance(rev_id, basestring):
 
1887
                    raise errors.InvalidRevisionId(revision_id=rev_id, branch=self)
1144
1888
        keys = [(key,) for key in revision_ids]
1145
1889
        stream = self.revisions.get_record_stream(keys, 'unordered', True)
1146
 
        revs = {}
1147
1890
        for record in stream:
 
1891
            revid = record.key[0]
1148
1892
            if record.storage_kind == 'absent':
1149
 
                raise errors.NoSuchRevision(self, record.key[0])
1150
 
            text = record.get_bytes_as('fulltext')
1151
 
            rev = self._serializer.read_revision_from_string(text)
1152
 
            revs[record.key[0]] = rev
1153
 
        return [revs[revid] for revid in revision_ids]
1154
 
 
1155
 
    @needs_read_lock
1156
 
    def get_revision_xml(self, revision_id):
1157
 
        # TODO: jam 20070210 This shouldn't be necessary since get_revision
1158
 
        #       would have already do it.
1159
 
        # TODO: jam 20070210 Just use _serializer.write_revision_to_string()
1160
 
        rev = self.get_revision(revision_id)
1161
 
        rev_tmp = StringIO()
1162
 
        # the current serializer..
1163
 
        self._serializer.write_revision(rev, rev_tmp)
1164
 
        rev_tmp.seek(0)
1165
 
        return rev_tmp.getvalue()
1166
 
 
1167
 
    def get_deltas_for_revisions(self, revisions):
 
1893
                yield (revid, None)
 
1894
            else:
 
1895
                text = record.get_bytes_as('fulltext')
 
1896
                rev = self._serializer.read_revision_from_string(text)
 
1897
                yield (revid, rev)
 
1898
 
 
1899
    def get_deltas_for_revisions(self, revisions, specific_fileids=None):
1168
1900
        """Produce a generator of revision deltas.
1169
 
        
 
1901
 
1170
1902
        Note that the input is a sequence of REVISIONS, not revision_ids.
1171
1903
        Trees will be held in memory until the generator exits.
1172
1904
        Each delta is relative to the revision's lefthand predecessor.
 
1905
 
 
1906
        :param specific_fileids: if not None, the result is filtered
 
1907
          so that only those file-ids, their parents and their
 
1908
          children are included.
1173
1909
        """
 
1910
        # Get the revision-ids of interest
1174
1911
        required_trees = set()
1175
1912
        for revision in revisions:
1176
1913
            required_trees.add(revision.revision_id)
1177
1914
            required_trees.update(revision.parent_ids[:1])
1178
 
        trees = dict((t.get_revision_id(), t) for 
1179
 
                     t in self.revision_trees(required_trees))
 
1915
 
 
1916
        # Get the matching filtered trees. Note that it's more
 
1917
        # efficient to pass filtered trees to changes_from() rather
 
1918
        # than doing the filtering afterwards. changes_from() could
 
1919
        # arguably do the filtering itself but it's path-based, not
 
1920
        # file-id based, so filtering before or afterwards is
 
1921
        # currently easier.
 
1922
        if specific_fileids is None:
 
1923
            trees = dict((t.get_revision_id(), t) for
 
1924
                t in self.revision_trees(required_trees))
 
1925
        else:
 
1926
            trees = dict((t.get_revision_id(), t) for
 
1927
                t in self._filtered_revision_trees(required_trees,
 
1928
                specific_fileids))
 
1929
 
 
1930
        # Calculate the deltas
1180
1931
        for revision in revisions:
1181
1932
            if not revision.parent_ids:
1182
1933
                old_tree = self.revision_tree(_mod_revision.NULL_REVISION)
1185
1936
            yield trees[revision.revision_id].changes_from(old_tree)
1186
1937
 
1187
1938
    @needs_read_lock
1188
 
    def get_revision_delta(self, revision_id):
 
1939
    def get_revision_delta(self, revision_id, specific_fileids=None):
1189
1940
        """Return the delta for one revision.
1190
1941
 
1191
1942
        The delta is relative to the left-hand predecessor of the
1192
1943
        revision.
 
1944
 
 
1945
        :param specific_fileids: if not None, the result is filtered
 
1946
          so that only those file-ids, their parents and their
 
1947
          children are included.
1193
1948
        """
1194
1949
        r = self.get_revision(revision_id)
1195
 
        return list(self.get_deltas_for_revisions([r]))[0]
 
1950
        return list(self.get_deltas_for_revisions([r],
 
1951
            specific_fileids=specific_fileids))[0]
1196
1952
 
1197
1953
    @needs_write_lock
1198
1954
    def store_revision_signature(self, gpg_strategy, plaintext, revision_id):
1207
1963
    def find_text_key_references(self):
1208
1964
        """Find the text key references within the repository.
1209
1965
 
1210
 
        :return: a dictionary mapping (file_id, revision_id) tuples to altered file-ids to an iterable of
1211
 
        revision_ids. Each altered file-ids has the exact revision_ids that
1212
 
        altered it listed explicitly.
1213
1966
        :return: A dictionary mapping text keys ((fileid, revision_id) tuples)
1214
1967
            to whether they were referred to by the inventory of the
1215
1968
            revision_id that they contain. The inventory texts from all present
1246
1999
 
1247
2000
        # this code needs to read every new line in every inventory for the
1248
2001
        # inventories [revision_ids]. Seeing a line twice is ok. Seeing a line
1249
 
        # not present in one of those inventories is unnecessary but not 
 
2002
        # not present in one of those inventories is unnecessary but not
1250
2003
        # harmful because we are filtering by the revision id marker in the
1251
 
        # inventory lines : we only select file ids altered in one of those  
 
2004
        # inventory lines : we only select file ids altered in one of those
1252
2005
        # revisions. We don't need to see all lines in the inventory because
1253
2006
        # only those added in an inventory in rev X can contain a revision=X
1254
2007
        # line.
1304
2057
                result[key] = True
1305
2058
        return result
1306
2059
 
 
2060
    def _inventory_xml_lines_for_keys(self, keys):
 
2061
        """Get a line iterator of the sort needed for findind references.
 
2062
 
 
2063
        Not relevant for non-xml inventory repositories.
 
2064
 
 
2065
        Ghosts in revision_keys are ignored.
 
2066
 
 
2067
        :param revision_keys: The revision keys for the inventories to inspect.
 
2068
        :return: An iterator over (inventory line, revid) for the fulltexts of
 
2069
            all of the xml inventories specified by revision_keys.
 
2070
        """
 
2071
        stream = self.inventories.get_record_stream(keys, 'unordered', True)
 
2072
        for record in stream:
 
2073
            if record.storage_kind != 'absent':
 
2074
                chunks = record.get_bytes_as('chunked')
 
2075
                revid = record.key[-1]
 
2076
                lines = osutils.chunks_to_lines(chunks)
 
2077
                for line in lines:
 
2078
                    yield line, revid
 
2079
 
1307
2080
    def _find_file_ids_from_xml_inventory_lines(self, line_iterator,
1308
 
        revision_ids):
 
2081
        revision_keys):
1309
2082
        """Helper routine for fileids_altered_by_revision_ids.
1310
2083
 
1311
2084
        This performs the translation of xml lines to revision ids.
1312
2085
 
1313
2086
        :param line_iterator: An iterator of lines, origin_version_id
1314
 
        :param revision_ids: The revision ids to filter for. This should be a
 
2087
        :param revision_keys: The revision ids to filter for. This should be a
1315
2088
            set or other type which supports efficient __contains__ lookups, as
1316
 
            the revision id from each parsed line will be looked up in the
1317
 
            revision_ids filter.
 
2089
            the revision key from each parsed line will be looked up in the
 
2090
            revision_keys filter.
1318
2091
        :return: a dictionary mapping altered file-ids to an iterable of
1319
2092
        revision_ids. Each altered file-ids has the exact revision_ids that
1320
2093
        altered it listed explicitly.
1321
2094
        """
 
2095
        seen = set(self._find_text_key_references_from_xml_inventory_lines(
 
2096
                line_iterator).iterkeys())
 
2097
        parent_keys = self._find_parent_keys_of_revisions(revision_keys)
 
2098
        parent_seen = set(self._find_text_key_references_from_xml_inventory_lines(
 
2099
            self._inventory_xml_lines_for_keys(parent_keys)))
 
2100
        new_keys = seen - parent_seen
1322
2101
        result = {}
1323
2102
        setdefault = result.setdefault
1324
 
        for key in \
1325
 
            self._find_text_key_references_from_xml_inventory_lines(
1326
 
                line_iterator).iterkeys():
1327
 
            # once data is all ensured-consistent; then this is
1328
 
            # if revision_id == version_id
1329
 
            if key[-1:] in revision_ids:
1330
 
                setdefault(key[0], set()).add(key[-1])
 
2103
        for key in new_keys:
 
2104
            setdefault(key[0], set()).add(key[-1])
1331
2105
        return result
1332
2106
 
 
2107
    def _find_parent_ids_of_revisions(self, revision_ids):
 
2108
        """Find all parent ids that are mentioned in the revision graph.
 
2109
 
 
2110
        :return: set of revisions that are parents of revision_ids which are
 
2111
            not part of revision_ids themselves
 
2112
        """
 
2113
        parent_map = self.get_parent_map(revision_ids)
 
2114
        parent_ids = set()
 
2115
        map(parent_ids.update, parent_map.itervalues())
 
2116
        parent_ids.difference_update(revision_ids)
 
2117
        parent_ids.discard(_mod_revision.NULL_REVISION)
 
2118
        return parent_ids
 
2119
 
 
2120
    def _find_parent_keys_of_revisions(self, revision_keys):
 
2121
        """Similar to _find_parent_ids_of_revisions, but used with keys.
 
2122
 
 
2123
        :param revision_keys: An iterable of revision_keys.
 
2124
        :return: The parents of all revision_keys that are not already in
 
2125
            revision_keys
 
2126
        """
 
2127
        parent_map = self.revisions.get_parent_map(revision_keys)
 
2128
        parent_keys = set()
 
2129
        map(parent_keys.update, parent_map.itervalues())
 
2130
        parent_keys.difference_update(revision_keys)
 
2131
        parent_keys.discard(_mod_revision.NULL_REVISION)
 
2132
        return parent_keys
 
2133
 
1333
2134
    def fileids_altered_by_revision_ids(self, revision_ids, _inv_weave=None):
1334
2135
        """Find the file ids and versions affected by revisions.
1335
2136
 
1342
2143
        """
1343
2144
        selected_keys = set((revid,) for revid in revision_ids)
1344
2145
        w = _inv_weave or self.inventories
1345
 
        pb = ui.ui_factory.nested_progress_bar()
1346
 
        try:
1347
 
            return self._find_file_ids_from_xml_inventory_lines(
1348
 
                w.iter_lines_added_or_present_in_keys(
1349
 
                    selected_keys, pb=pb),
1350
 
                selected_keys)
1351
 
        finally:
1352
 
            pb.finished()
 
2146
        return self._find_file_ids_from_xml_inventory_lines(
 
2147
            w.iter_lines_added_or_present_in_keys(
 
2148
                selected_keys, pb=None),
 
2149
            selected_keys)
1353
2150
 
1354
2151
    def iter_files_bytes(self, desired_files):
1355
2152
        """Iterate through file versions.
1370
2167
        :param desired_files: a list of (file_id, revision_id, identifier)
1371
2168
            triples
1372
2169
        """
1373
 
        transaction = self.get_transaction()
1374
2170
        text_keys = {}
1375
2171
        for file_id, revision_id, callable_data in desired_files:
1376
2172
            text_keys[(file_id, revision_id)] = callable_data
1377
2173
        for record in self.texts.get_record_stream(text_keys, 'unordered', True):
1378
2174
            if record.storage_kind == 'absent':
1379
2175
                raise errors.RevisionNotPresent(record.key, self)
1380
 
            yield text_keys[record.key], record.get_bytes_as('fulltext')
 
2176
            yield text_keys[record.key], record.get_bytes_as('chunked')
1381
2177
 
1382
2178
    def _generate_text_key_index(self, text_key_references=None,
1383
2179
        ancestors=None):
1432
2228
        batch_size = 10 # should be ~150MB on a 55K path tree
1433
2229
        batch_count = len(revision_order) / batch_size + 1
1434
2230
        processed_texts = 0
1435
 
        pb.update("Calculating text parents.", processed_texts, text_count)
 
2231
        pb.update("Calculating text parents", processed_texts, text_count)
1436
2232
        for offset in xrange(batch_count):
1437
2233
            to_query = revision_order[offset * batch_size:(offset + 1) *
1438
2234
                batch_size]
1439
2235
            if not to_query:
1440
2236
                break
1441
 
            for rev_tree in self.revision_trees(to_query):
1442
 
                revision_id = rev_tree.get_revision_id()
 
2237
            for revision_id in to_query:
1443
2238
                parent_ids = ancestors[revision_id]
1444
2239
                for text_key in revision_keys[revision_id]:
1445
 
                    pb.update("Calculating text parents.", processed_texts)
 
2240
                    pb.update("Calculating text parents", processed_texts)
1446
2241
                    processed_texts += 1
1447
2242
                    candidate_parents = []
1448
2243
                    for parent_id in parent_ids:
1464
2259
                            except KeyError:
1465
2260
                                inv = self.revision_tree(parent_id).inventory
1466
2261
                                inventory_cache[parent_id] = inv
1467
 
                            parent_entry = inv._byid.get(text_key[0], None)
 
2262
                            try:
 
2263
                                parent_entry = inv[text_key[0]]
 
2264
                            except (KeyError, errors.NoSuchId):
 
2265
                                parent_entry = None
1468
2266
                            if parent_entry is not None:
1469
2267
                                parent_text_key = (
1470
2268
                                    text_key[0], parent_entry.revision)
1495
2293
            versions).  knit-kind is one of 'file', 'inventory', 'signatures',
1496
2294
            'revisions'.  file-id is None unless knit-kind is 'file'.
1497
2295
        """
 
2296
        for result in self._find_file_keys_to_fetch(revision_ids, _files_pb):
 
2297
            yield result
 
2298
        del _files_pb
 
2299
        for result in self._find_non_file_keys_to_fetch(revision_ids):
 
2300
            yield result
 
2301
 
 
2302
    def _find_file_keys_to_fetch(self, revision_ids, pb):
1498
2303
        # XXX: it's a bit weird to control the inventory weave caching in this
1499
2304
        # generator.  Ideally the caching would be done in fetch.py I think.  Or
1500
2305
        # maybe this generator should explicitly have the contract that it
1507
2312
        count = 0
1508
2313
        num_file_ids = len(file_ids)
1509
2314
        for file_id, altered_versions in file_ids.iteritems():
1510
 
            if _files_pb is not None:
1511
 
                _files_pb.update("fetch texts", count, num_file_ids)
 
2315
            if pb is not None:
 
2316
                pb.update("Fetch texts", count, num_file_ids)
1512
2317
            count += 1
1513
2318
            yield ("file", file_id, altered_versions)
1514
 
        # We're done with the files_pb.  Note that it finished by the caller,
1515
 
        # just as it was created by the caller.
1516
 
        del _files_pb
1517
2319
 
 
2320
    def _find_non_file_keys_to_fetch(self, revision_ids):
1518
2321
        # inventory
1519
2322
        yield ("inventory", None, revision_ids)
1520
2323
 
1521
2324
        # signatures
1522
 
        revisions_with_signatures = set()
1523
 
        for rev_id in revision_ids:
1524
 
            try:
1525
 
                self.get_signature_text(rev_id)
1526
 
            except errors.NoSuchRevision:
1527
 
                # not signed.
1528
 
                pass
1529
 
            else:
1530
 
                revisions_with_signatures.add(rev_id)
 
2325
        # XXX: Note ATM no callers actually pay attention to this return
 
2326
        #      instead they just use the list of revision ids and ignore
 
2327
        #      missing sigs. Consider removing this work entirely
 
2328
        revisions_with_signatures = set(self.signatures.get_parent_map(
 
2329
            [(r,) for r in revision_ids]))
 
2330
        revisions_with_signatures = set(
 
2331
            [r for (r,) in revisions_with_signatures])
 
2332
        revisions_with_signatures.intersection_update(revision_ids)
1531
2333
        yield ("signatures", None, revisions_with_signatures)
1532
2334
 
1533
2335
        # revisions
1538
2340
        """Get Inventory object by revision id."""
1539
2341
        return self.iter_inventories([revision_id]).next()
1540
2342
 
1541
 
    def iter_inventories(self, revision_ids):
 
2343
    def iter_inventories(self, revision_ids, ordering=None):
1542
2344
        """Get many inventories by revision_ids.
1543
2345
 
1544
2346
        This will buffer some or all of the texts used in constructing the
1545
2347
        inventories in memory, but will only parse a single inventory at a
1546
2348
        time.
1547
2349
 
 
2350
        :param revision_ids: The expected revision ids of the inventories.
 
2351
        :param ordering: optional ordering, e.g. 'topological'.  If not
 
2352
            specified, the order of revision_ids will be preserved (by
 
2353
            buffering if necessary).
1548
2354
        :return: An iterator of inventories.
1549
2355
        """
1550
2356
        if ((None in revision_ids)
1551
2357
            or (_mod_revision.NULL_REVISION in revision_ids)):
1552
2358
            raise ValueError('cannot get null revision inventory')
1553
 
        return self._iter_inventories(revision_ids)
 
2359
        return self._iter_inventories(revision_ids, ordering)
1554
2360
 
1555
 
    def _iter_inventories(self, revision_ids):
 
2361
    def _iter_inventories(self, revision_ids, ordering):
1556
2362
        """single-document based inventory iteration."""
1557
 
        for text, revision_id in self._iter_inventory_xmls(revision_ids):
1558
 
            yield self.deserialise_inventory(revision_id, text)
 
2363
        inv_xmls = self._iter_inventory_xmls(revision_ids, ordering)
 
2364
        for text, revision_id in inv_xmls:
 
2365
            yield self._deserialise_inventory(revision_id, text)
1559
2366
 
1560
 
    def _iter_inventory_xmls(self, revision_ids):
 
2367
    def _iter_inventory_xmls(self, revision_ids, ordering):
 
2368
        if ordering is None:
 
2369
            order_as_requested = True
 
2370
            ordering = 'unordered'
 
2371
        else:
 
2372
            order_as_requested = False
1561
2373
        keys = [(revision_id,) for revision_id in revision_ids]
1562
 
        stream = self.inventories.get_record_stream(keys, 'unordered', True)
1563
 
        texts = {}
 
2374
        if not keys:
 
2375
            return
 
2376
        if order_as_requested:
 
2377
            key_iter = iter(keys)
 
2378
            next_key = key_iter.next()
 
2379
        stream = self.inventories.get_record_stream(keys, ordering, True)
 
2380
        text_chunks = {}
1564
2381
        for record in stream:
1565
2382
            if record.storage_kind != 'absent':
1566
 
                texts[record.key] = record.get_bytes_as('fulltext')
 
2383
                chunks = record.get_bytes_as('chunked')
 
2384
                if order_as_requested:
 
2385
                    text_chunks[record.key] = chunks
 
2386
                else:
 
2387
                    yield ''.join(chunks), record.key[-1]
1567
2388
            else:
1568
2389
                raise errors.NoSuchRevision(self, record.key)
1569
 
        for key in keys:
1570
 
            yield texts[key], key[-1]
 
2390
            if order_as_requested:
 
2391
                # Yield as many results as we can while preserving order.
 
2392
                while next_key in text_chunks:
 
2393
                    chunks = text_chunks.pop(next_key)
 
2394
                    yield ''.join(chunks), next_key[-1]
 
2395
                    try:
 
2396
                        next_key = key_iter.next()
 
2397
                    except StopIteration:
 
2398
                        # We still want to fully consume the get_record_stream,
 
2399
                        # just in case it is not actually finished at this point
 
2400
                        next_key = None
 
2401
                        break
1571
2402
 
1572
 
    def deserialise_inventory(self, revision_id, xml):
1573
 
        """Transform the xml into an inventory object. 
 
2403
    def _deserialise_inventory(self, revision_id, xml):
 
2404
        """Transform the xml into an inventory object.
1574
2405
 
1575
2406
        :param revision_id: The expected revision id of the inventory.
1576
2407
        :param xml: A serialised inventory.
1577
2408
        """
1578
 
        result = self._serializer.read_inventory_from_string(xml, revision_id)
 
2409
        result = self._serializer.read_inventory_from_string(xml, revision_id,
 
2410
                    entry_cache=self._inventory_entry_cache,
 
2411
                    return_from_cache=self._safe_to_return_from_cache)
1579
2412
        if result.revision_id != revision_id:
1580
2413
            raise AssertionError('revision id mismatch %s != %s' % (
1581
2414
                result.revision_id, revision_id))
1582
2415
        return result
1583
2416
 
1584
 
    def serialise_inventory(self, inv):
1585
 
        return self._serializer.write_inventory_to_string(inv)
1586
 
 
1587
 
    def _serialise_inventory_to_lines(self, inv):
1588
 
        return self._serializer.write_inventory_to_lines(inv)
1589
 
 
1590
2417
    def get_serializer_format(self):
1591
2418
        return self._serializer.format_num
1592
2419
 
1593
2420
    @needs_read_lock
1594
 
    def get_inventory_xml(self, revision_id):
1595
 
        """Get inventory XML as a file object."""
1596
 
        texts = self._iter_inventory_xmls([revision_id])
 
2421
    def _get_inventory_xml(self, revision_id):
 
2422
        """Get serialized inventory as a string."""
 
2423
        texts = self._iter_inventory_xmls([revision_id], 'unordered')
1597
2424
        try:
1598
2425
            text, revision_id = texts.next()
1599
2426
        except StopIteration:
1600
2427
            raise errors.HistoryMissing(self, 'inventory', revision_id)
1601
2428
        return text
1602
2429
 
1603
 
    @needs_read_lock
1604
 
    def get_inventory_sha1(self, revision_id):
1605
 
        """Return the sha1 hash of the inventory entry
 
2430
    def get_rev_id_for_revno(self, revno, known_pair):
 
2431
        """Return the revision id of a revno, given a later (revno, revid)
 
2432
        pair in the same history.
 
2433
 
 
2434
        :return: if found (True, revid).  If the available history ran out
 
2435
            before reaching the revno, then this returns
 
2436
            (False, (closest_revno, closest_revid)).
1606
2437
        """
1607
 
        return self.get_revision(revision_id).inventory_sha1
 
2438
        known_revno, known_revid = known_pair
 
2439
        partial_history = [known_revid]
 
2440
        distance_from_known = known_revno - revno
 
2441
        if distance_from_known < 0:
 
2442
            raise ValueError(
 
2443
                'requested revno (%d) is later than given known revno (%d)'
 
2444
                % (revno, known_revno))
 
2445
        try:
 
2446
            _iter_for_revno(
 
2447
                self, partial_history, stop_index=distance_from_known)
 
2448
        except errors.RevisionNotPresent, err:
 
2449
            if err.revision_id == known_revid:
 
2450
                # The start revision (known_revid) wasn't found.
 
2451
                raise
 
2452
            # This is a stacked repository with no fallbacks, or a there's a
 
2453
            # left-hand ghost.  Either way, even though the revision named in
 
2454
            # the error isn't in this repo, we know it's the next step in this
 
2455
            # left-hand history.
 
2456
            partial_history.append(err.revision_id)
 
2457
        if len(partial_history) <= distance_from_known:
 
2458
            # Didn't find enough history to get a revid for the revno.
 
2459
            earliest_revno = known_revno - len(partial_history) + 1
 
2460
            return (False, (earliest_revno, partial_history[-1]))
 
2461
        if len(partial_history) - 1 > distance_from_known:
 
2462
            raise AssertionError('_iter_for_revno returned too much history')
 
2463
        return (True, partial_history[-1])
1608
2464
 
1609
2465
    def iter_reverse_revision_history(self, revision_id):
1610
2466
        """Iterate backwards through revision ids in the lefthand history
1617
2473
        while True:
1618
2474
            if next_id in (None, _mod_revision.NULL_REVISION):
1619
2475
                return
 
2476
            try:
 
2477
                parents = graph.get_parent_map([next_id])[next_id]
 
2478
            except KeyError:
 
2479
                raise errors.RevisionNotPresent(next_id, self)
1620
2480
            yield next_id
1621
 
            # Note: The following line may raise KeyError in the event of
1622
 
            # truncated history. We decided not to have a try:except:raise
1623
 
            # RevisionNotPresent here until we see a use for it, because of the
1624
 
            # cost in an inner loop that is by its very nature O(history).
1625
 
            # Robert Collins 20080326
1626
 
            parents = graph.get_parent_map([next_id])[next_id]
1627
2481
            if len(parents) == 0:
1628
2482
                return
1629
2483
            else:
1630
2484
                next_id = parents[0]
1631
2485
 
1632
 
    @needs_read_lock
1633
 
    def get_revision_inventory(self, revision_id):
1634
 
        """Return inventory of a past revision."""
1635
 
        # TODO: Unify this with get_inventory()
1636
 
        # bzr 0.0.6 and later imposes the constraint that the inventory_id
1637
 
        # must be the same as its revision, so this is trivial.
1638
 
        if revision_id is None:
1639
 
            # This does not make sense: if there is no revision,
1640
 
            # then it is the current tree inventory surely ?!
1641
 
            # and thus get_root_id() is something that looks at the last
1642
 
            # commit on the branch, and the get_root_id is an inventory check.
1643
 
            raise NotImplementedError
1644
 
            # return Inventory(self.get_root_id())
1645
 
        else:
1646
 
            return self.get_inventory(revision_id)
1647
 
 
1648
2486
    def is_shared(self):
1649
2487
        """Return True if this repository is flagged as a shared repository."""
1650
2488
        raise NotImplementedError(self.is_shared)
1664
2502
        for repositories to maintain loaded indices across multiple locks
1665
2503
        by checking inside their implementation of this method to see
1666
2504
        whether their indices are still valid. This depends of course on
1667
 
        the disk format being validatable in this manner.
 
2505
        the disk format being validatable in this manner. This method is
 
2506
        also called by the refresh_data() public interface to cause a refresh
 
2507
        to occur while in a write lock so that data inserted by a smart server
 
2508
        push operation is visible on the client's instance of the physical
 
2509
        repository.
1668
2510
        """
1669
2511
 
1670
2512
    @needs_read_lock
1677
2519
        # TODO: refactor this to use an existing revision object
1678
2520
        # so we don't need to read it in twice.
1679
2521
        if revision_id == _mod_revision.NULL_REVISION:
1680
 
            return RevisionTree(self, Inventory(root_id=None), 
 
2522
            return RevisionTree(self, Inventory(root_id=None),
1681
2523
                                _mod_revision.NULL_REVISION)
1682
2524
        else:
1683
 
            inv = self.get_revision_inventory(revision_id)
 
2525
            inv = self.get_inventory(revision_id)
1684
2526
            return RevisionTree(self, inv, revision_id)
1685
2527
 
1686
2528
    def revision_trees(self, revision_ids):
1687
 
        """Return Tree for a revision on this branch.
 
2529
        """Return Trees for revisions in this repository.
1688
2530
 
1689
 
        `revision_id` may not be None or 'null:'"""
 
2531
        :param revision_ids: a sequence of revision-ids;
 
2532
          a revision-id may not be None or 'null:'
 
2533
        """
1690
2534
        inventories = self.iter_inventories(revision_ids)
1691
2535
        for inv in inventories:
1692
2536
            yield RevisionTree(self, inv, inv.revision_id)
1693
2537
 
 
2538
    def _filtered_revision_trees(self, revision_ids, file_ids):
 
2539
        """Return Tree for a revision on this branch with only some files.
 
2540
 
 
2541
        :param revision_ids: a sequence of revision-ids;
 
2542
          a revision-id may not be None or 'null:'
 
2543
        :param file_ids: if not None, the result is filtered
 
2544
          so that only those file-ids, their parents and their
 
2545
          children are included.
 
2546
        """
 
2547
        inventories = self.iter_inventories(revision_ids)
 
2548
        for inv in inventories:
 
2549
            # Should we introduce a FilteredRevisionTree class rather
 
2550
            # than pre-filter the inventory here?
 
2551
            filtered_inv = inv.filter(file_ids)
 
2552
            yield RevisionTree(self, filtered_inv, filtered_inv.revision_id)
 
2553
 
1694
2554
    @needs_read_lock
1695
2555
    def get_ancestry(self, revision_id, topo_sorted=True):
1696
2556
        """Return a list of revision-ids integrated by a revision.
1697
2557
 
1698
 
        The first element of the list is always None, indicating the origin 
1699
 
        revision.  This might change when we have history horizons, or 
 
2558
        The first element of the list is always None, indicating the origin
 
2559
        revision.  This might change when we have history horizons, or
1700
2560
        perhaps we should have a new API.
1701
 
        
 
2561
 
1702
2562
        This is topologically sorted.
1703
2563
        """
1704
2564
        if _mod_revision.is_null(revision_id):
1721
2581
            keys = tsort.topo_sort(parent_map)
1722
2582
        return [None] + list(keys)
1723
2583
 
1724
 
    def pack(self):
 
2584
    def pack(self, hint=None, clean_obsolete_packs=False):
1725
2585
        """Compress the data within the repository.
1726
2586
 
1727
2587
        This operation only makes sense for some repository types. For other
1728
2588
        types it should be a no-op that just returns.
1729
2589
 
1730
2590
        This stub method does not require a lock, but subclasses should use
1731
 
        @needs_write_lock as this is a long running call its reasonable to 
 
2591
        @needs_write_lock as this is a long running call its reasonable to
1732
2592
        implicitly lock for the user.
1733
 
        """
1734
 
 
1735
 
    @needs_read_lock
1736
 
    @deprecated_method(one_six)
1737
 
    def print_file(self, file, revision_id):
1738
 
        """Print `file` to stdout.
1739
 
        
1740
 
        FIXME RBC 20060125 as John Meinel points out this is a bad api
1741
 
        - it writes to stdout, it assumes that that is valid etc. Fix
1742
 
        by creating a new more flexible convenience function.
1743
 
        """
1744
 
        tree = self.revision_tree(revision_id)
1745
 
        # use inventory as it was in that revision
1746
 
        file_id = tree.inventory.path2id(file)
1747
 
        if not file_id:
1748
 
            # TODO: jam 20060427 Write a test for this code path
1749
 
            #       it had a bug in it, and was raising the wrong
1750
 
            #       exception.
1751
 
            raise errors.BzrError("%r is not present in revision %s" % (file, revision_id))
1752
 
        tree.print_file(file_id)
 
2593
 
 
2594
        :param hint: If not supplied, the whole repository is packed.
 
2595
            If supplied, the repository may use the hint parameter as a
 
2596
            hint for the parts of the repository to pack. A hint can be
 
2597
            obtained from the result of commit_write_group(). Out of
 
2598
            date hints are simply ignored, because concurrent operations
 
2599
            can obsolete them rapidly.
 
2600
 
 
2601
        :param clean_obsolete_packs: Clean obsolete packs immediately after
 
2602
            the pack operation.
 
2603
        """
1753
2604
 
1754
2605
    def get_transaction(self):
1755
2606
        return self.control_files.get_transaction()
1756
2607
 
1757
 
    @deprecated_method(one_one)
1758
 
    def get_parents(self, revision_ids):
1759
 
        """See StackedParentsProvider.get_parents"""
1760
 
        parent_map = self.get_parent_map(revision_ids)
1761
 
        return [parent_map.get(r, None) for r in revision_ids]
1762
 
 
1763
2608
    def get_parent_map(self, revision_ids):
1764
 
        """See graph._StackedParentsProvider.get_parent_map"""
 
2609
        """See graph.StackedParentsProvider.get_parent_map"""
1765
2610
        # revisions index works in keys; this just works in revisions
1766
2611
        # therefore wrap and unwrap
1767
2612
        query_keys = []
1776
2621
        for ((revision_id,), parent_keys) in \
1777
2622
                self.revisions.get_parent_map(query_keys).iteritems():
1778
2623
            if parent_keys:
1779
 
                result[revision_id] = tuple(parent_revid
1780
 
                    for (parent_revid,) in parent_keys)
 
2624
                result[revision_id] = tuple([parent_revid
 
2625
                    for (parent_revid,) in parent_keys])
1781
2626
            else:
1782
2627
                result[revision_id] = (_mod_revision.NULL_REVISION,)
1783
2628
        return result
1785
2630
    def _make_parents_provider(self):
1786
2631
        return self
1787
2632
 
 
2633
    @needs_read_lock
 
2634
    def get_known_graph_ancestry(self, revision_ids):
 
2635
        """Return the known graph for a set of revision ids and their ancestors.
 
2636
        """
 
2637
        st = static_tuple.StaticTuple
 
2638
        revision_keys = [st(r_id).intern() for r_id in revision_ids]
 
2639
        known_graph = self.revisions.get_known_graph_ancestry(revision_keys)
 
2640
        return graph.GraphThunkIdsToKeys(known_graph)
 
2641
 
1788
2642
    def get_graph(self, other_repository=None):
1789
2643
        """Return the graph walker for this repository format"""
1790
2644
        parents_provider = self._make_parents_provider()
1791
2645
        if (other_repository is not None and
1792
2646
            not self.has_same_location(other_repository)):
1793
 
            parents_provider = graph._StackedParentsProvider(
 
2647
            parents_provider = graph.StackedParentsProvider(
1794
2648
                [parents_provider, other_repository._make_parents_provider()])
1795
2649
        return graph.Graph(parents_provider)
1796
2650
 
1797
 
    def _get_versioned_file_checker(self):
1798
 
        """Return an object suitable for checking versioned files."""
1799
 
        return _VersionedFileChecker(self)
 
2651
    def _get_versioned_file_checker(self, text_key_references=None,
 
2652
        ancestors=None):
 
2653
        """Return an object suitable for checking versioned files.
 
2654
        
 
2655
        :param text_key_references: if non-None, an already built
 
2656
            dictionary mapping text keys ((fileid, revision_id) tuples)
 
2657
            to whether they were referred to by the inventory of the
 
2658
            revision_id that they contain. If None, this will be
 
2659
            calculated.
 
2660
        :param ancestors: Optional result from
 
2661
            self.get_graph().get_parent_map(self.all_revision_ids()) if already
 
2662
            available.
 
2663
        """
 
2664
        return _VersionedFileChecker(self,
 
2665
            text_key_references=text_key_references, ancestors=ancestors)
1800
2666
 
1801
2667
    def revision_ids_to_search_result(self, result_set):
1802
2668
        """Convert a set of revision ids to a graph SearchResult."""
1822
2688
                          working trees.
1823
2689
        """
1824
2690
        raise NotImplementedError(self.set_make_working_trees)
1825
 
    
 
2691
 
1826
2692
    def make_working_trees(self):
1827
2693
        """Returns the policy for making working trees on new branches."""
1828
2694
        raise NotImplementedError(self.make_working_trees)
1852
2718
        return record.get_bytes_as('fulltext')
1853
2719
 
1854
2720
    @needs_read_lock
1855
 
    def check(self, revision_ids=None):
 
2721
    def check(self, revision_ids=None, callback_refs=None, check_repo=True):
1856
2722
        """Check consistency of all history of given revision_ids.
1857
2723
 
1858
2724
        Different repository implementations should override _check().
1859
2725
 
1860
2726
        :param revision_ids: A non-empty list of revision_ids whose ancestry
1861
2727
             will be checked.  Typically the last revision_id of a branch.
 
2728
        :param callback_refs: A dict of check-refs to resolve and callback
 
2729
            the check/_check method on the items listed as wanting the ref.
 
2730
            see bzrlib.check.
 
2731
        :param check_repo: If False do not check the repository contents, just 
 
2732
            calculate the data callback_refs requires and call them back.
1862
2733
        """
1863
 
        return self._check(revision_ids)
 
2734
        return self._check(revision_ids, callback_refs=callback_refs,
 
2735
            check_repo=check_repo)
1864
2736
 
1865
 
    def _check(self, revision_ids):
1866
 
        result = check.Check(self)
1867
 
        result.check()
 
2737
    def _check(self, revision_ids, callback_refs, check_repo):
 
2738
        result = check.Check(self, check_repo=check_repo)
 
2739
        result.check(callback_refs)
1868
2740
        return result
1869
2741
 
1870
 
    def _warn_if_deprecated(self):
 
2742
    def _warn_if_deprecated(self, branch=None):
1871
2743
        global _deprecation_warning_done
1872
2744
        if _deprecation_warning_done:
1873
2745
            return
1874
 
        _deprecation_warning_done = True
1875
 
        warning("Format %s for %s is deprecated - please use 'bzr upgrade' to get better performance"
1876
 
                % (self._format, self.bzrdir.transport.base))
 
2746
        try:
 
2747
            if branch is None:
 
2748
                conf = config.GlobalConfig()
 
2749
            else:
 
2750
                conf = branch.get_config()
 
2751
            if conf.suppress_warning('format_deprecation'):
 
2752
                return
 
2753
            warning("Format %s for %s is deprecated -"
 
2754
                    " please use 'bzr upgrade' to get better performance"
 
2755
                    % (self._format, self.bzrdir.transport.base))
 
2756
        finally:
 
2757
            _deprecation_warning_done = True
1877
2758
 
1878
2759
    def supports_rich_root(self):
1879
2760
        return self._format.rich_root_data
1893
2774
                    revision_id.decode('ascii')
1894
2775
                except UnicodeDecodeError:
1895
2776
                    raise errors.NonAsciiRevisionId(method, self)
1896
 
    
 
2777
 
1897
2778
    def revision_graph_can_have_wrong_parents(self):
1898
2779
        """Is it possible for this repository to have a revision graph with
1899
2780
        incorrect parents?
1953
2834
    """
1954
2835
    repository.start_write_group()
1955
2836
    try:
 
2837
        inventory_cache = lru_cache.LRUCache(10)
1956
2838
        for n, (revision, revision_tree, signature) in enumerate(iterable):
1957
 
            _install_revision(repository, revision, revision_tree, signature)
 
2839
            _install_revision(repository, revision, revision_tree, signature,
 
2840
                inventory_cache)
1958
2841
            if pb is not None:
1959
2842
                pb.update('Transferring revisions', n + 1, num_revisions)
1960
2843
    except:
1964
2847
        repository.commit_write_group()
1965
2848
 
1966
2849
 
1967
 
def _install_revision(repository, rev, revision_tree, signature):
 
2850
def _install_revision(repository, rev, revision_tree, signature,
 
2851
    inventory_cache):
1968
2852
    """Install all revision data into a repository."""
1969
2853
    present_parents = []
1970
2854
    parent_trees = {}
2007
2891
        repository.texts.add_lines(text_key, text_parents, lines)
2008
2892
    try:
2009
2893
        # install the inventory
2010
 
        repository.add_inventory(rev.revision_id, inv, present_parents)
 
2894
        if repository._format._commit_inv_deltas and len(rev.parent_ids):
 
2895
            # Cache this inventory
 
2896
            inventory_cache[rev.revision_id] = inv
 
2897
            try:
 
2898
                basis_inv = inventory_cache[rev.parent_ids[0]]
 
2899
            except KeyError:
 
2900
                repository.add_inventory(rev.revision_id, inv, present_parents)
 
2901
            else:
 
2902
                delta = inv._make_delta(basis_inv)
 
2903
                repository.add_inventory_by_delta(rev.parent_ids[0], delta,
 
2904
                    rev.revision_id, present_parents)
 
2905
        else:
 
2906
            repository.add_inventory(rev.revision_id, inv, present_parents)
2011
2907
    except errors.RevisionAlreadyPresent:
2012
2908
        pass
2013
2909
    if signature is not None:
2017
2913
 
2018
2914
class MetaDirRepository(Repository):
2019
2915
    """Repositories in the new meta-dir layout.
2020
 
    
 
2916
 
2021
2917
    :ivar _transport: Transport for access to repository control files,
2022
2918
        typically pointing to .bzr/repository.
2023
2919
    """
2048
2944
        else:
2049
2945
            self._transport.put_bytes('no-working-trees', '',
2050
2946
                mode=self.bzrdir._get_file_mode())
2051
 
    
 
2947
 
2052
2948
    def make_working_trees(self):
2053
2949
        """Returns the policy for making working trees on new branches."""
2054
2950
        return not self._transport.has('no-working-trees')
2062
2958
            control_files)
2063
2959
 
2064
2960
 
2065
 
class RepositoryFormatRegistry(registry.Registry):
2066
 
    """Registry of RepositoryFormats."""
2067
 
 
2068
 
    def get(self, format_string):
2069
 
        r = registry.Registry.get(self, format_string)
2070
 
        if callable(r):
2071
 
            r = r()
2072
 
        return r
2073
 
    
2074
 
 
2075
 
format_registry = RepositoryFormatRegistry()
2076
 
"""Registry of formats, indexed by their identifying format string.
 
2961
network_format_registry = registry.FormatRegistry()
 
2962
"""Registry of formats indexed by their network name.
 
2963
 
 
2964
The network name for a repository format is an identifier that can be used when
 
2965
referring to formats with smart server operations. See
 
2966
RepositoryFormat.network_name() for more detail.
 
2967
"""
 
2968
 
 
2969
 
 
2970
format_registry = registry.FormatRegistry(network_format_registry)
 
2971
"""Registry of formats, indexed by their BzrDirMetaFormat format string.
2077
2972
 
2078
2973
This can contain either format instances themselves, or classes/factories that
2079
2974
can be called to obtain one.
2086
2981
class RepositoryFormat(object):
2087
2982
    """A repository format.
2088
2983
 
2089
 
    Formats provide three things:
 
2984
    Formats provide four things:
2090
2985
     * An initialization routine to construct repository data on disk.
2091
 
     * a format string which is used when the BzrDir supports versioned
2092
 
       children.
 
2986
     * a optional format string which is used when the BzrDir supports
 
2987
       versioned children.
2093
2988
     * an open routine which returns a Repository instance.
 
2989
     * A network name for referring to the format in smart server RPC
 
2990
       methods.
2094
2991
 
2095
2992
    There is one and only one Format subclass for each on-disk format. But
2096
2993
    there can be one Repository subclass that is used for several different
2097
2994
    formats. The _format attribute on a Repository instance can be used to
2098
2995
    determine the disk format.
2099
2996
 
2100
 
    Formats are placed in an dict by their format string for reference 
2101
 
    during opening. These should be subclasses of RepositoryFormat
2102
 
    for consistency.
 
2997
    Formats are placed in a registry by their format string for reference
 
2998
    during opening. These should be subclasses of RepositoryFormat for
 
2999
    consistency.
2103
3000
 
2104
3001
    Once a format is deprecated, just deprecate the initialize and open
2105
 
    methods on the format class. Do not deprecate the object, as the 
2106
 
    object will be created every system load.
 
3002
    methods on the format class. Do not deprecate the object, as the
 
3003
    object may be created even when a repository instance hasn't been
 
3004
    created.
2107
3005
 
2108
3006
    Common instance attributes:
2109
3007
    _matchingbzrdir - the bzrdir format that the repository format was
2118
3016
    # Can this repository be given external locations to lookup additional
2119
3017
    # data. Set to True or False in derived classes.
2120
3018
    supports_external_lookups = None
 
3019
    # Does this format support CHK bytestring lookups. Set to True or False in
 
3020
    # derived classes.
 
3021
    supports_chks = None
 
3022
    # Should commit add an inventory, or an inventory delta to the repository.
 
3023
    _commit_inv_deltas = True
 
3024
    # What order should fetch operations request streams in?
 
3025
    # The default is unordered as that is the cheapest for an origin to
 
3026
    # provide.
 
3027
    _fetch_order = 'unordered'
 
3028
    # Does this repository format use deltas that can be fetched as-deltas ?
 
3029
    # (E.g. knits, where the knit deltas can be transplanted intact.
 
3030
    # We default to False, which will ensure that enough data to get
 
3031
    # a full text out of any fetch stream will be grabbed.
 
3032
    _fetch_uses_deltas = False
 
3033
    # Should fetch trigger a reconcile after the fetch? Only needed for
 
3034
    # some repository formats that can suffer internal inconsistencies.
 
3035
    _fetch_reconcile = False
 
3036
    # Does this format have < O(tree_size) delta generation. Used to hint what
 
3037
    # code path for commit, amongst other things.
 
3038
    fast_deltas = None
 
3039
    # Does doing a pack operation compress data? Useful for the pack UI command
 
3040
    # (so if there is one pack, the operation can still proceed because it may
 
3041
    # help), and for fetching when data won't have come from the same
 
3042
    # compressor.
 
3043
    pack_compresses = False
 
3044
    # Does the repository inventory storage understand references to trees?
 
3045
    supports_tree_reference = None
 
3046
    # Is the format experimental ?
 
3047
    experimental = False
2121
3048
 
2122
 
    def __str__(self):
2123
 
        return "<%s>" % self.__class__.__name__
 
3049
    def __repr__(self):
 
3050
        return "%s()" % self.__class__.__name__
2124
3051
 
2125
3052
    def __eq__(self, other):
2126
3053
        # format objects are generally stateless
2132
3059
    @classmethod
2133
3060
    def find_format(klass, a_bzrdir):
2134
3061
        """Return the format for the repository object in a_bzrdir.
2135
 
        
 
3062
 
2136
3063
        This is used by bzr native formats that have a "format" file in
2137
 
        the repository.  Other methods may be used by different types of 
 
3064
        the repository.  Other methods may be used by different types of
2138
3065
        control directory.
2139
3066
        """
2140
3067
        try:
2141
3068
            transport = a_bzrdir.get_repository_transport(None)
2142
 
            format_string = transport.get("format").read()
 
3069
            format_string = transport.get_bytes("format")
2143
3070
            return format_registry.get(format_string)
2144
3071
        except errors.NoSuchFile:
2145
3072
            raise errors.NoRepositoryPresent(a_bzrdir)
2154
3081
    @classmethod
2155
3082
    def unregister_format(klass, format):
2156
3083
        format_registry.remove(format.get_format_string())
2157
 
    
 
3084
 
2158
3085
    @classmethod
2159
3086
    def get_default_format(klass):
2160
3087
        """Return the current default format."""
2163
3090
 
2164
3091
    def get_format_string(self):
2165
3092
        """Return the ASCII format string that identifies this format.
2166
 
        
2167
 
        Note that in pre format ?? repositories the format string is 
 
3093
 
 
3094
        Note that in pre format ?? repositories the format string is
2168
3095
        not permitted nor written to disk.
2169
3096
        """
2170
3097
        raise NotImplementedError(self.get_format_string)
2201
3128
        :param a_bzrdir: The bzrdir to put the new repository in it.
2202
3129
        :param shared: The repository should be initialized as a sharable one.
2203
3130
        :returns: The new repository object.
2204
 
        
 
3131
 
2205
3132
        This may raise UninitializableFormat if shared repository are not
2206
3133
        compatible the a_bzrdir.
2207
3134
        """
2211
3138
        """Is this format supported?
2212
3139
 
2213
3140
        Supported formats must be initializable and openable.
2214
 
        Unsupported formats may not support initialization or committing or 
 
3141
        Unsupported formats may not support initialization or committing or
2215
3142
        some other features depending on the reason for not being supported.
2216
3143
        """
2217
3144
        return True
2218
3145
 
 
3146
    def network_name(self):
 
3147
        """A simple byte string uniquely identifying this format for RPC calls.
 
3148
 
 
3149
        MetaDir repository formats use their disk format string to identify the
 
3150
        repository over the wire. All in one formats such as bzr < 0.8, and
 
3151
        foreign formats like svn/git and hg should use some marker which is
 
3152
        unique and immutable.
 
3153
        """
 
3154
        raise NotImplementedError(self.network_name)
 
3155
 
2219
3156
    def check_conversion_target(self, target_format):
2220
 
        raise NotImplementedError(self.check_conversion_target)
 
3157
        if self.rich_root_data and not target_format.rich_root_data:
 
3158
            raise errors.BadConversionTarget(
 
3159
                'Does not support rich root data.', target_format,
 
3160
                from_format=self)
 
3161
        if (self.supports_tree_reference and 
 
3162
            not getattr(target_format, 'supports_tree_reference', False)):
 
3163
            raise errors.BadConversionTarget(
 
3164
                'Does not support nested trees', target_format,
 
3165
                from_format=self)
2221
3166
 
2222
3167
    def open(self, a_bzrdir, _found=False):
2223
3168
        """Return an instance of this format for the bzrdir a_bzrdir.
2224
 
        
 
3169
 
2225
3170
        _found is a private parameter, do not use it.
2226
3171
        """
2227
3172
        raise NotImplementedError(self.open)
2233
3178
    rich_root_data = False
2234
3179
    supports_tree_reference = False
2235
3180
    supports_external_lookups = False
2236
 
    _matchingbzrdir = bzrdir.BzrDirMetaFormat1()
 
3181
 
 
3182
    @property
 
3183
    def _matchingbzrdir(self):
 
3184
        matching = bzrdir.BzrDirMetaFormat1()
 
3185
        matching.repository_format = self
 
3186
        return matching
2237
3187
 
2238
3188
    def __init__(self):
2239
3189
        super(MetaDirRepositoryFormat, self).__init__()
2266
3216
        finally:
2267
3217
            control_files.unlock()
2268
3218
 
2269
 
 
2270
 
# formats which have no format string are not discoverable
2271
 
# and not independently creatable, so are not registered.  They're 
 
3219
    def network_name(self):
 
3220
        """Metadir formats have matching disk and network format strings."""
 
3221
        return self.get_format_string()
 
3222
 
 
3223
 
 
3224
# Pre-0.8 formats that don't have a disk format string (because they are
 
3225
# versioned by the matching control directory). We use the control directories
 
3226
# disk format string as a key for the network_name because they meet the
 
3227
# constraints (simple string, unique, immutable).
 
3228
network_format_registry.register_lazy(
 
3229
    "Bazaar-NG branch, format 5\n",
 
3230
    'bzrlib.repofmt.weaverepo',
 
3231
    'RepositoryFormat5',
 
3232
)
 
3233
network_format_registry.register_lazy(
 
3234
    "Bazaar-NG branch, format 6\n",
 
3235
    'bzrlib.repofmt.weaverepo',
 
3236
    'RepositoryFormat6',
 
3237
)
 
3238
 
 
3239
# formats which have no format string are not discoverable or independently
 
3240
# creatable on disk, so are not registered in format_registry.  They're
2272
3241
# all in bzrlib.repofmt.weaverepo now.  When an instance of one of these is
2273
3242
# needed, it's constructed directly by the BzrDir.  Non-native formats where
2274
3243
# the repository is not separately opened are similar.
2330
3299
    'bzrlib.repofmt.pack_repo',
2331
3300
    'RepositoryFormatKnitPack5RichRootBroken',
2332
3301
    )
 
3302
format_registry.register_lazy(
 
3303
    'Bazaar RepositoryFormatKnitPack6 (bzr 1.9)\n',
 
3304
    'bzrlib.repofmt.pack_repo',
 
3305
    'RepositoryFormatKnitPack6',
 
3306
    )
 
3307
format_registry.register_lazy(
 
3308
    'Bazaar RepositoryFormatKnitPack6RichRoot (bzr 1.9)\n',
 
3309
    'bzrlib.repofmt.pack_repo',
 
3310
    'RepositoryFormatKnitPack6RichRoot',
 
3311
    )
2333
3312
 
2334
 
# Development formats. 
2335
 
# 1.7->1.8 go below here
2336
 
format_registry.register_lazy(
2337
 
    "Bazaar development format 2 (needs bzr.dev from before 1.8)\n",
2338
 
    'bzrlib.repofmt.pack_repo',
2339
 
    'RepositoryFormatPackDevelopment2',
2340
 
    )
 
3313
# Development formats.
 
3314
# Obsolete but kept pending a CHK based subtree format.
2341
3315
format_registry.register_lazy(
2342
3316
    ("Bazaar development format 2 with subtree support "
2343
3317
        "(needs bzr.dev from before 1.8)\n"),
2345
3319
    'RepositoryFormatPackDevelopment2Subtree',
2346
3320
    )
2347
3321
 
 
3322
# 1.14->1.16 go below here
 
3323
format_registry.register_lazy(
 
3324
    'Bazaar development format - group compression and chk inventory'
 
3325
        ' (needs bzr.dev from 1.14)\n',
 
3326
    'bzrlib.repofmt.groupcompress_repo',
 
3327
    'RepositoryFormatCHK1',
 
3328
    )
 
3329
 
 
3330
format_registry.register_lazy(
 
3331
    'Bazaar development format - chk repository with bencode revision '
 
3332
        'serialization (needs bzr.dev from 1.16)\n',
 
3333
    'bzrlib.repofmt.groupcompress_repo',
 
3334
    'RepositoryFormatCHK2',
 
3335
    )
 
3336
format_registry.register_lazy(
 
3337
    'Bazaar repository format 2a (needs bzr 1.16 or later)\n',
 
3338
    'bzrlib.repofmt.groupcompress_repo',
 
3339
    'RepositoryFormat2a',
 
3340
    )
 
3341
 
2348
3342
 
2349
3343
class InterRepository(InterObject):
2350
3344
    """This class represents operations taking place between two repositories.
2351
3345
 
2352
3346
    Its instances have methods like copy_content and fetch, and contain
2353
 
    references to the source and target repositories these operations can be 
 
3347
    references to the source and target repositories these operations can be
2354
3348
    carried out on.
2355
3349
 
2356
3350
    Often we will provide convenience methods on 'repository' which carry out
2358
3352
    InterRepository.get(other).method_name(parameters).
2359
3353
    """
2360
3354
 
 
3355
    _walk_to_common_revisions_batch_size = 50
2361
3356
    _optimisers = []
2362
3357
    """The available optimised InterRepository types."""
2363
3358
 
 
3359
    @needs_write_lock
2364
3360
    def copy_content(self, revision_id=None):
2365
 
        raise NotImplementedError(self.copy_content)
2366
 
 
2367
 
    def fetch(self, revision_id=None, pb=None, find_ghosts=False):
 
3361
        """Make a complete copy of the content in self into destination.
 
3362
 
 
3363
        This is a destructive operation! Do not use it on existing
 
3364
        repositories.
 
3365
 
 
3366
        :param revision_id: Only copy the content needed to construct
 
3367
                            revision_id and its parents.
 
3368
        """
 
3369
        try:
 
3370
            self.target.set_make_working_trees(self.source.make_working_trees())
 
3371
        except NotImplementedError:
 
3372
            pass
 
3373
        self.target.fetch(self.source, revision_id=revision_id)
 
3374
 
 
3375
    @needs_write_lock
 
3376
    def fetch(self, revision_id=None, pb=None, find_ghosts=False,
 
3377
            fetch_spec=None):
2368
3378
        """Fetch the content required to construct revision_id.
2369
3379
 
2370
3380
        The content is copied from self.source to self.target.
2371
3381
 
2372
3382
        :param revision_id: if None all content is copied, if NULL_REVISION no
2373
3383
                            content is copied.
2374
 
        :param pb: optional progress bar to use for progress reports. If not
2375
 
                   provided a default one will be created.
2376
 
 
2377
 
        :returns: (copied_revision_count, failures).
 
3384
        :param pb: ignored.
 
3385
        :return: None.
2378
3386
        """
2379
 
        # Normally we should find a specific InterRepository subclass to do
2380
 
        # the fetch; if nothing else then at least InterSameDataRepository.
2381
 
        # If none of them is suitable it looks like fetching is not possible;
2382
 
        # we try to give a good message why.  _assert_same_model will probably
2383
 
        # give a helpful message; otherwise a generic one.
2384
 
        self._assert_same_model(self.source, self.target)
2385
 
        raise errors.IncompatibleRepositories(self.source, self.target,
2386
 
            "no suitableInterRepository found")
 
3387
        ui.ui_factory.warn_experimental_format_fetch(self)
 
3388
        from bzrlib.fetch import RepoFetcher
 
3389
        # See <https://launchpad.net/bugs/456077> asking for a warning here
 
3390
        if self.source._format.network_name() != self.target._format.network_name():
 
3391
            ui.ui_factory.show_user_warning('cross_format_fetch',
 
3392
                from_format=self.source._format,
 
3393
                to_format=self.target._format)
 
3394
        f = RepoFetcher(to_repository=self.target,
 
3395
                               from_repository=self.source,
 
3396
                               last_revision=revision_id,
 
3397
                               fetch_spec=fetch_spec,
 
3398
                               find_ghosts=find_ghosts)
2387
3399
 
2388
3400
    def _walk_to_common_revisions(self, revision_ids):
2389
3401
        """Walk out from revision_ids in source to revisions target has.
2393
3405
        """
2394
3406
        target_graph = self.target.get_graph()
2395
3407
        revision_ids = frozenset(revision_ids)
2396
 
        if set(target_graph.get_parent_map(revision_ids)) == revision_ids:
2397
 
            return graph.SearchResult(revision_ids, set(), 0, set())
2398
3408
        missing_revs = set()
2399
3409
        source_graph = self.source.get_graph()
2400
3410
        # ensure we don't pay silly lookup costs.
2401
3411
        searcher = source_graph._make_breadth_first_searcher(revision_ids)
2402
3412
        null_set = frozenset([_mod_revision.NULL_REVISION])
 
3413
        searcher_exhausted = False
2403
3414
        while True:
2404
 
            try:
2405
 
                next_revs, ghosts = searcher.next_with_ghosts()
2406
 
            except StopIteration:
2407
 
                break
2408
 
            if revision_ids.intersection(ghosts):
2409
 
                absent_ids = set(revision_ids.intersection(ghosts))
2410
 
                # If all absent_ids are present in target, no error is needed.
2411
 
                absent_ids.difference_update(
2412
 
                    set(target_graph.get_parent_map(absent_ids)))
2413
 
                if absent_ids:
2414
 
                    raise errors.NoSuchRevision(self.source, absent_ids.pop())
2415
 
            # we don't care about other ghosts as we can't fetch them and
 
3415
            next_revs = set()
 
3416
            ghosts = set()
 
3417
            # Iterate the searcher until we have enough next_revs
 
3418
            while len(next_revs) < self._walk_to_common_revisions_batch_size:
 
3419
                try:
 
3420
                    next_revs_part, ghosts_part = searcher.next_with_ghosts()
 
3421
                    next_revs.update(next_revs_part)
 
3422
                    ghosts.update(ghosts_part)
 
3423
                except StopIteration:
 
3424
                    searcher_exhausted = True
 
3425
                    break
 
3426
            # If there are ghosts in the source graph, and the caller asked for
 
3427
            # them, make sure that they are present in the target.
 
3428
            # We don't care about other ghosts as we can't fetch them and
2416
3429
            # haven't been asked to.
2417
 
            next_revs = set(next_revs)
2418
 
            # we always have NULL_REVISION present.
2419
 
            have_revs = set(target_graph.get_parent_map(next_revs)).union(null_set)
2420
 
            missing_revs.update(next_revs - have_revs)
2421
 
            searcher.stop_searching_any(have_revs)
 
3430
            ghosts_to_check = set(revision_ids.intersection(ghosts))
 
3431
            revs_to_get = set(next_revs).union(ghosts_to_check)
 
3432
            if revs_to_get:
 
3433
                have_revs = set(target_graph.get_parent_map(revs_to_get))
 
3434
                # we always have NULL_REVISION present.
 
3435
                have_revs = have_revs.union(null_set)
 
3436
                # Check if the target is missing any ghosts we need.
 
3437
                ghosts_to_check.difference_update(have_revs)
 
3438
                if ghosts_to_check:
 
3439
                    # One of the caller's revision_ids is a ghost in both the
 
3440
                    # source and the target.
 
3441
                    raise errors.NoSuchRevision(
 
3442
                        self.source, ghosts_to_check.pop())
 
3443
                missing_revs.update(next_revs - have_revs)
 
3444
                # Because we may have walked past the original stop point, make
 
3445
                # sure everything is stopped
 
3446
                stop_revs = searcher.find_seen_ancestors(have_revs)
 
3447
                searcher.stop_searching_any(stop_revs)
 
3448
            if searcher_exhausted:
 
3449
                break
2422
3450
        return searcher.get_result()
2423
 
   
2424
 
    @deprecated_method(one_two)
2425
 
    @needs_read_lock
2426
 
    def missing_revision_ids(self, revision_id=None, find_ghosts=True):
2427
 
        """Return the revision ids that source has that target does not.
2428
 
        
2429
 
        These are returned in topological order.
2430
 
 
2431
 
        :param revision_id: only return revision ids included by this
2432
 
                            revision_id.
2433
 
        :param find_ghosts: If True find missing revisions in deep history
2434
 
            rather than just finding the surface difference.
2435
 
        """
2436
 
        return list(self.search_missing_revision_ids(
2437
 
            revision_id, find_ghosts).get_keys())
2438
3451
 
2439
3452
    @needs_read_lock
2440
3453
    def search_missing_revision_ids(self, revision_id=None, find_ghosts=True):
2441
3454
        """Return the revision ids that source has that target does not.
2442
 
        
 
3455
 
2443
3456
        :param revision_id: only return revision ids included by this
2444
3457
                            revision_id.
2445
3458
        :param find_ghosts: If True find missing revisions in deep history
2464
3477
    @staticmethod
2465
3478
    def _same_model(source, target):
2466
3479
        """True if source and target have the same data representation.
2467
 
        
 
3480
 
2468
3481
        Note: this is always called on the base class; overriding it in a
2469
3482
        subclass will have no effect.
2470
3483
        """
2488
3501
 
2489
3502
class InterSameDataRepository(InterRepository):
2490
3503
    """Code for converting between repositories that represent the same data.
2491
 
    
 
3504
 
2492
3505
    Data format and model must match for this to work.
2493
3506
    """
2494
3507
 
2495
3508
    @classmethod
2496
3509
    def _get_repo_format_to_test(self):
2497
3510
        """Repository format for testing with.
2498
 
        
 
3511
 
2499
3512
        InterSameData can pull from subtree to subtree and from non-subtree to
2500
3513
        non-subtree, so we test this with the richest repository format.
2501
3514
        """
2506
3519
    def is_compatible(source, target):
2507
3520
        return InterRepository._same_model(source, target)
2508
3521
 
2509
 
    @needs_write_lock
2510
 
    def copy_content(self, revision_id=None):
2511
 
        """Make a complete copy of the content in self into destination.
2512
 
 
2513
 
        This copies both the repository's revision data, and configuration information
2514
 
        such as the make_working_trees setting.
2515
 
        
2516
 
        This is a destructive operation! Do not use it on existing 
2517
 
        repositories.
2518
 
 
2519
 
        :param revision_id: Only copy the content needed to construct
2520
 
                            revision_id and its parents.
2521
 
        """
2522
 
        try:
2523
 
            self.target.set_make_working_trees(self.source.make_working_trees())
2524
 
        except NotImplementedError:
2525
 
            pass
2526
 
        # but don't bother fetching if we have the needed data now.
2527
 
        if (revision_id not in (None, _mod_revision.NULL_REVISION) and 
2528
 
            self.target.has_revision(revision_id)):
2529
 
            return
2530
 
        self.target.fetch(self.source, revision_id=revision_id)
2531
 
 
2532
 
    @needs_write_lock
2533
 
    def fetch(self, revision_id=None, pb=None, find_ghosts=False):
2534
 
        """See InterRepository.fetch()."""
2535
 
        from bzrlib.fetch import RepoFetcher
2536
 
        mutter("Using fetch logic to copy between %s(%s) and %s(%s)",
2537
 
               self.source, self.source._format, self.target,
2538
 
               self.target._format)
2539
 
        f = RepoFetcher(to_repository=self.target,
2540
 
                               from_repository=self.source,
2541
 
                               last_revision=revision_id,
2542
 
                               pb=pb, find_ghosts=find_ghosts)
2543
 
        return f.count_copied, f.failed_revisions
2544
 
 
2545
3522
 
2546
3523
class InterWeaveRepo(InterSameDataRepository):
2547
3524
    """Optimised code paths between Weave based repositories.
2548
 
    
 
3525
 
2549
3526
    This should be in bzrlib/repofmt/weaverepo.py but we have not yet
2550
3527
    implemented lazy inter-object optimisation.
2551
3528
    """
2558
3535
    @staticmethod
2559
3536
    def is_compatible(source, target):
2560
3537
        """Be compatible with known Weave formats.
2561
 
        
 
3538
 
2562
3539
        We don't test for the stores being of specific types because that
2563
 
        could lead to confusing results, and there is no need to be 
 
3540
        could lead to confusing results, and there is no need to be
2564
3541
        overly general.
2565
3542
        """
2566
3543
        from bzrlib.repofmt.weaverepo import (
2577
3554
                                                RepositoryFormat7)))
2578
3555
        except AttributeError:
2579
3556
            return False
2580
 
    
 
3557
 
2581
3558
    @needs_write_lock
2582
3559
    def copy_content(self, revision_id=None):
2583
3560
        """See InterRepository.copy_content()."""
2593
3570
                self.target.texts.insert_record_stream(
2594
3571
                    self.source.texts.get_record_stream(
2595
3572
                        self.source.texts.keys(), 'topological', False))
2596
 
                pb.update('copying inventory', 0, 1)
 
3573
                pb.update('Copying inventory', 0, 1)
2597
3574
                self.target.inventories.insert_record_stream(
2598
3575
                    self.source.inventories.get_record_stream(
2599
3576
                        self.source.inventories.keys(), 'topological', False))
2610
3587
        else:
2611
3588
            self.target.fetch(self.source, revision_id=revision_id)
2612
3589
 
2613
 
    @needs_write_lock
2614
 
    def fetch(self, revision_id=None, pb=None, find_ghosts=False):
2615
 
        """See InterRepository.fetch()."""
2616
 
        from bzrlib.fetch import RepoFetcher
2617
 
        mutter("Using fetch logic to copy between %s(%s) and %s(%s)",
2618
 
               self.source, self.source._format, self.target, self.target._format)
2619
 
        f = RepoFetcher(to_repository=self.target,
2620
 
                               from_repository=self.source,
2621
 
                               last_revision=revision_id,
2622
 
                               pb=pb, find_ghosts=find_ghosts)
2623
 
        return f.count_copied, f.failed_revisions
2624
 
 
2625
3590
    @needs_read_lock
2626
3591
    def search_missing_revision_ids(self, revision_id=None, find_ghosts=True):
2627
3592
        """See InterRepository.missing_revision_ids()."""
2628
3593
        # we want all revisions to satisfy revision_id in source.
2629
3594
        # but we don't want to stat every file here and there.
2630
 
        # we want then, all revisions other needs to satisfy revision_id 
 
3595
        # we want then, all revisions other needs to satisfy revision_id
2631
3596
        # checked, but not those that we have locally.
2632
 
        # so the first thing is to get a subset of the revisions to 
 
3597
        # so the first thing is to get a subset of the revisions to
2633
3598
        # satisfy revision_id in source, and then eliminate those that
2634
 
        # we do already have. 
2635
 
        # this is slow on high latency connection to self, but as as this
2636
 
        # disk format scales terribly for push anyway due to rewriting 
 
3599
        # we do already have.
 
3600
        # this is slow on high latency connection to self, but as this
 
3601
        # disk format scales terribly for push anyway due to rewriting
2637
3602
        # inventory.weave, this is considered acceptable.
2638
3603
        # - RBC 20060209
2639
3604
        if revision_id is not None:
2659
3624
            # and the tip revision was validated by get_ancestry.
2660
3625
            result_set = required_revisions
2661
3626
        else:
2662
 
            # if we just grabbed the possibly available ids, then 
 
3627
            # if we just grabbed the possibly available ids, then
2663
3628
            # we only have an estimate of whats available and need to validate
2664
3629
            # that against the revision records.
2665
3630
            result_set = set(
2678
3643
    @staticmethod
2679
3644
    def is_compatible(source, target):
2680
3645
        """Be compatible with known Knit formats.
2681
 
        
 
3646
 
2682
3647
        We don't test for the stores being of specific types because that
2683
 
        could lead to confusing results, and there is no need to be 
 
3648
        could lead to confusing results, and there is no need to be
2684
3649
        overly general.
2685
3650
        """
2686
3651
        from bzrlib.repofmt.knitrepo import RepositoryFormatKnit
2691
3656
            return False
2692
3657
        return are_knits and InterRepository._same_model(source, target)
2693
3658
 
2694
 
    @needs_write_lock
2695
 
    def fetch(self, revision_id=None, pb=None, find_ghosts=False):
2696
 
        """See InterRepository.fetch()."""
2697
 
        from bzrlib.fetch import RepoFetcher
2698
 
        mutter("Using fetch logic to copy between %s(%s) and %s(%s)",
2699
 
               self.source, self.source._format, self.target, self.target._format)
2700
 
        f = RepoFetcher(to_repository=self.target,
2701
 
                            from_repository=self.source,
2702
 
                            last_revision=revision_id,
2703
 
                            pb=pb, find_ghosts=find_ghosts)
2704
 
        return f.count_copied, f.failed_revisions
2705
 
 
2706
3659
    @needs_read_lock
2707
3660
    def search_missing_revision_ids(self, revision_id=None, find_ghosts=True):
2708
3661
        """See InterRepository.missing_revision_ids()."""
2729
3682
            # and the tip revision was validated by get_ancestry.
2730
3683
            result_set = required_revisions
2731
3684
        else:
2732
 
            # if we just grabbed the possibly available ids, then 
 
3685
            # if we just grabbed the possibly available ids, then
2733
3686
            # we only have an estimate of whats available and need to validate
2734
3687
            # that against the revision records.
2735
3688
            result_set = set(
2737
3690
        return self.source.revision_ids_to_search_result(result_set)
2738
3691
 
2739
3692
 
2740
 
class InterPackRepo(InterSameDataRepository):
2741
 
    """Optimised code paths between Pack based repositories."""
2742
 
 
2743
 
    @classmethod
2744
 
    def _get_repo_format_to_test(self):
2745
 
        from bzrlib.repofmt import pack_repo
2746
 
        return pack_repo.RepositoryFormatKnitPack1()
2747
 
 
2748
 
    @staticmethod
2749
 
    def is_compatible(source, target):
2750
 
        """Be compatible with known Pack formats.
2751
 
        
2752
 
        We don't test for the stores being of specific types because that
2753
 
        could lead to confusing results, and there is no need to be 
2754
 
        overly general.
2755
 
        """
2756
 
        from bzrlib.repofmt.pack_repo import RepositoryFormatPack
2757
 
        try:
2758
 
            are_packs = (isinstance(source._format, RepositoryFormatPack) and
2759
 
                isinstance(target._format, RepositoryFormatPack))
2760
 
        except AttributeError:
2761
 
            return False
2762
 
        return are_packs and InterRepository._same_model(source, target)
2763
 
 
2764
 
    @needs_write_lock
2765
 
    def fetch(self, revision_id=None, pb=None, find_ghosts=False):
2766
 
        """See InterRepository.fetch()."""
2767
 
        if (len(self.source._fallback_repositories) > 0 or
2768
 
            len(self.target._fallback_repositories) > 0):
2769
 
            # The pack layer is not aware of fallback repositories, so when
2770
 
            # fetching from a stacked repository or into a stacked repository
2771
 
            # we use the generic fetch logic which uses the VersionedFiles
2772
 
            # attributes on repository.
2773
 
            from bzrlib.fetch import RepoFetcher
2774
 
            fetcher = RepoFetcher(self.target, self.source, revision_id,
2775
 
                                  pb, find_ghosts)
2776
 
            return fetcher.count_copied, fetcher.failed_revisions
2777
 
        from bzrlib.repofmt.pack_repo import Packer
2778
 
        mutter("Using fetch logic to copy between %s(%s) and %s(%s)",
2779
 
               self.source, self.source._format, self.target, self.target._format)
2780
 
        self.count_copied = 0
2781
 
        if revision_id is None:
2782
 
            # TODO:
2783
 
            # everything to do - use pack logic
2784
 
            # to fetch from all packs to one without
2785
 
            # inventory parsing etc, IFF nothing to be copied is in the target.
2786
 
            # till then:
2787
 
            source_revision_ids = frozenset(self.source.all_revision_ids())
2788
 
            revision_ids = source_revision_ids - \
2789
 
                frozenset(self.target.get_parent_map(source_revision_ids))
2790
 
            revision_keys = [(revid,) for revid in revision_ids]
2791
 
            index = self.target._pack_collection.revision_index.combined_index
2792
 
            present_revision_ids = set(item[1][0] for item in
2793
 
                index.iter_entries(revision_keys))
2794
 
            revision_ids = set(revision_ids) - present_revision_ids
2795
 
            # implementing the TODO will involve:
2796
 
            # - detecting when all of a pack is selected
2797
 
            # - avoiding as much as possible pre-selection, so the
2798
 
            # more-core routines such as create_pack_from_packs can filter in
2799
 
            # a just-in-time fashion. (though having a HEADS list on a
2800
 
            # repository might make this a lot easier, because we could
2801
 
            # sensibly detect 'new revisions' without doing a full index scan.
2802
 
        elif _mod_revision.is_null(revision_id):
2803
 
            # nothing to do:
2804
 
            return (0, [])
2805
 
        else:
2806
 
            try:
2807
 
                revision_ids = self.search_missing_revision_ids(revision_id,
2808
 
                    find_ghosts=find_ghosts).get_keys()
2809
 
            except errors.NoSuchRevision:
2810
 
                raise errors.InstallFailed([revision_id])
2811
 
            if len(revision_ids) == 0:
2812
 
                return (0, [])
2813
 
        packs = self.source._pack_collection.all_packs()
2814
 
        pack = Packer(self.target._pack_collection, packs, '.fetch',
2815
 
            revision_ids).pack()
2816
 
        if pack is not None:
2817
 
            self.target._pack_collection._save_pack_names()
2818
 
            # Trigger an autopack. This may duplicate effort as we've just done
2819
 
            # a pack creation, but for now it is simpler to think about as
2820
 
            # 'upload data, then repack if needed'.
2821
 
            self.target._pack_collection.autopack()
2822
 
            return (pack.get_revision_count(), [])
2823
 
        else:
2824
 
            return (0, [])
2825
 
 
2826
 
    @needs_read_lock
2827
 
    def search_missing_revision_ids(self, revision_id=None, find_ghosts=True):
2828
 
        """See InterRepository.missing_revision_ids().
2829
 
        
2830
 
        :param find_ghosts: Find ghosts throughout the ancestry of
2831
 
            revision_id.
2832
 
        """
2833
 
        if not find_ghosts and revision_id is not None:
2834
 
            return self._walk_to_common_revisions([revision_id])
2835
 
        elif revision_id is not None:
2836
 
            # Find ghosts: search for revisions pointing from one repository to
2837
 
            # the other, and vice versa, anywhere in the history of revision_id.
2838
 
            graph = self.target.get_graph(other_repository=self.source)
2839
 
            searcher = graph._make_breadth_first_searcher([revision_id])
2840
 
            found_ids = set()
2841
 
            while True:
2842
 
                try:
2843
 
                    next_revs, ghosts = searcher.next_with_ghosts()
2844
 
                except StopIteration:
2845
 
                    break
2846
 
                if revision_id in ghosts:
2847
 
                    raise errors.NoSuchRevision(self.source, revision_id)
2848
 
                found_ids.update(next_revs)
2849
 
                found_ids.update(ghosts)
2850
 
            found_ids = frozenset(found_ids)
2851
 
            # Double query here: should be able to avoid this by changing the
2852
 
            # graph api further.
2853
 
            result_set = found_ids - frozenset(
2854
 
                self.target.get_parent_map(found_ids))
2855
 
        else:
2856
 
            source_ids = self.source.all_revision_ids()
2857
 
            # source_ids is the worst possible case we may need to pull.
2858
 
            # now we want to filter source_ids against what we actually
2859
 
            # have in target, but don't try to check for existence where we know
2860
 
            # we do not have a revision as that would be pointless.
2861
 
            target_ids = set(self.target.all_revision_ids())
2862
 
            result_set = set(source_ids).difference(target_ids)
2863
 
        return self.source.revision_ids_to_search_result(result_set)
2864
 
 
2865
 
 
2866
 
class InterModel1and2(InterRepository):
2867
 
 
2868
 
    @classmethod
2869
 
    def _get_repo_format_to_test(self):
2870
 
        return None
2871
 
 
2872
 
    @staticmethod
2873
 
    def is_compatible(source, target):
2874
 
        if not source.supports_rich_root() and target.supports_rich_root():
2875
 
            return True
2876
 
        else:
2877
 
            return False
2878
 
 
2879
 
    @needs_write_lock
2880
 
    def fetch(self, revision_id=None, pb=None, find_ghosts=False):
2881
 
        """See InterRepository.fetch()."""
2882
 
        from bzrlib.fetch import Model1toKnit2Fetcher
2883
 
        f = Model1toKnit2Fetcher(to_repository=self.target,
2884
 
                                 from_repository=self.source,
2885
 
                                 last_revision=revision_id,
2886
 
                                 pb=pb, find_ghosts=find_ghosts)
2887
 
        return f.count_copied, f.failed_revisions
2888
 
 
2889
 
    @needs_write_lock
2890
 
    def copy_content(self, revision_id=None):
2891
 
        """Make a complete copy of the content in self into destination.
2892
 
        
2893
 
        This is a destructive operation! Do not use it on existing 
2894
 
        repositories.
2895
 
 
2896
 
        :param revision_id: Only copy the content needed to construct
2897
 
                            revision_id and its parents.
2898
 
        """
2899
 
        try:
2900
 
            self.target.set_make_working_trees(self.source.make_working_trees())
2901
 
        except NotImplementedError:
2902
 
            pass
2903
 
        # but don't bother fetching if we have the needed data now.
2904
 
        if (revision_id not in (None, _mod_revision.NULL_REVISION) and 
2905
 
            self.target.has_revision(revision_id)):
2906
 
            return
2907
 
        self.target.fetch(self.source, revision_id=revision_id)
2908
 
 
2909
 
 
2910
 
class InterKnit1and2(InterKnitRepo):
2911
 
 
2912
 
    @classmethod
2913
 
    def _get_repo_format_to_test(self):
2914
 
        return None
2915
 
 
2916
 
    @staticmethod
2917
 
    def is_compatible(source, target):
2918
 
        """Be compatible with Knit1 source and Knit3 target"""
2919
 
        try:
2920
 
            from bzrlib.repofmt.knitrepo import (
2921
 
                RepositoryFormatKnit1,
2922
 
                RepositoryFormatKnit3,
2923
 
                )
2924
 
            from bzrlib.repofmt.pack_repo import (
2925
 
                RepositoryFormatKnitPack1,
2926
 
                RepositoryFormatKnitPack3,
2927
 
                RepositoryFormatKnitPack4,
2928
 
                RepositoryFormatKnitPack5,
2929
 
                RepositoryFormatKnitPack5RichRoot,
2930
 
                RepositoryFormatPackDevelopment2,
2931
 
                RepositoryFormatPackDevelopment2Subtree,
2932
 
                )
2933
 
            norichroot = (
2934
 
                RepositoryFormatKnit1,            # no rr, no subtree
2935
 
                RepositoryFormatKnitPack1,        # no rr, no subtree
2936
 
                RepositoryFormatPackDevelopment2, # no rr, no subtree
2937
 
                RepositoryFormatKnitPack5,        # no rr, no subtree
2938
 
                )
2939
 
            richroot = (
2940
 
                RepositoryFormatKnit3,            # rr, subtree
2941
 
                RepositoryFormatKnitPack3,        # rr, subtree
2942
 
                RepositoryFormatKnitPack4,        # rr, no subtree
2943
 
                RepositoryFormatKnitPack5RichRoot,# rr, no subtree
2944
 
                RepositoryFormatPackDevelopment2Subtree, # rr, subtree
2945
 
                )
2946
 
            for format in norichroot:
2947
 
                if format.rich_root_data:
2948
 
                    raise AssertionError('Format %s is a rich-root format'
2949
 
                        ' but is included in the non-rich-root list'
2950
 
                        % (format,))
2951
 
            for format in richroot:
2952
 
                if not format.rich_root_data:
2953
 
                    raise AssertionError('Format %s is not a rich-root format'
2954
 
                        ' but is included in the rich-root list'
2955
 
                        % (format,))
2956
 
            # TODO: One alternative is to just check format.rich_root_data,
2957
 
            #       instead of keeping membership lists. However, the formats
2958
 
            #       *also* have to use the same 'Knit' style of storage
2959
 
            #       (line-deltas, fulltexts, etc.)
2960
 
            return (isinstance(source._format, norichroot) and
2961
 
                    isinstance(target._format, richroot))
2962
 
        except AttributeError:
2963
 
            return False
2964
 
 
2965
 
    @needs_write_lock
2966
 
    def fetch(self, revision_id=None, pb=None, find_ghosts=False):
2967
 
        """See InterRepository.fetch()."""
2968
 
        from bzrlib.fetch import Knit1to2Fetcher
2969
 
        mutter("Using fetch logic to copy between %s(%s) and %s(%s)",
2970
 
               self.source, self.source._format, self.target, 
2971
 
               self.target._format)
2972
 
        f = Knit1to2Fetcher(to_repository=self.target,
2973
 
                            from_repository=self.source,
2974
 
                            last_revision=revision_id,
2975
 
                            pb=pb, find_ghosts=find_ghosts)
2976
 
        return f.count_copied, f.failed_revisions
2977
 
 
2978
 
 
2979
 
class InterDifferingSerializer(InterKnitRepo):
 
3693
class InterDifferingSerializer(InterRepository):
2980
3694
 
2981
3695
    @classmethod
2982
3696
    def _get_repo_format_to_test(self):
2985
3699
    @staticmethod
2986
3700
    def is_compatible(source, target):
2987
3701
        """Be compatible with Knit2 source and Knit3 target"""
2988
 
        if source.supports_rich_root() != target.supports_rich_root():
2989
 
            return False
2990
 
        # Ideally, we'd support fetching if the source had no tree references
2991
 
        # even if it supported them...
2992
 
        if (getattr(source, '_format.supports_tree_reference', False) and
2993
 
            not getattr(target, '_format.supports_tree_reference', False)):
 
3702
        # This is redundant with format.check_conversion_target(), however that
 
3703
        # raises an exception, and we just want to say "False" as in we won't
 
3704
        # support converting between these formats.
 
3705
        if 'IDS_never' in debug.debug_flags:
 
3706
            return False
 
3707
        if source.supports_rich_root() and not target.supports_rich_root():
 
3708
            return False
 
3709
        if (source._format.supports_tree_reference
 
3710
            and not target._format.supports_tree_reference):
 
3711
            return False
 
3712
        if target._fallback_repositories and target._format.supports_chks:
 
3713
            # IDS doesn't know how to copy CHKs for the parent inventories it
 
3714
            # adds to stacked repos.
 
3715
            return False
 
3716
        if 'IDS_always' in debug.debug_flags:
 
3717
            return True
 
3718
        # Only use this code path for local source and target.  IDS does far
 
3719
        # too much IO (both bandwidth and roundtrips) over a network.
 
3720
        if not source.bzrdir.transport.base.startswith('file:///'):
 
3721
            return False
 
3722
        if not target.bzrdir.transport.base.startswith('file:///'):
2994
3723
            return False
2995
3724
        return True
2996
3725
 
 
3726
    def _get_trees(self, revision_ids, cache):
 
3727
        possible_trees = []
 
3728
        for rev_id in revision_ids:
 
3729
            if rev_id in cache:
 
3730
                possible_trees.append((rev_id, cache[rev_id]))
 
3731
            else:
 
3732
                # Not cached, but inventory might be present anyway.
 
3733
                try:
 
3734
                    tree = self.source.revision_tree(rev_id)
 
3735
                except errors.NoSuchRevision:
 
3736
                    # Nope, parent is ghost.
 
3737
                    pass
 
3738
                else:
 
3739
                    cache[rev_id] = tree
 
3740
                    possible_trees.append((rev_id, tree))
 
3741
        return possible_trees
 
3742
 
 
3743
    def _get_delta_for_revision(self, tree, parent_ids, possible_trees):
 
3744
        """Get the best delta and base for this revision.
 
3745
 
 
3746
        :return: (basis_id, delta)
 
3747
        """
 
3748
        deltas = []
 
3749
        # Generate deltas against each tree, to find the shortest.
 
3750
        texts_possibly_new_in_tree = set()
 
3751
        for basis_id, basis_tree in possible_trees:
 
3752
            delta = tree.inventory._make_delta(basis_tree.inventory)
 
3753
            for old_path, new_path, file_id, new_entry in delta:
 
3754
                if new_path is None:
 
3755
                    # This file_id isn't present in the new rev, so we don't
 
3756
                    # care about it.
 
3757
                    continue
 
3758
                if not new_path:
 
3759
                    # Rich roots are handled elsewhere...
 
3760
                    continue
 
3761
                kind = new_entry.kind
 
3762
                if kind != 'directory' and kind != 'file':
 
3763
                    # No text record associated with this inventory entry.
 
3764
                    continue
 
3765
                # This is a directory or file that has changed somehow.
 
3766
                texts_possibly_new_in_tree.add((file_id, new_entry.revision))
 
3767
            deltas.append((len(delta), basis_id, delta))
 
3768
        deltas.sort()
 
3769
        return deltas[0][1:]
 
3770
 
 
3771
    def _fetch_parent_invs_for_stacking(self, parent_map, cache):
 
3772
        """Find all parent revisions that are absent, but for which the
 
3773
        inventory is present, and copy those inventories.
 
3774
 
 
3775
        This is necessary to preserve correctness when the source is stacked
 
3776
        without fallbacks configured.  (Note that in cases like upgrade the
 
3777
        source may be not have _fallback_repositories even though it is
 
3778
        stacked.)
 
3779
        """
 
3780
        parent_revs = set()
 
3781
        for parents in parent_map.values():
 
3782
            parent_revs.update(parents)
 
3783
        present_parents = self.source.get_parent_map(parent_revs)
 
3784
        absent_parents = set(parent_revs).difference(present_parents)
 
3785
        parent_invs_keys_for_stacking = self.source.inventories.get_parent_map(
 
3786
            (rev_id,) for rev_id in absent_parents)
 
3787
        parent_inv_ids = [key[-1] for key in parent_invs_keys_for_stacking]
 
3788
        for parent_tree in self.source.revision_trees(parent_inv_ids):
 
3789
            current_revision_id = parent_tree.get_revision_id()
 
3790
            parents_parents_keys = parent_invs_keys_for_stacking[
 
3791
                (current_revision_id,)]
 
3792
            parents_parents = [key[-1] for key in parents_parents_keys]
 
3793
            basis_id = _mod_revision.NULL_REVISION
 
3794
            basis_tree = self.source.revision_tree(basis_id)
 
3795
            delta = parent_tree.inventory._make_delta(basis_tree.inventory)
 
3796
            self.target.add_inventory_by_delta(
 
3797
                basis_id, delta, current_revision_id, parents_parents)
 
3798
            cache[current_revision_id] = parent_tree
 
3799
 
 
3800
    def _fetch_batch(self, revision_ids, basis_id, cache, a_graph=None):
 
3801
        """Fetch across a few revisions.
 
3802
 
 
3803
        :param revision_ids: The revisions to copy
 
3804
        :param basis_id: The revision_id of a tree that must be in cache, used
 
3805
            as a basis for delta when no other base is available
 
3806
        :param cache: A cache of RevisionTrees that we can use.
 
3807
        :param a_graph: A Graph object to determine the heads() of the
 
3808
            rich-root data stream.
 
3809
        :return: The revision_id of the last converted tree. The RevisionTree
 
3810
            for it will be in cache
 
3811
        """
 
3812
        # Walk though all revisions; get inventory deltas, copy referenced
 
3813
        # texts that delta references, insert the delta, revision and
 
3814
        # signature.
 
3815
        root_keys_to_create = set()
 
3816
        text_keys = set()
 
3817
        pending_deltas = []
 
3818
        pending_revisions = []
 
3819
        parent_map = self.source.get_parent_map(revision_ids)
 
3820
        self._fetch_parent_invs_for_stacking(parent_map, cache)
 
3821
        self.source._safe_to_return_from_cache = True
 
3822
        for tree in self.source.revision_trees(revision_ids):
 
3823
            # Find a inventory delta for this revision.
 
3824
            # Find text entries that need to be copied, too.
 
3825
            current_revision_id = tree.get_revision_id()
 
3826
            parent_ids = parent_map.get(current_revision_id, ())
 
3827
            parent_trees = self._get_trees(parent_ids, cache)
 
3828
            possible_trees = list(parent_trees)
 
3829
            if len(possible_trees) == 0:
 
3830
                # There either aren't any parents, or the parents are ghosts,
 
3831
                # so just use the last converted tree.
 
3832
                possible_trees.append((basis_id, cache[basis_id]))
 
3833
            basis_id, delta = self._get_delta_for_revision(tree, parent_ids,
 
3834
                                                           possible_trees)
 
3835
            revision = self.source.get_revision(current_revision_id)
 
3836
            pending_deltas.append((basis_id, delta,
 
3837
                current_revision_id, revision.parent_ids))
 
3838
            if self._converting_to_rich_root:
 
3839
                self._revision_id_to_root_id[current_revision_id] = \
 
3840
                    tree.get_root_id()
 
3841
            # Determine which texts are in present in this revision but not in
 
3842
            # any of the available parents.
 
3843
            texts_possibly_new_in_tree = set()
 
3844
            for old_path, new_path, file_id, entry in delta:
 
3845
                if new_path is None:
 
3846
                    # This file_id isn't present in the new rev
 
3847
                    continue
 
3848
                if not new_path:
 
3849
                    # This is the root
 
3850
                    if not self.target.supports_rich_root():
 
3851
                        # The target doesn't support rich root, so we don't
 
3852
                        # copy
 
3853
                        continue
 
3854
                    if self._converting_to_rich_root:
 
3855
                        # This can't be copied normally, we have to insert
 
3856
                        # it specially
 
3857
                        root_keys_to_create.add((file_id, entry.revision))
 
3858
                        continue
 
3859
                kind = entry.kind
 
3860
                texts_possibly_new_in_tree.add((file_id, entry.revision))
 
3861
            for basis_id, basis_tree in possible_trees:
 
3862
                basis_inv = basis_tree.inventory
 
3863
                for file_key in list(texts_possibly_new_in_tree):
 
3864
                    file_id, file_revision = file_key
 
3865
                    try:
 
3866
                        entry = basis_inv[file_id]
 
3867
                    except errors.NoSuchId:
 
3868
                        continue
 
3869
                    if entry.revision == file_revision:
 
3870
                        texts_possibly_new_in_tree.remove(file_key)
 
3871
            text_keys.update(texts_possibly_new_in_tree)
 
3872
            pending_revisions.append(revision)
 
3873
            cache[current_revision_id] = tree
 
3874
            basis_id = current_revision_id
 
3875
        self.source._safe_to_return_from_cache = False
 
3876
        # Copy file texts
 
3877
        from_texts = self.source.texts
 
3878
        to_texts = self.target.texts
 
3879
        if root_keys_to_create:
 
3880
            root_stream = _mod_fetch._new_root_data_stream(
 
3881
                root_keys_to_create, self._revision_id_to_root_id, parent_map,
 
3882
                self.source, graph=a_graph)
 
3883
            to_texts.insert_record_stream(root_stream)
 
3884
        to_texts.insert_record_stream(from_texts.get_record_stream(
 
3885
            text_keys, self.target._format._fetch_order,
 
3886
            not self.target._format._fetch_uses_deltas))
 
3887
        # insert inventory deltas
 
3888
        for delta in pending_deltas:
 
3889
            self.target.add_inventory_by_delta(*delta)
 
3890
        if self.target._fallback_repositories:
 
3891
            # Make sure this stacked repository has all the parent inventories
 
3892
            # for the new revisions that we are about to insert.  We do this
 
3893
            # before adding the revisions so that no revision is added until
 
3894
            # all the inventories it may depend on are added.
 
3895
            # Note that this is overzealous, as we may have fetched these in an
 
3896
            # earlier batch.
 
3897
            parent_ids = set()
 
3898
            revision_ids = set()
 
3899
            for revision in pending_revisions:
 
3900
                revision_ids.add(revision.revision_id)
 
3901
                parent_ids.update(revision.parent_ids)
 
3902
            parent_ids.difference_update(revision_ids)
 
3903
            parent_ids.discard(_mod_revision.NULL_REVISION)
 
3904
            parent_map = self.source.get_parent_map(parent_ids)
 
3905
            # we iterate over parent_map and not parent_ids because we don't
 
3906
            # want to try copying any revision which is a ghost
 
3907
            for parent_tree in self.source.revision_trees(parent_map):
 
3908
                current_revision_id = parent_tree.get_revision_id()
 
3909
                parents_parents = parent_map[current_revision_id]
 
3910
                possible_trees = self._get_trees(parents_parents, cache)
 
3911
                if len(possible_trees) == 0:
 
3912
                    # There either aren't any parents, or the parents are
 
3913
                    # ghosts, so just use the last converted tree.
 
3914
                    possible_trees.append((basis_id, cache[basis_id]))
 
3915
                basis_id, delta = self._get_delta_for_revision(parent_tree,
 
3916
                    parents_parents, possible_trees)
 
3917
                self.target.add_inventory_by_delta(
 
3918
                    basis_id, delta, current_revision_id, parents_parents)
 
3919
        # insert signatures and revisions
 
3920
        for revision in pending_revisions:
 
3921
            try:
 
3922
                signature = self.source.get_signature_text(
 
3923
                    revision.revision_id)
 
3924
                self.target.add_signature_text(revision.revision_id,
 
3925
                    signature)
 
3926
            except errors.NoSuchRevision:
 
3927
                pass
 
3928
            self.target.add_revision(revision.revision_id, revision)
 
3929
        return basis_id
 
3930
 
 
3931
    def _fetch_all_revisions(self, revision_ids, pb):
 
3932
        """Fetch everything for the list of revisions.
 
3933
 
 
3934
        :param revision_ids: The list of revisions to fetch. Must be in
 
3935
            topological order.
 
3936
        :param pb: A ProgressTask
 
3937
        :return: None
 
3938
        """
 
3939
        basis_id, basis_tree = self._get_basis(revision_ids[0])
 
3940
        batch_size = 100
 
3941
        cache = lru_cache.LRUCache(100)
 
3942
        cache[basis_id] = basis_tree
 
3943
        del basis_tree # We don't want to hang on to it here
 
3944
        hints = []
 
3945
        if self._converting_to_rich_root and len(revision_ids) > 100:
 
3946
            a_graph = _mod_fetch._get_rich_root_heads_graph(self.source,
 
3947
                                                            revision_ids)
 
3948
        else:
 
3949
            a_graph = None
 
3950
 
 
3951
        for offset in range(0, len(revision_ids), batch_size):
 
3952
            self.target.start_write_group()
 
3953
            try:
 
3954
                pb.update('Transferring revisions', offset,
 
3955
                          len(revision_ids))
 
3956
                batch = revision_ids[offset:offset+batch_size]
 
3957
                basis_id = self._fetch_batch(batch, basis_id, cache,
 
3958
                                             a_graph=a_graph)
 
3959
            except:
 
3960
                self.source._safe_to_return_from_cache = False
 
3961
                self.target.abort_write_group()
 
3962
                raise
 
3963
            else:
 
3964
                hint = self.target.commit_write_group()
 
3965
                if hint:
 
3966
                    hints.extend(hint)
 
3967
        if hints and self.target._format.pack_compresses:
 
3968
            self.target.pack(hint=hints)
 
3969
        pb.update('Transferring revisions', len(revision_ids),
 
3970
                  len(revision_ids))
 
3971
 
2997
3972
    @needs_write_lock
2998
 
    def fetch(self, revision_id=None, pb=None, find_ghosts=False):
 
3973
    def fetch(self, revision_id=None, pb=None, find_ghosts=False,
 
3974
            fetch_spec=None):
2999
3975
        """See InterRepository.fetch()."""
 
3976
        if fetch_spec is not None:
 
3977
            raise AssertionError("Not implemented yet...")
 
3978
        ui.ui_factory.warn_experimental_format_fetch(self)
 
3979
        if (not self.source.supports_rich_root()
 
3980
            and self.target.supports_rich_root()):
 
3981
            self._converting_to_rich_root = True
 
3982
            self._revision_id_to_root_id = {}
 
3983
        else:
 
3984
            self._converting_to_rich_root = False
 
3985
        # See <https://launchpad.net/bugs/456077> asking for a warning here
 
3986
        if self.source._format.network_name() != self.target._format.network_name():
 
3987
            ui.ui_factory.show_user_warning('cross_format_fetch',
 
3988
                from_format=self.source._format,
 
3989
                to_format=self.target._format)
3000
3990
        revision_ids = self.target.search_missing_revision_ids(self.source,
3001
3991
            revision_id, find_ghosts=find_ghosts).get_keys()
 
3992
        if not revision_ids:
 
3993
            return 0, 0
3002
3994
        revision_ids = tsort.topo_sort(
3003
3995
            self.source.get_graph().get_parent_map(revision_ids))
3004
 
        def revisions_iterator():
3005
 
            for current_revision_id in revision_ids:
3006
 
                revision = self.source.get_revision(current_revision_id)
3007
 
                tree = self.source.revision_tree(current_revision_id)
3008
 
                try:
3009
 
                    signature = self.source.get_signature_text(
3010
 
                        current_revision_id)
3011
 
                except errors.NoSuchRevision:
3012
 
                    signature = None
3013
 
                yield revision, tree, signature
 
3996
        if not revision_ids:
 
3997
            return 0, 0
 
3998
        # Walk though all revisions; get inventory deltas, copy referenced
 
3999
        # texts that delta references, insert the delta, revision and
 
4000
        # signature.
3014
4001
        if pb is None:
3015
4002
            my_pb = ui.ui_factory.nested_progress_bar()
3016
4003
            pb = my_pb
3017
4004
        else:
 
4005
            symbol_versioning.warn(
 
4006
                symbol_versioning.deprecated_in((1, 14, 0))
 
4007
                % "pb parameter to fetch()")
3018
4008
            my_pb = None
3019
4009
        try:
3020
 
            install_revisions(self.target, revisions_iterator(),
3021
 
                              len(revision_ids), pb)
 
4010
            self._fetch_all_revisions(revision_ids, pb)
3022
4011
        finally:
3023
4012
            if my_pb is not None:
3024
4013
                my_pb.finished()
3025
4014
        return len(revision_ids), 0
3026
4015
 
3027
 
 
3028
 
class InterOtherToRemote(InterRepository):
3029
 
 
3030
 
    def __init__(self, source, target):
3031
 
        InterRepository.__init__(self, source, target)
3032
 
        self._real_inter = None
3033
 
 
3034
 
    @staticmethod
3035
 
    def is_compatible(source, target):
3036
 
        if isinstance(target, remote.RemoteRepository):
3037
 
            return True
3038
 
        return False
3039
 
 
3040
 
    def _ensure_real_inter(self):
3041
 
        if self._real_inter is None:
3042
 
            self.target._ensure_real()
3043
 
            real_target = self.target._real_repository
3044
 
            self._real_inter = InterRepository.get(self.source, real_target)
3045
 
    
3046
 
    def copy_content(self, revision_id=None):
3047
 
        self._ensure_real_inter()
3048
 
        self._real_inter.copy_content(revision_id=revision_id)
3049
 
 
3050
 
    def fetch(self, revision_id=None, pb=None, find_ghosts=False):
3051
 
        self._ensure_real_inter()
3052
 
        return self._real_inter.fetch(revision_id=revision_id, pb=pb,
3053
 
            find_ghosts=find_ghosts)
3054
 
 
3055
 
    @classmethod
3056
 
    def _get_repo_format_to_test(self):
3057
 
        return None
3058
 
 
3059
 
 
3060
 
class InterRemoteToOther(InterRepository):
3061
 
 
3062
 
    def __init__(self, source, target):
3063
 
        InterRepository.__init__(self, source, target)
3064
 
        self._real_inter = None
3065
 
 
3066
 
    @staticmethod
3067
 
    def is_compatible(source, target):
3068
 
        if not isinstance(source, remote.RemoteRepository):
3069
 
            return False
3070
 
        # Is source's model compatible with target's model?
3071
 
        source._ensure_real()
3072
 
        real_source = source._real_repository
3073
 
        if isinstance(real_source, remote.RemoteRepository):
3074
 
            raise NotImplementedError(
3075
 
                "We don't support remote repos backed by remote repos yet.")
3076
 
        return InterRepository._same_model(real_source, target)
3077
 
 
3078
 
    def _ensure_real_inter(self):
3079
 
        if self._real_inter is None:
3080
 
            self.source._ensure_real()
3081
 
            real_source = self.source._real_repository
3082
 
            self._real_inter = InterRepository.get(real_source, self.target)
3083
 
    
3084
 
    def fetch(self, revision_id=None, pb=None, find_ghosts=False):
3085
 
        self._ensure_real_inter()
3086
 
        return self._real_inter.fetch(revision_id=revision_id, pb=pb,
3087
 
            find_ghosts=find_ghosts)
3088
 
 
3089
 
    def copy_content(self, revision_id=None):
3090
 
        self._ensure_real_inter()
3091
 
        self._real_inter.copy_content(revision_id=revision_id)
3092
 
 
3093
 
    @classmethod
3094
 
    def _get_repo_format_to_test(self):
3095
 
        return None
3096
 
 
 
4016
    def _get_basis(self, first_revision_id):
 
4017
        """Get a revision and tree which exists in the target.
 
4018
 
 
4019
        This assumes that first_revision_id is selected for transmission
 
4020
        because all other ancestors are already present. If we can't find an
 
4021
        ancestor we fall back to NULL_REVISION since we know that is safe.
 
4022
 
 
4023
        :return: (basis_id, basis_tree)
 
4024
        """
 
4025
        first_rev = self.source.get_revision(first_revision_id)
 
4026
        try:
 
4027
            basis_id = first_rev.parent_ids[0]
 
4028
            # only valid as a basis if the target has it
 
4029
            self.target.get_revision(basis_id)
 
4030
            # Try to get a basis tree - if its a ghost it will hit the
 
4031
            # NoSuchRevision case.
 
4032
            basis_tree = self.source.revision_tree(basis_id)
 
4033
        except (IndexError, errors.NoSuchRevision):
 
4034
            basis_id = _mod_revision.NULL_REVISION
 
4035
            basis_tree = self.source.revision_tree(basis_id)
 
4036
        return basis_id, basis_tree
3097
4037
 
3098
4038
 
3099
4039
InterRepository.register_optimiser(InterDifferingSerializer)
3100
4040
InterRepository.register_optimiser(InterSameDataRepository)
3101
4041
InterRepository.register_optimiser(InterWeaveRepo)
3102
4042
InterRepository.register_optimiser(InterKnitRepo)
3103
 
InterRepository.register_optimiser(InterModel1and2)
3104
 
InterRepository.register_optimiser(InterKnit1and2)
3105
 
InterRepository.register_optimiser(InterPackRepo)
3106
 
InterRepository.register_optimiser(InterOtherToRemote)
3107
 
InterRepository.register_optimiser(InterRemoteToOther)
3108
4043
 
3109
4044
 
3110
4045
class CopyConverter(object):
3111
4046
    """A repository conversion tool which just performs a copy of the content.
3112
 
    
 
4047
 
3113
4048
    This is slow but quite reliable.
3114
4049
    """
3115
4050
 
3119
4054
        :param target_format: The format the resulting repository should be.
3120
4055
        """
3121
4056
        self.target_format = target_format
3122
 
        
 
4057
 
3123
4058
    def convert(self, repo, pb):
3124
4059
        """Perform the conversion of to_convert, giving feedback via pb.
3125
4060
 
3126
4061
        :param to_convert: The disk object to convert.
3127
4062
        :param pb: a progress bar to use for progress information.
3128
4063
        """
3129
 
        self.pb = pb
 
4064
        pb = ui.ui_factory.nested_progress_bar()
3130
4065
        self.count = 0
3131
4066
        self.total = 4
3132
4067
        # this is only useful with metadir layouts - separated repo content.
3133
4068
        # trigger an assertion if not such
3134
4069
        repo._format.get_format_string()
3135
4070
        self.repo_dir = repo.bzrdir
3136
 
        self.step('Moving repository to repository.backup')
 
4071
        pb.update('Moving repository to repository.backup')
3137
4072
        self.repo_dir.transport.move('repository', 'repository.backup')
3138
4073
        backup_transport =  self.repo_dir.transport.clone('repository.backup')
3139
4074
        repo._format.check_conversion_target(self.target_format)
3140
4075
        self.source_repo = repo._format.open(self.repo_dir,
3141
4076
            _found=True,
3142
4077
            _override_transport=backup_transport)
3143
 
        self.step('Creating new repository')
 
4078
        pb.update('Creating new repository')
3144
4079
        converted = self.target_format.initialize(self.repo_dir,
3145
4080
                                                  self.source_repo.is_shared())
3146
4081
        converted.lock_write()
3147
4082
        try:
3148
 
            self.step('Copying content into repository.')
 
4083
            pb.update('Copying content')
3149
4084
            self.source_repo.copy_content_into(converted)
3150
4085
        finally:
3151
4086
            converted.unlock()
3152
 
        self.step('Deleting old repository content.')
 
4087
        pb.update('Deleting old repository content')
3153
4088
        self.repo_dir.transport.delete_tree('repository.backup')
3154
 
        self.pb.note('repository converted')
3155
 
 
3156
 
    def step(self, message):
3157
 
        """Update the pb by a step."""
3158
 
        self.count +=1
3159
 
        self.pb.update(message, self.count, self.total)
 
4089
        ui.ui_factory.note('repository converted')
 
4090
        pb.finished()
3160
4091
 
3161
4092
 
3162
4093
_unescape_map = {
3191
4122
 
3192
4123
class _VersionedFileChecker(object):
3193
4124
 
3194
 
    def __init__(self, repository):
 
4125
    def __init__(self, repository, text_key_references=None, ancestors=None):
3195
4126
        self.repository = repository
3196
 
        self.text_index = self.repository._generate_text_key_index()
3197
 
    
 
4127
        self.text_index = self.repository._generate_text_key_index(
 
4128
            text_key_references=text_key_references, ancestors=ancestors)
 
4129
 
3198
4130
    def calculate_file_version_parents(self, text_key):
3199
4131
        """Calculate the correct parents for a file version according to
3200
4132
        the inventories.
3217
4149
            revision_id) tuples for versions that are present in this versioned
3218
4150
            file, but not used by the corresponding inventory.
3219
4151
        """
 
4152
        local_progress = None
 
4153
        if progress_bar is None:
 
4154
            local_progress = ui.ui_factory.nested_progress_bar()
 
4155
            progress_bar = local_progress
 
4156
        try:
 
4157
            return self._check_file_version_parents(texts, progress_bar)
 
4158
        finally:
 
4159
            if local_progress:
 
4160
                local_progress.finished()
 
4161
 
 
4162
    def _check_file_version_parents(self, texts, progress_bar):
 
4163
        """See check_file_version_parents."""
3220
4164
        wrong_parents = {}
3221
4165
        self.file_ids = set([file_id for file_id, _ in
3222
4166
            self.text_index.iterkeys()])
3223
4167
        # text keys is now grouped by file_id
3224
 
        n_weaves = len(self.file_ids)
3225
 
        files_in_revisions = {}
3226
 
        revisions_of_files = {}
3227
4168
        n_versions = len(self.text_index)
3228
4169
        progress_bar.update('loading text store', 0, n_versions)
3229
4170
        parent_map = self.repository.texts.get_parent_map(self.text_index)
3231
4172
        text_keys = self.repository.texts.keys()
3232
4173
        unused_keys = frozenset(text_keys) - set(self.text_index)
3233
4174
        for num, key in enumerate(self.text_index.iterkeys()):
3234
 
            if progress_bar is not None:
3235
 
                progress_bar.update('checking text graph', num, n_versions)
 
4175
            progress_bar.update('checking text graph', num, n_versions)
3236
4176
            correct_parents = self.calculate_file_version_parents(key)
3237
4177
            try:
3238
4178
                knit_parents = parent_map[key]
3261
4201
        revision_graph[key] = tuple(parent for parent in parents if parent
3262
4202
            in revision_graph)
3263
4203
    return revision_graph
 
4204
 
 
4205
 
 
4206
class StreamSink(object):
 
4207
    """An object that can insert a stream into a repository.
 
4208
 
 
4209
    This interface handles the complexity of reserialising inventories and
 
4210
    revisions from different formats, and allows unidirectional insertion into
 
4211
    stacked repositories without looking for the missing basis parents
 
4212
    beforehand.
 
4213
    """
 
4214
 
 
4215
    def __init__(self, target_repo):
 
4216
        self.target_repo = target_repo
 
4217
 
 
4218
    def insert_stream(self, stream, src_format, resume_tokens):
 
4219
        """Insert a stream's content into the target repository.
 
4220
 
 
4221
        :param src_format: a bzr repository format.
 
4222
 
 
4223
        :return: a list of resume tokens and an  iterable of keys additional
 
4224
            items required before the insertion can be completed.
 
4225
        """
 
4226
        self.target_repo.lock_write()
 
4227
        try:
 
4228
            if resume_tokens:
 
4229
                self.target_repo.resume_write_group(resume_tokens)
 
4230
                is_resume = True
 
4231
            else:
 
4232
                self.target_repo.start_write_group()
 
4233
                is_resume = False
 
4234
            try:
 
4235
                # locked_insert_stream performs a commit|suspend.
 
4236
                return self._locked_insert_stream(stream, src_format, is_resume)
 
4237
            except:
 
4238
                self.target_repo.abort_write_group(suppress_errors=True)
 
4239
                raise
 
4240
        finally:
 
4241
            self.target_repo.unlock()
 
4242
 
 
4243
    def _locked_insert_stream(self, stream, src_format, is_resume):
 
4244
        to_serializer = self.target_repo._format._serializer
 
4245
        src_serializer = src_format._serializer
 
4246
        new_pack = None
 
4247
        if to_serializer == src_serializer:
 
4248
            # If serializers match and the target is a pack repository, set the
 
4249
            # write cache size on the new pack.  This avoids poor performance
 
4250
            # on transports where append is unbuffered (such as
 
4251
            # RemoteTransport).  This is safe to do because nothing should read
 
4252
            # back from the target repository while a stream with matching
 
4253
            # serialization is being inserted.
 
4254
            # The exception is that a delta record from the source that should
 
4255
            # be a fulltext may need to be expanded by the target (see
 
4256
            # test_fetch_revisions_with_deltas_into_pack); but we take care to
 
4257
            # explicitly flush any buffered writes first in that rare case.
 
4258
            try:
 
4259
                new_pack = self.target_repo._pack_collection._new_pack
 
4260
            except AttributeError:
 
4261
                # Not a pack repository
 
4262
                pass
 
4263
            else:
 
4264
                new_pack.set_write_cache_size(1024*1024)
 
4265
        for substream_type, substream in stream:
 
4266
            if 'stream' in debug.debug_flags:
 
4267
                mutter('inserting substream: %s', substream_type)
 
4268
            if substream_type == 'texts':
 
4269
                self.target_repo.texts.insert_record_stream(substream)
 
4270
            elif substream_type == 'inventories':
 
4271
                if src_serializer == to_serializer:
 
4272
                    self.target_repo.inventories.insert_record_stream(
 
4273
                        substream)
 
4274
                else:
 
4275
                    self._extract_and_insert_inventories(
 
4276
                        substream, src_serializer)
 
4277
            elif substream_type == 'inventory-deltas':
 
4278
                self._extract_and_insert_inventory_deltas(
 
4279
                    substream, src_serializer)
 
4280
            elif substream_type == 'chk_bytes':
 
4281
                # XXX: This doesn't support conversions, as it assumes the
 
4282
                #      conversion was done in the fetch code.
 
4283
                self.target_repo.chk_bytes.insert_record_stream(substream)
 
4284
            elif substream_type == 'revisions':
 
4285
                # This may fallback to extract-and-insert more often than
 
4286
                # required if the serializers are different only in terms of
 
4287
                # the inventory.
 
4288
                if src_serializer == to_serializer:
 
4289
                    self.target_repo.revisions.insert_record_stream(
 
4290
                        substream)
 
4291
                else:
 
4292
                    self._extract_and_insert_revisions(substream,
 
4293
                        src_serializer)
 
4294
            elif substream_type == 'signatures':
 
4295
                self.target_repo.signatures.insert_record_stream(substream)
 
4296
            else:
 
4297
                raise AssertionError('kaboom! %s' % (substream_type,))
 
4298
        # Done inserting data, and the missing_keys calculations will try to
 
4299
        # read back from the inserted data, so flush the writes to the new pack
 
4300
        # (if this is pack format).
 
4301
        if new_pack is not None:
 
4302
            new_pack._write_data('', flush=True)
 
4303
        # Find all the new revisions (including ones from resume_tokens)
 
4304
        missing_keys = self.target_repo.get_missing_parent_inventories(
 
4305
            check_for_missing_texts=is_resume)
 
4306
        try:
 
4307
            for prefix, versioned_file in (
 
4308
                ('texts', self.target_repo.texts),
 
4309
                ('inventories', self.target_repo.inventories),
 
4310
                ('revisions', self.target_repo.revisions),
 
4311
                ('signatures', self.target_repo.signatures),
 
4312
                ('chk_bytes', self.target_repo.chk_bytes),
 
4313
                ):
 
4314
                if versioned_file is None:
 
4315
                    continue
 
4316
                # TODO: key is often going to be a StaticTuple object
 
4317
                #       I don't believe we can define a method by which
 
4318
                #       (prefix,) + StaticTuple will work, though we could
 
4319
                #       define a StaticTuple.sq_concat that would allow you to
 
4320
                #       pass in either a tuple or a StaticTuple as the second
 
4321
                #       object, so instead we could have:
 
4322
                #       StaticTuple(prefix) + key here...
 
4323
                missing_keys.update((prefix,) + key for key in
 
4324
                    versioned_file.get_missing_compression_parent_keys())
 
4325
        except NotImplementedError:
 
4326
            # cannot even attempt suspending, and missing would have failed
 
4327
            # during stream insertion.
 
4328
            missing_keys = set()
 
4329
        else:
 
4330
            if missing_keys:
 
4331
                # suspend the write group and tell the caller what we is
 
4332
                # missing. We know we can suspend or else we would not have
 
4333
                # entered this code path. (All repositories that can handle
 
4334
                # missing keys can handle suspending a write group).
 
4335
                write_group_tokens = self.target_repo.suspend_write_group()
 
4336
                return write_group_tokens, missing_keys
 
4337
        hint = self.target_repo.commit_write_group()
 
4338
        if (to_serializer != src_serializer and
 
4339
            self.target_repo._format.pack_compresses):
 
4340
            self.target_repo.pack(hint=hint)
 
4341
        return [], set()
 
4342
 
 
4343
    def _extract_and_insert_inventory_deltas(self, substream, serializer):
 
4344
        target_rich_root = self.target_repo._format.rich_root_data
 
4345
        target_tree_refs = self.target_repo._format.supports_tree_reference
 
4346
        for record in substream:
 
4347
            # Insert the delta directly
 
4348
            inventory_delta_bytes = record.get_bytes_as('fulltext')
 
4349
            deserialiser = inventory_delta.InventoryDeltaDeserializer()
 
4350
            try:
 
4351
                parse_result = deserialiser.parse_text_bytes(
 
4352
                    inventory_delta_bytes)
 
4353
            except inventory_delta.IncompatibleInventoryDelta, err:
 
4354
                trace.mutter("Incompatible delta: %s", err.msg)
 
4355
                raise errors.IncompatibleRevision(self.target_repo._format)
 
4356
            basis_id, new_id, rich_root, tree_refs, inv_delta = parse_result
 
4357
            revision_id = new_id
 
4358
            parents = [key[0] for key in record.parents]
 
4359
            self.target_repo.add_inventory_by_delta(
 
4360
                basis_id, inv_delta, revision_id, parents)
 
4361
 
 
4362
    def _extract_and_insert_inventories(self, substream, serializer,
 
4363
            parse_delta=None):
 
4364
        """Generate a new inventory versionedfile in target, converting data.
 
4365
 
 
4366
        The inventory is retrieved from the source, (deserializing it), and
 
4367
        stored in the target (reserializing it in a different format).
 
4368
        """
 
4369
        target_rich_root = self.target_repo._format.rich_root_data
 
4370
        target_tree_refs = self.target_repo._format.supports_tree_reference
 
4371
        for record in substream:
 
4372
            # It's not a delta, so it must be a fulltext in the source
 
4373
            # serializer's format.
 
4374
            bytes = record.get_bytes_as('fulltext')
 
4375
            revision_id = record.key[0]
 
4376
            inv = serializer.read_inventory_from_string(bytes, revision_id)
 
4377
            parents = [key[0] for key in record.parents]
 
4378
            self.target_repo.add_inventory(revision_id, inv, parents)
 
4379
            # No need to keep holding this full inv in memory when the rest of
 
4380
            # the substream is likely to be all deltas.
 
4381
            del inv
 
4382
 
 
4383
    def _extract_and_insert_revisions(self, substream, serializer):
 
4384
        for record in substream:
 
4385
            bytes = record.get_bytes_as('fulltext')
 
4386
            revision_id = record.key[0]
 
4387
            rev = serializer.read_revision_from_string(bytes)
 
4388
            if rev.revision_id != revision_id:
 
4389
                raise AssertionError('wtf: %s != %s' % (rev, revision_id))
 
4390
            self.target_repo.add_revision(revision_id, rev)
 
4391
 
 
4392
    def finished(self):
 
4393
        if self.target_repo._format._fetch_reconcile:
 
4394
            self.target_repo.reconcile()
 
4395
 
 
4396
 
 
4397
class StreamSource(object):
 
4398
    """A source of a stream for fetching between repositories."""
 
4399
 
 
4400
    def __init__(self, from_repository, to_format):
 
4401
        """Create a StreamSource streaming from from_repository."""
 
4402
        self.from_repository = from_repository
 
4403
        self.to_format = to_format
 
4404
 
 
4405
    def delta_on_metadata(self):
 
4406
        """Return True if delta's are permitted on metadata streams.
 
4407
 
 
4408
        That is on revisions and signatures.
 
4409
        """
 
4410
        src_serializer = self.from_repository._format._serializer
 
4411
        target_serializer = self.to_format._serializer
 
4412
        return (self.to_format._fetch_uses_deltas and
 
4413
            src_serializer == target_serializer)
 
4414
 
 
4415
    def _fetch_revision_texts(self, revs):
 
4416
        # fetch signatures first and then the revision texts
 
4417
        # may need to be a InterRevisionStore call here.
 
4418
        from_sf = self.from_repository.signatures
 
4419
        # A missing signature is just skipped.
 
4420
        keys = [(rev_id,) for rev_id in revs]
 
4421
        signatures = versionedfile.filter_absent(from_sf.get_record_stream(
 
4422
            keys,
 
4423
            self.to_format._fetch_order,
 
4424
            not self.to_format._fetch_uses_deltas))
 
4425
        # If a revision has a delta, this is actually expanded inside the
 
4426
        # insert_record_stream code now, which is an alternate fix for
 
4427
        # bug #261339
 
4428
        from_rf = self.from_repository.revisions
 
4429
        revisions = from_rf.get_record_stream(
 
4430
            keys,
 
4431
            self.to_format._fetch_order,
 
4432
            not self.delta_on_metadata())
 
4433
        return [('signatures', signatures), ('revisions', revisions)]
 
4434
 
 
4435
    def _generate_root_texts(self, revs):
 
4436
        """This will be called by get_stream between fetching weave texts and
 
4437
        fetching the inventory weave.
 
4438
        """
 
4439
        if self._rich_root_upgrade():
 
4440
            return _mod_fetch.Inter1and2Helper(
 
4441
                self.from_repository).generate_root_texts(revs)
 
4442
        else:
 
4443
            return []
 
4444
 
 
4445
    def get_stream(self, search):
 
4446
        phase = 'file'
 
4447
        revs = search.get_keys()
 
4448
        graph = self.from_repository.get_graph()
 
4449
        revs = tsort.topo_sort(graph.get_parent_map(revs))
 
4450
        data_to_fetch = self.from_repository.item_keys_introduced_by(revs)
 
4451
        text_keys = []
 
4452
        for knit_kind, file_id, revisions in data_to_fetch:
 
4453
            if knit_kind != phase:
 
4454
                phase = knit_kind
 
4455
                # Make a new progress bar for this phase
 
4456
            if knit_kind == "file":
 
4457
                # Accumulate file texts
 
4458
                text_keys.extend([(file_id, revision) for revision in
 
4459
                    revisions])
 
4460
            elif knit_kind == "inventory":
 
4461
                # Now copy the file texts.
 
4462
                from_texts = self.from_repository.texts
 
4463
                yield ('texts', from_texts.get_record_stream(
 
4464
                    text_keys, self.to_format._fetch_order,
 
4465
                    not self.to_format._fetch_uses_deltas))
 
4466
                # Cause an error if a text occurs after we have done the
 
4467
                # copy.
 
4468
                text_keys = None
 
4469
                # Before we process the inventory we generate the root
 
4470
                # texts (if necessary) so that the inventories references
 
4471
                # will be valid.
 
4472
                for _ in self._generate_root_texts(revs):
 
4473
                    yield _
 
4474
                # we fetch only the referenced inventories because we do not
 
4475
                # know for unselected inventories whether all their required
 
4476
                # texts are present in the other repository - it could be
 
4477
                # corrupt.
 
4478
                for info in self._get_inventory_stream(revs):
 
4479
                    yield info
 
4480
            elif knit_kind == "signatures":
 
4481
                # Nothing to do here; this will be taken care of when
 
4482
                # _fetch_revision_texts happens.
 
4483
                pass
 
4484
            elif knit_kind == "revisions":
 
4485
                for record in self._fetch_revision_texts(revs):
 
4486
                    yield record
 
4487
            else:
 
4488
                raise AssertionError("Unknown knit kind %r" % knit_kind)
 
4489
 
 
4490
    def get_stream_for_missing_keys(self, missing_keys):
 
4491
        # missing keys can only occur when we are byte copying and not
 
4492
        # translating (because translation means we don't send
 
4493
        # unreconstructable deltas ever).
 
4494
        keys = {}
 
4495
        keys['texts'] = set()
 
4496
        keys['revisions'] = set()
 
4497
        keys['inventories'] = set()
 
4498
        keys['chk_bytes'] = set()
 
4499
        keys['signatures'] = set()
 
4500
        for key in missing_keys:
 
4501
            keys[key[0]].add(key[1:])
 
4502
        if len(keys['revisions']):
 
4503
            # If we allowed copying revisions at this point, we could end up
 
4504
            # copying a revision without copying its required texts: a
 
4505
            # violation of the requirements for repository integrity.
 
4506
            raise AssertionError(
 
4507
                'cannot copy revisions to fill in missing deltas %s' % (
 
4508
                    keys['revisions'],))
 
4509
        for substream_kind, keys in keys.iteritems():
 
4510
            vf = getattr(self.from_repository, substream_kind)
 
4511
            if vf is None and keys:
 
4512
                    raise AssertionError(
 
4513
                        "cannot fill in keys for a versioned file we don't"
 
4514
                        " have: %s needs %s" % (substream_kind, keys))
 
4515
            if not keys:
 
4516
                # No need to stream something we don't have
 
4517
                continue
 
4518
            if substream_kind == 'inventories':
 
4519
                # Some missing keys are genuinely ghosts, filter those out.
 
4520
                present = self.from_repository.inventories.get_parent_map(keys)
 
4521
                revs = [key[0] for key in present]
 
4522
                # Get the inventory stream more-or-less as we do for the
 
4523
                # original stream; there's no reason to assume that records
 
4524
                # direct from the source will be suitable for the sink.  (Think
 
4525
                # e.g. 2a -> 1.9-rich-root).
 
4526
                for info in self._get_inventory_stream(revs, missing=True):
 
4527
                    yield info
 
4528
                continue
 
4529
 
 
4530
            # Ask for full texts always so that we don't need more round trips
 
4531
            # after this stream.
 
4532
            # Some of the missing keys are genuinely ghosts, so filter absent
 
4533
            # records. The Sink is responsible for doing another check to
 
4534
            # ensure that ghosts don't introduce missing data for future
 
4535
            # fetches.
 
4536
            stream = versionedfile.filter_absent(vf.get_record_stream(keys,
 
4537
                self.to_format._fetch_order, True))
 
4538
            yield substream_kind, stream
 
4539
 
 
4540
    def inventory_fetch_order(self):
 
4541
        if self._rich_root_upgrade():
 
4542
            return 'topological'
 
4543
        else:
 
4544
            return self.to_format._fetch_order
 
4545
 
 
4546
    def _rich_root_upgrade(self):
 
4547
        return (not self.from_repository._format.rich_root_data and
 
4548
            self.to_format.rich_root_data)
 
4549
 
 
4550
    def _get_inventory_stream(self, revision_ids, missing=False):
 
4551
        from_format = self.from_repository._format
 
4552
        if (from_format.supports_chks and self.to_format.supports_chks and
 
4553
            from_format.network_name() == self.to_format.network_name()):
 
4554
            raise AssertionError(
 
4555
                "this case should be handled by GroupCHKStreamSource")
 
4556
        elif 'forceinvdeltas' in debug.debug_flags:
 
4557
            return self._get_convertable_inventory_stream(revision_ids,
 
4558
                    delta_versus_null=missing)
 
4559
        elif from_format.network_name() == self.to_format.network_name():
 
4560
            # Same format.
 
4561
            return self._get_simple_inventory_stream(revision_ids,
 
4562
                    missing=missing)
 
4563
        elif (not from_format.supports_chks and not self.to_format.supports_chks
 
4564
                and from_format._serializer == self.to_format._serializer):
 
4565
            # Essentially the same format.
 
4566
            return self._get_simple_inventory_stream(revision_ids,
 
4567
                    missing=missing)
 
4568
        else:
 
4569
            # Any time we switch serializations, we want to use an
 
4570
            # inventory-delta based approach.
 
4571
            return self._get_convertable_inventory_stream(revision_ids,
 
4572
                    delta_versus_null=missing)
 
4573
 
 
4574
    def _get_simple_inventory_stream(self, revision_ids, missing=False):
 
4575
        # NB: This currently reopens the inventory weave in source;
 
4576
        # using a single stream interface instead would avoid this.
 
4577
        from_weave = self.from_repository.inventories
 
4578
        if missing:
 
4579
            delta_closure = True
 
4580
        else:
 
4581
            delta_closure = not self.delta_on_metadata()
 
4582
        yield ('inventories', from_weave.get_record_stream(
 
4583
            [(rev_id,) for rev_id in revision_ids],
 
4584
            self.inventory_fetch_order(), delta_closure))
 
4585
 
 
4586
    def _get_convertable_inventory_stream(self, revision_ids,
 
4587
                                          delta_versus_null=False):
 
4588
        # The two formats are sufficiently different that there is no fast
 
4589
        # path, so we need to send just inventorydeltas, which any
 
4590
        # sufficiently modern client can insert into any repository.
 
4591
        # The StreamSink code expects to be able to
 
4592
        # convert on the target, so we need to put bytes-on-the-wire that can
 
4593
        # be converted.  That means inventory deltas (if the remote is <1.19,
 
4594
        # RemoteStreamSink will fallback to VFS to insert the deltas).
 
4595
        yield ('inventory-deltas',
 
4596
           self._stream_invs_as_deltas(revision_ids,
 
4597
                                       delta_versus_null=delta_versus_null))
 
4598
 
 
4599
    def _stream_invs_as_deltas(self, revision_ids, delta_versus_null=False):
 
4600
        """Return a stream of inventory-deltas for the given rev ids.
 
4601
 
 
4602
        :param revision_ids: The list of inventories to transmit
 
4603
        :param delta_versus_null: Don't try to find a minimal delta for this
 
4604
            entry, instead compute the delta versus the NULL_REVISION. This
 
4605
            effectively streams a complete inventory. Used for stuff like
 
4606
            filling in missing parents, etc.
 
4607
        """
 
4608
        from_repo = self.from_repository
 
4609
        revision_keys = [(rev_id,) for rev_id in revision_ids]
 
4610
        parent_map = from_repo.inventories.get_parent_map(revision_keys)
 
4611
        # XXX: possibly repos could implement a more efficient iter_inv_deltas
 
4612
        # method...
 
4613
        inventories = self.from_repository.iter_inventories(
 
4614
            revision_ids, 'topological')
 
4615
        format = from_repo._format
 
4616
        invs_sent_so_far = set([_mod_revision.NULL_REVISION])
 
4617
        inventory_cache = lru_cache.LRUCache(50)
 
4618
        null_inventory = from_repo.revision_tree(
 
4619
            _mod_revision.NULL_REVISION).inventory
 
4620
        # XXX: ideally the rich-root/tree-refs flags would be per-revision, not
 
4621
        # per-repo (e.g.  streaming a non-rich-root revision out of a rich-root
 
4622
        # repo back into a non-rich-root repo ought to be allowed)
 
4623
        serializer = inventory_delta.InventoryDeltaSerializer(
 
4624
            versioned_root=format.rich_root_data,
 
4625
            tree_references=format.supports_tree_reference)
 
4626
        for inv in inventories:
 
4627
            key = (inv.revision_id,)
 
4628
            parent_keys = parent_map.get(key, ())
 
4629
            delta = None
 
4630
            if not delta_versus_null and parent_keys:
 
4631
                # The caller did not ask for complete inventories and we have
 
4632
                # some parents that we can delta against.  Make a delta against
 
4633
                # each parent so that we can find the smallest.
 
4634
                parent_ids = [parent_key[0] for parent_key in parent_keys]
 
4635
                for parent_id in parent_ids:
 
4636
                    if parent_id not in invs_sent_so_far:
 
4637
                        # We don't know that the remote side has this basis, so
 
4638
                        # we can't use it.
 
4639
                        continue
 
4640
                    if parent_id == _mod_revision.NULL_REVISION:
 
4641
                        parent_inv = null_inventory
 
4642
                    else:
 
4643
                        parent_inv = inventory_cache.get(parent_id, None)
 
4644
                        if parent_inv is None:
 
4645
                            parent_inv = from_repo.get_inventory(parent_id)
 
4646
                    candidate_delta = inv._make_delta(parent_inv)
 
4647
                    if (delta is None or
 
4648
                        len(delta) > len(candidate_delta)):
 
4649
                        delta = candidate_delta
 
4650
                        basis_id = parent_id
 
4651
            if delta is None:
 
4652
                # Either none of the parents ended up being suitable, or we
 
4653
                # were asked to delta against NULL
 
4654
                basis_id = _mod_revision.NULL_REVISION
 
4655
                delta = inv._make_delta(null_inventory)
 
4656
            invs_sent_so_far.add(inv.revision_id)
 
4657
            inventory_cache[inv.revision_id] = inv
 
4658
            delta_serialized = ''.join(
 
4659
                serializer.delta_to_lines(basis_id, key[-1], delta))
 
4660
            yield versionedfile.FulltextContentFactory(
 
4661
                key, parent_keys, None, delta_serialized)
 
4662
 
 
4663
 
 
4664
def _iter_for_revno(repo, partial_history_cache, stop_index=None,
 
4665
                    stop_revision=None):
 
4666
    """Extend the partial history to include a given index
 
4667
 
 
4668
    If a stop_index is supplied, stop when that index has been reached.
 
4669
    If a stop_revision is supplied, stop when that revision is
 
4670
    encountered.  Otherwise, stop when the beginning of history is
 
4671
    reached.
 
4672
 
 
4673
    :param stop_index: The index which should be present.  When it is
 
4674
        present, history extension will stop.
 
4675
    :param stop_revision: The revision id which should be present.  When
 
4676
        it is encountered, history extension will stop.
 
4677
    """
 
4678
    start_revision = partial_history_cache[-1]
 
4679
    iterator = repo.iter_reverse_revision_history(start_revision)
 
4680
    try:
 
4681
        #skip the last revision in the list
 
4682
        iterator.next()
 
4683
        while True:
 
4684
            if (stop_index is not None and
 
4685
                len(partial_history_cache) > stop_index):
 
4686
                break
 
4687
            if partial_history_cache[-1] == stop_revision:
 
4688
                break
 
4689
            revision_id = iterator.next()
 
4690
            partial_history_cache.append(revision_id)
 
4691
    except StopIteration:
 
4692
        # No more history
 
4693
        return
 
4694