~bzr-pqm/bzr/bzr.dev

« back to all changes in this revision

Viewing changes to bzrlib/versionedfile.py

  • Committer: Alexander Belchenko
  • Date: 2006-07-30 18:47:00 UTC
  • mto: (1711.2.111 jam-integration)
  • mto: This revision was merged to the branch mainline in revision 1906.
  • Revision ID: bialix@ukr.net-20060730184700-cfc979f8f530908d
setup.py: get version info from bzrlib

Show diffs side-by-side

added added

removed removed

Lines of Context:
1
 
# Copyright (C) 2005, 2006 Canonical Ltd
 
1
# Copyright (C) 2005, 2006 by Canonical Ltd
2
2
#
3
3
# Authors:
4
4
#   Johan Rydberg <jrydberg@gnu.org>
19
19
 
20
20
"""Versioned text file storage api."""
21
21
 
22
 
from copy import copy
23
 
from cStringIO import StringIO
24
 
import os
25
 
import urllib
26
 
from zlib import adler32
27
 
 
28
 
from bzrlib.lazy_import import lazy_import
29
 
lazy_import(globals(), """
30
 
 
31
 
from bzrlib import (
32
 
    errors,
33
 
    osutils,
34
 
    multiparent,
35
 
    tsort,
36
 
    revision,
37
 
    ui,
38
 
    )
39
 
from bzrlib.graph import DictParentsProvider, Graph, _StackedParentsProvider
40
 
from bzrlib.transport.memory import MemoryTransport
41
 
""")
 
22
 
 
23
from copy import deepcopy
 
24
from unittest import TestSuite
 
25
 
 
26
 
 
27
import bzrlib.errors as errors
42
28
from bzrlib.inter import InterObject
43
 
from bzrlib.registry import Registry
44
 
from bzrlib.symbol_versioning import *
45
29
from bzrlib.textmerge import TextMerge
46
 
 
47
 
 
48
 
adapter_registry = Registry()
49
 
adapter_registry.register_lazy(('knit-delta-gz', 'fulltext'), 'bzrlib.knit',
50
 
    'DeltaPlainToFullText')
51
 
adapter_registry.register_lazy(('knit-ft-gz', 'fulltext'), 'bzrlib.knit',
52
 
    'FTPlainToFullText')
53
 
adapter_registry.register_lazy(('knit-annotated-delta-gz', 'knit-delta-gz'),
54
 
    'bzrlib.knit', 'DeltaAnnotatedToUnannotated')
55
 
adapter_registry.register_lazy(('knit-annotated-delta-gz', 'fulltext'),
56
 
    'bzrlib.knit', 'DeltaAnnotatedToFullText')
57
 
adapter_registry.register_lazy(('knit-annotated-ft-gz', 'knit-ft-gz'),
58
 
    'bzrlib.knit', 'FTAnnotatedToUnannotated')
59
 
adapter_registry.register_lazy(('knit-annotated-ft-gz', 'fulltext'),
60
 
    'bzrlib.knit', 'FTAnnotatedToFullText')
61
 
 
62
 
 
63
 
class ContentFactory(object):
64
 
    """Abstract interface for insertion and retrieval from a VersionedFile.
65
 
    
66
 
    :ivar sha1: None, or the sha1 of the content fulltext.
67
 
    :ivar storage_kind: The native storage kind of this factory. One of
68
 
        'mpdiff', 'knit-annotated-ft', 'knit-annotated-delta', 'knit-ft',
69
 
        'knit-delta', 'fulltext', 'knit-annotated-ft-gz',
70
 
        'knit-annotated-delta-gz', 'knit-ft-gz', 'knit-delta-gz'.
71
 
    :ivar key: The key of this content. Each key is a tuple with a single
72
 
        string in it.
73
 
    :ivar parents: A tuple of parent keys for self.key. If the object has
74
 
        no parent information, None (as opposed to () for an empty list of
75
 
        parents).
76
 
    """
77
 
 
78
 
    def __init__(self):
79
 
        """Create a ContentFactory."""
80
 
        self.sha1 = None
81
 
        self.storage_kind = None
82
 
        self.key = None
83
 
        self.parents = None
84
 
 
85
 
 
86
 
class FulltextContentFactory(ContentFactory):
87
 
    """Static data content factory.
88
 
 
89
 
    This takes a fulltext when created and just returns that during
90
 
    get_bytes_as('fulltext').
91
 
    
92
 
    :ivar sha1: None, or the sha1 of the content fulltext.
93
 
    :ivar storage_kind: The native storage kind of this factory. Always
94
 
        'fulltext'.
95
 
    :ivar key: The key of this content. Each key is a tuple with a single
96
 
        string in it.
97
 
    :ivar parents: A tuple of parent keys for self.key. If the object has
98
 
        no parent information, None (as opposed to () for an empty list of
99
 
        parents).
100
 
     """
101
 
 
102
 
    def __init__(self, key, parents, sha1, text):
103
 
        """Create a ContentFactory."""
104
 
        self.sha1 = sha1
105
 
        self.storage_kind = 'fulltext'
106
 
        self.key = key
107
 
        self.parents = parents
108
 
        self._text = text
109
 
 
110
 
    def get_bytes_as(self, storage_kind):
111
 
        if storage_kind == self.storage_kind:
112
 
            return self._text
113
 
        raise errors.UnavailableRepresentation(self.key, storage_kind,
114
 
            self.storage_kind)
115
 
 
116
 
 
117
 
class AbsentContentFactory(ContentFactory):
118
 
    """A placeholder content factory for unavailable texts.
119
 
    
120
 
    :ivar sha1: None.
121
 
    :ivar storage_kind: 'absent'.
122
 
    :ivar key: The key of this content. Each key is a tuple with a single
123
 
        string in it.
124
 
    :ivar parents: None.
125
 
    """
126
 
 
127
 
    def __init__(self, key):
128
 
        """Create a ContentFactory."""
129
 
        self.sha1 = None
130
 
        self.storage_kind = 'absent'
131
 
        self.key = key
132
 
        self.parents = None
133
 
 
134
 
 
135
 
class AdapterFactory(ContentFactory):
136
 
    """A content factory to adapt between key prefix's."""
137
 
 
138
 
    def __init__(self, key, parents, adapted):
139
 
        """Create an adapter factory instance."""
140
 
        self.key = key
141
 
        self.parents = parents
142
 
        self._adapted = adapted
143
 
 
144
 
    def __getattr__(self, attr):
145
 
        """Return a member from the adapted object."""
146
 
        if attr in ('key', 'parents'):
147
 
            return self.__dict__[attr]
148
 
        else:
149
 
            return getattr(self._adapted, attr)
150
 
 
151
 
 
152
 
def filter_absent(record_stream):
153
 
    """Adapt a record stream to remove absent records."""
154
 
    for record in record_stream:
155
 
        if record.storage_kind != 'absent':
156
 
            yield record
 
30
from bzrlib.transport.memory import MemoryTransport
 
31
from bzrlib.tsort import topo_sort
 
32
from bzrlib import ui
 
33
from bzrlib.symbol_versioning import (deprecated_function,
 
34
        deprecated_method,
 
35
        zero_eight,
 
36
        )
157
37
 
158
38
 
159
39
class VersionedFile(object):
170
50
    Texts are identified by a version-id string.
171
51
    """
172
52
 
173
 
    @staticmethod
174
 
    def check_not_reserved_id(version_id):
175
 
        revision.check_not_reserved_id(version_id)
 
53
    def __init__(self, access_mode):
 
54
        self.finished = False
 
55
        self._access_mode = access_mode
176
56
 
177
57
    def copy_to(self, name, transport):
178
58
        """Copy this versioned file to name on transport."""
179
59
        raise NotImplementedError(self.copy_to)
180
60
 
181
 
    def get_record_stream(self, versions, ordering, include_delta_closure):
182
 
        """Get a stream of records for versions.
 
61
    @deprecated_method(zero_eight)
 
62
    def names(self):
 
63
        """Return a list of all the versions in this versioned file.
183
64
 
184
 
        :param versions: The versions to include. Each version is a tuple
185
 
            (version,).
186
 
        :param ordering: Either 'unordered' or 'topological'. A topologically
187
 
            sorted stream has compression parents strictly before their
188
 
            children.
189
 
        :param include_delta_closure: If True then the closure across any
190
 
            compression parents will be included (in the data content of the
191
 
            stream, not in the emitted records). This guarantees that
192
 
            'fulltext' can be used successfully on every record.
193
 
        :return: An iterator of ContentFactory objects, each of which is only
194
 
            valid until the iterator is advanced.
 
65
        Please use versionedfile.versions() now.
195
66
        """
196
 
        raise NotImplementedError(self.get_record_stream)
 
67
        return self.versions()
 
68
 
 
69
    def versions(self):
 
70
        """Return a unsorted list of versions."""
 
71
        raise NotImplementedError(self.versions)
 
72
 
 
73
    def has_ghost(self, version_id):
 
74
        """Returns whether version is present as a ghost."""
 
75
        raise NotImplementedError(self.has_ghost)
197
76
 
198
77
    def has_version(self, version_id):
199
78
        """Returns whether version is present."""
200
79
        raise NotImplementedError(self.has_version)
201
80
 
202
 
    def insert_record_stream(self, stream):
203
 
        """Insert a record stream into this versioned file.
204
 
 
205
 
        :param stream: A stream of records to insert. 
206
 
        :return: None
207
 
        :seealso VersionedFile.get_record_stream:
208
 
        """
209
 
        raise NotImplementedError
210
 
 
211
 
    def add_lines(self, version_id, parents, lines, parent_texts=None,
212
 
        left_matching_blocks=None, nostore_sha=None, random_id=False,
213
 
        check_content=True):
 
81
    def add_delta(self, version_id, parents, delta_parent, sha1, noeol, delta):
 
82
        """Add a text to the versioned file via a pregenerated delta.
 
83
 
 
84
        :param version_id: The version id being added.
 
85
        :param parents: The parents of the version_id.
 
86
        :param delta_parent: The parent this delta was created against.
 
87
        :param sha1: The sha1 of the full text.
 
88
        :param delta: The delta instructions. See get_delta for details.
 
89
        """
 
90
        self._check_write_ok()
 
91
        if self.has_version(version_id):
 
92
            raise errors.RevisionAlreadyPresent(version_id, self)
 
93
        return self._add_delta(version_id, parents, delta_parent, sha1, noeol, delta)
 
94
 
 
95
    def _add_delta(self, version_id, parents, delta_parent, sha1, noeol, delta):
 
96
        """Class specific routine to add a delta.
 
97
 
 
98
        This generic version simply applies the delta to the delta_parent and
 
99
        then inserts it.
 
100
        """
 
101
        # strip annotation from delta
 
102
        new_delta = []
 
103
        for start, stop, delta_len, delta_lines in delta:
 
104
            new_delta.append((start, stop, delta_len, [text for origin, text in delta_lines]))
 
105
        if delta_parent is not None:
 
106
            parent_full = self.get_lines(delta_parent)
 
107
        else:
 
108
            parent_full = []
 
109
        new_full = self._apply_delta(parent_full, new_delta)
 
110
        # its impossible to have noeol on an empty file
 
111
        if noeol and new_full[-1][-1] == '\n':
 
112
            new_full[-1] = new_full[-1][:-1]
 
113
        self.add_lines(version_id, parents, new_full)
 
114
 
 
115
    def add_lines(self, version_id, parents, lines, parent_texts=None):
214
116
        """Add a single text on top of the versioned file.
215
117
 
216
118
        Must raise RevisionAlreadyPresent if the new version is
218
120
 
219
121
        Must raise RevisionNotPresent if any of the given parents are
220
122
        not present in file history.
221
 
 
222
 
        :param lines: A list of lines. Each line must be a bytestring. And all
223
 
            of them except the last must be terminated with \n and contain no
224
 
            other \n's. The last line may either contain no \n's or a single
225
 
            terminated \n. If the lines list does meet this constraint the add
226
 
            routine may error or may succeed - but you will be unable to read
227
 
            the data back accurately. (Checking the lines have been split
228
 
            correctly is expensive and extremely unlikely to catch bugs so it
229
 
            is not done at runtime unless check_content is True.)
230
123
        :param parent_texts: An optional dictionary containing the opaque 
231
 
            representations of some or all of the parents of version_id to
232
 
            allow delta optimisations.  VERY IMPORTANT: the texts must be those
233
 
            returned by add_lines or data corruption can be caused.
234
 
        :param left_matching_blocks: a hint about which areas are common
235
 
            between the text and its left-hand-parent.  The format is
236
 
            the SequenceMatcher.get_matching_blocks format.
237
 
        :param nostore_sha: Raise ExistingContent and do not add the lines to
238
 
            the versioned file if the digest of the lines matches this.
239
 
        :param random_id: If True a random id has been selected rather than
240
 
            an id determined by some deterministic process such as a converter
241
 
            from a foreign VCS. When True the backend may choose not to check
242
 
            for uniqueness of the resulting key within the versioned file, so
243
 
            this should only be done when the result is expected to be unique
244
 
            anyway.
245
 
        :param check_content: If True, the lines supplied are verified to be
246
 
            bytestrings that are correctly formed lines.
247
 
        :return: The text sha1, the number of bytes in the text, and an opaque
248
 
                 representation of the inserted version which can be provided
249
 
                 back to future add_lines calls in the parent_texts dictionary.
 
124
             representations of some or all of the parents of 
 
125
             version_id to allow delta optimisations. 
 
126
             VERY IMPORTANT: the texts must be those returned
 
127
             by add_lines or data corruption can be caused.
 
128
        :return: An opaque representation of the inserted version which can be
 
129
                 provided back to future add_lines calls in the parent_texts
 
130
                 dictionary.
250
131
        """
251
132
        self._check_write_ok()
252
 
        return self._add_lines(version_id, parents, lines, parent_texts,
253
 
            left_matching_blocks, nostore_sha, random_id, check_content)
 
133
        return self._add_lines(version_id, parents, lines, parent_texts)
254
134
 
255
 
    def _add_lines(self, version_id, parents, lines, parent_texts,
256
 
        left_matching_blocks, nostore_sha, random_id, check_content):
 
135
    def _add_lines(self, version_id, parents, lines, parent_texts):
257
136
        """Helper to do the class specific add_lines."""
258
137
        raise NotImplementedError(self.add_lines)
259
138
 
260
139
    def add_lines_with_ghosts(self, version_id, parents, lines,
261
 
        parent_texts=None, nostore_sha=None, random_id=False,
262
 
        check_content=True, left_matching_blocks=None):
 
140
                              parent_texts=None):
263
141
        """Add lines to the versioned file, allowing ghosts to be present.
264
142
        
265
 
        This takes the same parameters as add_lines and returns the same.
 
143
        This takes the same parameters as add_lines.
266
144
        """
267
145
        self._check_write_ok()
268
146
        return self._add_lines_with_ghosts(version_id, parents, lines,
269
 
            parent_texts, nostore_sha, random_id, check_content, left_matching_blocks)
 
147
                                           parent_texts)
270
148
 
271
 
    def _add_lines_with_ghosts(self, version_id, parents, lines, parent_texts,
272
 
        nostore_sha, random_id, check_content, left_matching_blocks):
 
149
    def _add_lines_with_ghosts(self, version_id, parents, lines, parent_texts):
273
150
        """Helper to do class specific add_lines_with_ghosts."""
274
151
        raise NotImplementedError(self.add_lines_with_ghosts)
275
152
 
289
166
            if '\n' in line[:-1]:
290
167
                raise errors.BzrBadParameterContainsNewline("lines")
291
168
 
292
 
    def get_format_signature(self):
293
 
        """Get a text description of the data encoding in this file.
294
 
        
295
 
        :since: 0.90
296
 
        """
297
 
        raise NotImplementedError(self.get_format_signature)
298
 
 
299
 
    def make_mpdiffs(self, version_ids):
300
 
        """Create multiparent diffs for specified versions."""
301
 
        knit_versions = set()
302
 
        knit_versions.update(version_ids)
303
 
        parent_map = self.get_parent_map(version_ids)
304
 
        for version_id in version_ids:
305
 
            try:
306
 
                knit_versions.update(parent_map[version_id])
307
 
            except KeyError:
308
 
                raise errors.RevisionNotPresent(version_id, self)
309
 
        # We need to filter out ghosts, because we can't diff against them.
310
 
        knit_versions = set(self.get_parent_map(knit_versions).keys())
311
 
        lines = dict(zip(knit_versions,
312
 
            self._get_lf_split_line_list(knit_versions)))
313
 
        diffs = []
314
 
        for version_id in version_ids:
315
 
            target = lines[version_id]
316
 
            try:
317
 
                parents = [lines[p] for p in parent_map[version_id] if p in
318
 
                    knit_versions]
319
 
            except KeyError:
320
 
                # I don't know how this could ever trigger.
321
 
                # parent_map[version_id] was already triggered in the previous
322
 
                # for loop, and lines[p] has the 'if p in knit_versions' check,
323
 
                # so we again won't have a KeyError.
324
 
                raise errors.RevisionNotPresent(version_id, self)
325
 
            if len(parents) > 0:
326
 
                left_parent_blocks = self._extract_blocks(version_id,
327
 
                                                          parents[0], target)
328
 
            else:
329
 
                left_parent_blocks = None
330
 
            diffs.append(multiparent.MultiParent.from_lines(target, parents,
331
 
                         left_parent_blocks))
332
 
        return diffs
333
 
 
334
 
    def _extract_blocks(self, version_id, source, target):
335
 
        return None
336
 
 
337
 
    def add_mpdiffs(self, records):
338
 
        """Add mpdiffs to this VersionedFile.
339
 
 
340
 
        Records should be iterables of version, parents, expected_sha1,
341
 
        mpdiff. mpdiff should be a MultiParent instance.
342
 
        """
343
 
        # Does this need to call self._check_write_ok()? (IanC 20070919)
344
 
        vf_parents = {}
345
 
        mpvf = multiparent.MultiMemoryVersionedFile()
346
 
        versions = []
347
 
        for version, parent_ids, expected_sha1, mpdiff in records:
348
 
            versions.append(version)
349
 
            mpvf.add_diff(mpdiff, version, parent_ids)
350
 
        needed_parents = set()
351
 
        for version, parent_ids, expected_sha1, mpdiff in records:
352
 
            needed_parents.update(p for p in parent_ids
353
 
                                  if not mpvf.has_version(p))
354
 
        present_parents = set(self.get_parent_map(needed_parents).keys())
355
 
        for parent_id, lines in zip(present_parents,
356
 
                                 self._get_lf_split_line_list(present_parents)):
357
 
            mpvf.add_version(lines, parent_id, [])
358
 
        for (version, parent_ids, expected_sha1, mpdiff), lines in\
359
 
            zip(records, mpvf.get_line_list(versions)):
360
 
            if len(parent_ids) == 1:
361
 
                left_matching_blocks = list(mpdiff.get_matching_blocks(0,
362
 
                    mpvf.get_diff(parent_ids[0]).num_lines()))
363
 
            else:
364
 
                left_matching_blocks = None
365
 
            try:
366
 
                _, _, version_text = self.add_lines_with_ghosts(version,
367
 
                    parent_ids, lines, vf_parents,
368
 
                    left_matching_blocks=left_matching_blocks)
369
 
            except NotImplementedError:
370
 
                # The vf can't handle ghosts, so add lines normally, which will
371
 
                # (reasonably) fail if there are ghosts in the data.
372
 
                _, _, version_text = self.add_lines(version,
373
 
                    parent_ids, lines, vf_parents,
374
 
                    left_matching_blocks=left_matching_blocks)
375
 
            vf_parents[version] = version_text
376
 
        sha1s = self.get_sha1s(versions)
377
 
        for version, parent_ids, expected_sha1, mpdiff in records:
378
 
            if expected_sha1 != sha1s[version]:
379
 
                raise errors.VersionedFileInvalidChecksum(version)
380
 
 
 
169
    def _check_write_ok(self):
 
170
        """Is the versioned file marked as 'finished' ? Raise if it is."""
 
171
        if self.finished:
 
172
            raise errors.OutSideTransaction()
 
173
        if self._access_mode != 'w':
 
174
            raise errors.ReadOnlyObjectDirtiedError(self)
 
175
 
 
176
    def enable_cache(self):
 
177
        """Tell this versioned file that it should cache any data it reads.
 
178
        
 
179
        This is advisory, implementations do not have to support caching.
 
180
        """
 
181
        pass
 
182
    
 
183
    def clear_cache(self):
 
184
        """Remove any data cached in the versioned file object.
 
185
 
 
186
        This only needs to be supported if caches are supported
 
187
        """
 
188
        pass
 
189
 
 
190
    def clone_text(self, new_version_id, old_version_id, parents):
 
191
        """Add an identical text to old_version_id as new_version_id.
 
192
 
 
193
        Must raise RevisionNotPresent if the old version or any of the
 
194
        parents are not present in file history.
 
195
 
 
196
        Must raise RevisionAlreadyPresent if the new version is
 
197
        already present in file history."""
 
198
        self._check_write_ok()
 
199
        return self._clone_text(new_version_id, old_version_id, parents)
 
200
 
 
201
    def _clone_text(self, new_version_id, old_version_id, parents):
 
202
        """Helper function to do the _clone_text work."""
 
203
        raise NotImplementedError(self.clone_text)
 
204
 
 
205
    def create_empty(self, name, transport, mode=None):
 
206
        """Create a new versioned file of this exact type.
 
207
 
 
208
        :param name: the file name
 
209
        :param transport: the transport
 
210
        :param mode: optional file mode.
 
211
        """
 
212
        raise NotImplementedError(self.create_empty)
 
213
 
 
214
    def fix_parents(self, version, new_parents):
 
215
        """Fix the parents list for version.
 
216
        
 
217
        This is done by appending a new version to the index
 
218
        with identical data except for the parents list.
 
219
        the parents list must be a superset of the current
 
220
        list.
 
221
        """
 
222
        self._check_write_ok()
 
223
        return self._fix_parents(version, new_parents)
 
224
 
 
225
    def _fix_parents(self, version, new_parents):
 
226
        """Helper for fix_parents."""
 
227
        raise NotImplementedError(self.fix_parents)
 
228
 
 
229
    def get_delta(self, version):
 
230
        """Get a delta for constructing version from some other version.
 
231
        
 
232
        :return: (delta_parent, sha1, noeol, delta)
 
233
        Where delta_parent is a version id or None to indicate no parent.
 
234
        """
 
235
        raise NotImplementedError(self.get_delta)
 
236
 
 
237
    def get_deltas(self, versions):
 
238
        """Get multiple deltas at once for constructing versions.
 
239
        
 
240
        :return: dict(version_id:(delta_parent, sha1, noeol, delta))
 
241
        Where delta_parent is a version id or None to indicate no parent, and
 
242
        version_id is the version_id created by that delta.
 
243
        """
 
244
        result = {}
 
245
        for version in versions:
 
246
            result[version] = self.get_delta(version)
 
247
        return result
 
248
 
 
249
    def get_sha1(self, version_id):
 
250
        """Get the stored sha1 sum for the given revision.
 
251
        
 
252
        :param name: The name of the version to lookup
 
253
        """
 
254
        raise NotImplementedError(self.get_sha1)
 
255
 
 
256
    def get_suffixes(self):
 
257
        """Return the file suffixes associated with this versioned file."""
 
258
        raise NotImplementedError(self.get_suffixes)
 
259
    
381
260
    def get_text(self, version_id):
382
261
        """Return version contents as a text string.
383
262
 
403
282
        """
404
283
        raise NotImplementedError(self.get_lines)
405
284
 
406
 
    def _get_lf_split_line_list(self, version_ids):
407
 
        return [StringIO(t).readlines() for t in self.get_texts(version_ids)]
408
 
 
409
 
    def get_ancestry(self, version_ids, topo_sorted=True):
 
285
    def get_ancestry(self, version_ids):
410
286
        """Return a list of all ancestors of given version(s). This
411
287
        will not include the null revision.
412
288
 
413
 
        This list will not be topologically sorted if topo_sorted=False is
414
 
        passed.
415
 
 
416
289
        Must raise RevisionNotPresent if any of the given versions are
417
290
        not present in file history."""
418
291
        if isinstance(version_ids, basestring):
430
303
        but are not explicitly marked.
431
304
        """
432
305
        raise NotImplementedError(self.get_ancestry_with_ghosts)
433
 
    
434
 
    def get_parent_map(self, version_ids):
435
 
        """Get a map of the parents of version_ids.
436
 
 
437
 
        :param version_ids: The version ids to look up parents for.
438
 
        :return: A mapping from version id to parents.
439
 
        """
440
 
        raise NotImplementedError(self.get_parent_map)
 
306
        
 
307
    def get_graph(self, version_ids=None):
 
308
        """Return a graph from the versioned file. 
 
309
        
 
310
        Ghosts are not listed or referenced in the graph.
 
311
        :param version_ids: Versions to select.
 
312
                            None means retrieve all versions.
 
313
        """
 
314
        result = {}
 
315
        if version_ids is None:
 
316
            for version in self.versions():
 
317
                result[version] = self.get_parents(version)
 
318
        else:
 
319
            pending = set(version_ids)
 
320
            while pending:
 
321
                version = pending.pop()
 
322
                if version in result:
 
323
                    continue
 
324
                parents = self.get_parents(version)
 
325
                for parent in parents:
 
326
                    if parent in result:
 
327
                        continue
 
328
                    pending.add(parent)
 
329
                result[version] = parents
 
330
        return result
 
331
 
 
332
    def get_graph_with_ghosts(self):
 
333
        """Return a graph for the entire versioned file.
 
334
        
 
335
        Ghosts are referenced in parents list but are not
 
336
        explicitly listed.
 
337
        """
 
338
        raise NotImplementedError(self.get_graph_with_ghosts)
 
339
 
 
340
    @deprecated_method(zero_eight)
 
341
    def parent_names(self, version):
 
342
        """Return version names for parents of a version.
 
343
        
 
344
        See get_parents for the current api.
 
345
        """
 
346
        return self.get_parents(version)
 
347
 
 
348
    def get_parents(self, version_id):
 
349
        """Return version names for parents of a version.
 
350
 
 
351
        Must raise RevisionNotPresent if version is not present in
 
352
        file history.
 
353
        """
 
354
        raise NotImplementedError(self.get_parents)
441
355
 
442
356
    def get_parents_with_ghosts(self, version_id):
443
357
        """Return version names for parents of version_id.
448
362
        Ghosts that are known about will be included in the parent list,
449
363
        but are not explicitly marked.
450
364
        """
451
 
        try:
452
 
            return list(self.get_parent_map([version_id])[version_id])
453
 
        except KeyError:
454
 
            raise errors.RevisionNotPresent(version_id, self)
 
365
        raise NotImplementedError(self.get_parents_with_ghosts)
 
366
 
 
367
    def annotate_iter(self, version_id):
 
368
        """Yield list of (version-id, line) pairs for the specified
 
369
        version.
 
370
 
 
371
        Must raise RevisionNotPresent if any of the given versions are
 
372
        not present in file history.
 
373
        """
 
374
        raise NotImplementedError(self.annotate_iter)
455
375
 
456
376
    def annotate(self, version_id):
457
 
        """Return a list of (version-id, line) tuples for version_id.
458
 
 
459
 
        :raise RevisionNotPresent: If the given version is
460
 
        not present in file history.
 
377
        return list(self.annotate_iter(version_id))
 
378
 
 
379
    def _apply_delta(self, lines, delta):
 
380
        """Apply delta to lines."""
 
381
        lines = list(lines)
 
382
        offset = 0
 
383
        for start, end, count, delta_lines in delta:
 
384
            lines[offset+start:offset+end] = delta_lines
 
385
            offset = offset + (start - end) + count
 
386
        return lines
 
387
 
 
388
    def join(self, other, pb=None, msg=None, version_ids=None,
 
389
             ignore_missing=False):
 
390
        """Integrate versions from other into this versioned file.
 
391
 
 
392
        If version_ids is None all versions from other should be
 
393
        incorporated into this versioned file.
 
394
 
 
395
        Must raise RevisionNotPresent if any of the specified versions
 
396
        are not present in the other files history unless ignore_missing
 
397
        is supplied when they are silently skipped.
461
398
        """
462
 
        raise NotImplementedError(self.annotate)
 
399
        self._check_write_ok()
 
400
        return InterVersionedFile.get(other, self).join(
 
401
            pb,
 
402
            msg,
 
403
            version_ids,
 
404
            ignore_missing)
463
405
 
464
 
    def iter_lines_added_or_present_in_versions(self, version_ids=None,
465
 
                                                pb=None):
 
406
    def iter_lines_added_or_present_in_versions(self, version_ids=None):
466
407
        """Iterate over the lines in the versioned file from version_ids.
467
408
 
468
 
        This may return lines from other versions. Each item the returned
469
 
        iterator yields is a tuple of a line and a text version that that line
470
 
        is present in (not introduced in).
471
 
 
472
 
        Ordering of results is in whatever order is most suitable for the
473
 
        underlying storage format.
474
 
 
475
 
        If a progress bar is supplied, it may be used to indicate progress.
476
 
        The caller is responsible for cleaning up progress bars (because this
477
 
        is an iterator).
 
409
        This may return lines from other versions, and does not return the
 
410
        specific version marker at this point. The api may be changed
 
411
        during development to include the version that the versioned file
 
412
        thinks is relevant, but given that such hints are just guesses,
 
413
        its better not to have it if we don't need it.
478
414
 
479
415
        NOTES: Lines are normalised: they will all have \n terminators.
480
416
               Lines are returned in arbitrary order.
481
 
 
482
 
        :return: An iterator over (line, version_id).
483
417
        """
484
418
        raise NotImplementedError(self.iter_lines_added_or_present_in_versions)
485
419
 
 
420
    def transaction_finished(self):
 
421
        """The transaction that this file was opened in has finished.
 
422
 
 
423
        This records self.finished = True and should cause all mutating
 
424
        operations to error.
 
425
        """
 
426
        self.finished = True
 
427
 
 
428
    @deprecated_method(zero_eight)
 
429
    def walk(self, version_ids=None):
 
430
        """Walk the versioned file as a weave-like structure, for
 
431
        versions relative to version_ids.  Yields sequence of (lineno,
 
432
        insert, deletes, text) for each relevant line.
 
433
 
 
434
        Must raise RevisionNotPresent if any of the specified versions
 
435
        are not present in the file history.
 
436
 
 
437
        :param version_ids: the version_ids to walk with respect to. If not
 
438
                            supplied the entire weave-like structure is walked.
 
439
 
 
440
        walk is deprecated in favour of iter_lines_added_or_present_in_versions
 
441
        """
 
442
        raise NotImplementedError(self.walk)
 
443
 
 
444
    @deprecated_method(zero_eight)
 
445
    def iter_names(self):
 
446
        """Walk the names list."""
 
447
        return iter(self.versions())
 
448
 
486
449
    def plan_merge(self, ver_a, ver_b):
487
450
        """Return pseudo-annotation indicating how the two versions merge.
488
451
 
505
468
        """
506
469
        raise NotImplementedError(VersionedFile.plan_merge)
507
470
        
508
 
    def weave_merge(self, plan, a_marker=TextMerge.A_MARKER,
 
471
    def weave_merge(self, plan, a_marker=TextMerge.A_MARKER, 
509
472
                    b_marker=TextMerge.B_MARKER):
510
473
        return PlanWeaveMerge(plan, a_marker, b_marker).merge_lines()[0]
511
474
 
512
475
 
513
 
class RecordingVersionedFilesDecorator(object):
514
 
    """A minimal versioned files that records calls made on it.
515
 
    
516
 
    Only enough methods have been added to support tests using it to date.
517
 
 
518
 
    :ivar calls: A list of the calls made; can be reset at any time by
519
 
        assigning [] to it.
520
 
    """
521
 
 
522
 
    def __init__(self, backing_vf):
523
 
        """Create a RecordingVersionedFileDsecorator decorating backing_vf.
524
 
        
525
 
        :param backing_vf: The versioned file to answer all methods.
526
 
        """
527
 
        self._backing_vf = backing_vf
528
 
        self.calls = []
529
 
 
530
 
    def add_lines(self, key, parents, lines, parent_texts=None,
531
 
        left_matching_blocks=None, nostore_sha=None, random_id=False,
532
 
        check_content=True):
533
 
        self.calls.append(("add_lines", key, parents, lines, parent_texts,
534
 
            left_matching_blocks, nostore_sha, random_id, check_content))
535
 
        return self._backing_vf.add_lines(key, parents, lines, parent_texts,
536
 
            left_matching_blocks, nostore_sha, random_id, check_content)
537
 
 
538
 
    def check(self):
539
 
        self._backing_vf.check()
540
 
 
541
 
    def get_parent_map(self, keys):
542
 
        self.calls.append(("get_parent_map", copy(keys)))
543
 
        return self._backing_vf.get_parent_map(keys)
544
 
 
545
 
    def get_record_stream(self, keys, sort_order, include_delta_closure):
546
 
        self.calls.append(("get_record_stream", list(keys), sort_order,
547
 
            include_delta_closure))
548
 
        return self._backing_vf.get_record_stream(keys, sort_order,
549
 
            include_delta_closure)
550
 
 
551
 
    def get_sha1s(self, keys):
552
 
        self.calls.append(("get_sha1s", copy(keys)))
553
 
        return self._backing_vf.get_sha1s(keys)
554
 
 
555
 
    def iter_lines_added_or_present_in_keys(self, keys, pb=None):
556
 
        self.calls.append(("iter_lines_added_or_present_in_keys", copy(keys)))
557
 
        return self._backing_vf.iter_lines_added_or_present_in_keys(keys, pb=pb)
558
 
 
559
 
    def keys(self):
560
 
        self.calls.append(("keys",))
561
 
        return self._backing_vf.keys()
562
 
 
563
 
 
564
 
class KeyMapper(object):
565
 
    """KeyMappers map between keys and underlying partitioned storage."""
566
 
 
567
 
    def map(self, key):
568
 
        """Map key to an underlying storage identifier.
569
 
 
570
 
        :param key: A key tuple e.g. ('file-id', 'revision-id').
571
 
        :return: An underlying storage identifier, specific to the partitioning
572
 
            mechanism.
573
 
        """
574
 
        raise NotImplementedError(self.map)
575
 
 
576
 
    def unmap(self, partition_id):
577
 
        """Map a partitioned storage id back to a key prefix.
578
 
        
579
 
        :param partition_id: The underlying partition id.
580
 
        :return: As much of a key (or prefix) as is derivable from the partition
581
 
            id.
582
 
        """
583
 
        raise NotImplementedError(self.unmap)
584
 
 
585
 
 
586
 
class ConstantMapper(KeyMapper):
587
 
    """A key mapper that maps to a constant result."""
588
 
 
589
 
    def __init__(self, result):
590
 
        """Create a ConstantMapper which will return result for all maps."""
591
 
        self._result = result
592
 
 
593
 
    def map(self, key):
594
 
        """See KeyMapper.map()."""
595
 
        return self._result
596
 
 
597
 
 
598
 
class URLEscapeMapper(KeyMapper):
599
 
    """Base class for use with transport backed storage.
600
 
 
601
 
    This provides a map and unmap wrapper that respectively url escape and
602
 
    unescape their outputs and inputs.
603
 
    """
604
 
 
605
 
    def map(self, key):
606
 
        """See KeyMapper.map()."""
607
 
        return urllib.quote(self._map(key))
608
 
 
609
 
    def unmap(self, partition_id):
610
 
        """See KeyMapper.unmap()."""
611
 
        return self._unmap(urllib.unquote(partition_id))
612
 
 
613
 
 
614
 
class PrefixMapper(URLEscapeMapper):
615
 
    """A key mapper that extracts the first component of a key.
616
 
    
617
 
    This mapper is for use with a transport based backend.
618
 
    """
619
 
 
620
 
    def _map(self, key):
621
 
        """See KeyMapper.map()."""
622
 
        return key[0]
623
 
 
624
 
    def _unmap(self, partition_id):
625
 
        """See KeyMapper.unmap()."""
626
 
        return (partition_id,)
627
 
 
628
 
 
629
 
class HashPrefixMapper(URLEscapeMapper):
630
 
    """A key mapper that combines the first component of a key with a hash.
631
 
 
632
 
    This mapper is for use with a transport based backend.
633
 
    """
634
 
 
635
 
    def _map(self, key):
636
 
        """See KeyMapper.map()."""
637
 
        prefix = self._escape(key[0])
638
 
        return "%02x/%s" % (adler32(prefix) & 0xff, prefix)
639
 
 
640
 
    def _escape(self, prefix):
641
 
        """No escaping needed here."""
642
 
        return prefix
643
 
 
644
 
    def _unmap(self, partition_id):
645
 
        """See KeyMapper.unmap()."""
646
 
        return (self._unescape(osutils.basename(partition_id)),)
647
 
 
648
 
    def _unescape(self, basename):
649
 
        """No unescaping needed for HashPrefixMapper."""
650
 
        return basename
651
 
 
652
 
 
653
 
class HashEscapedPrefixMapper(HashPrefixMapper):
654
 
    """Combines the escaped first component of a key with a hash.
655
 
    
656
 
    This mapper is for use with a transport based backend.
657
 
    """
658
 
 
659
 
    _safe = "abcdefghijklmnopqrstuvwxyz0123456789-_@,."
660
 
 
661
 
    def _escape(self, prefix):
662
 
        """Turn a key element into a filesystem safe string.
663
 
 
664
 
        This is similar to a plain urllib.quote, except
665
 
        it uses specific safe characters, so that it doesn't
666
 
        have to translate a lot of valid file ids.
667
 
        """
668
 
        # @ does not get escaped. This is because it is a valid
669
 
        # filesystem character we use all the time, and it looks
670
 
        # a lot better than seeing %40 all the time.
671
 
        r = [((c in self._safe) and c or ('%%%02x' % ord(c)))
672
 
             for c in prefix]
673
 
        return ''.join(r)
674
 
 
675
 
    def _unescape(self, basename):
676
 
        """Escaped names are easily unescaped by urlutils."""
677
 
        return urllib.unquote(basename)
678
 
 
679
 
 
680
 
def make_versioned_files_factory(versioned_file_factory, mapper):
681
 
    """Create a ThunkedVersionedFiles factory.
682
 
 
683
 
    This will create a callable which when called creates a
684
 
    ThunkedVersionedFiles on a transport, using mapper to access individual
685
 
    versioned files, and versioned_file_factory to create each individual file.
686
 
    """
687
 
    def factory(transport):
688
 
        return ThunkedVersionedFiles(transport, versioned_file_factory, mapper,
689
 
            lambda:True)
690
 
    return factory
691
 
 
692
 
 
693
 
class VersionedFiles(object):
694
 
    """Storage for many versioned files.
695
 
 
696
 
    This object allows a single keyspace for accessing the history graph and
697
 
    contents of named bytestrings.
698
 
 
699
 
    Currently no implementation allows the graph of different key prefixes to
700
 
    intersect, but the API does allow such implementations in the future.
701
 
 
702
 
    The keyspace is expressed via simple tuples. Any instance of VersionedFiles
703
 
    may have a different length key-size, but that size will be constant for
704
 
    all texts added to or retrieved from it. For instance, bzrlib uses
705
 
    instances with a key-size of 2 for storing user files in a repository, with
706
 
    the first element the fileid, and the second the version of that file.
707
 
 
708
 
    The use of tuples allows a single code base to support several different
709
 
    uses with only the mapping logic changing from instance to instance.
710
 
    """
711
 
 
712
 
    def add_lines(self, key, parents, lines, parent_texts=None,
713
 
        left_matching_blocks=None, nostore_sha=None, random_id=False,
714
 
        check_content=True):
715
 
        """Add a text to the store.
716
 
 
717
 
        :param key: The key tuple of the text to add.
718
 
        :param parents: The parents key tuples of the text to add.
719
 
        :param lines: A list of lines. Each line must be a bytestring. And all
720
 
            of them except the last must be terminated with \n and contain no
721
 
            other \n's. The last line may either contain no \n's or a single
722
 
            terminating \n. If the lines list does meet this constraint the add
723
 
            routine may error or may succeed - but you will be unable to read
724
 
            the data back accurately. (Checking the lines have been split
725
 
            correctly is expensive and extremely unlikely to catch bugs so it
726
 
            is not done at runtime unless check_content is True.)
727
 
        :param parent_texts: An optional dictionary containing the opaque 
728
 
            representations of some or all of the parents of version_id to
729
 
            allow delta optimisations.  VERY IMPORTANT: the texts must be those
730
 
            returned by add_lines or data corruption can be caused.
731
 
        :param left_matching_blocks: a hint about which areas are common
732
 
            between the text and its left-hand-parent.  The format is
733
 
            the SequenceMatcher.get_matching_blocks format.
734
 
        :param nostore_sha: Raise ExistingContent and do not add the lines to
735
 
            the versioned file if the digest of the lines matches this.
736
 
        :param random_id: If True a random id has been selected rather than
737
 
            an id determined by some deterministic process such as a converter
738
 
            from a foreign VCS. When True the backend may choose not to check
739
 
            for uniqueness of the resulting key within the versioned file, so
740
 
            this should only be done when the result is expected to be unique
741
 
            anyway.
742
 
        :param check_content: If True, the lines supplied are verified to be
743
 
            bytestrings that are correctly formed lines.
744
 
        :return: The text sha1, the number of bytes in the text, and an opaque
745
 
                 representation of the inserted version which can be provided
746
 
                 back to future add_lines calls in the parent_texts dictionary.
747
 
        """
748
 
        raise NotImplementedError(self.add_lines)
749
 
 
750
 
    def add_mpdiffs(self, records):
751
 
        """Add mpdiffs to this VersionedFile.
752
 
 
753
 
        Records should be iterables of version, parents, expected_sha1,
754
 
        mpdiff. mpdiff should be a MultiParent instance.
755
 
        """
756
 
        vf_parents = {}
757
 
        mpvf = multiparent.MultiMemoryVersionedFile()
758
 
        versions = []
759
 
        for version, parent_ids, expected_sha1, mpdiff in records:
760
 
            versions.append(version)
761
 
            mpvf.add_diff(mpdiff, version, parent_ids)
762
 
        needed_parents = set()
763
 
        for version, parent_ids, expected_sha1, mpdiff in records:
764
 
            needed_parents.update(p for p in parent_ids
765
 
                                  if not mpvf.has_version(p))
766
 
        # It seems likely that adding all the present parents as fulltexts can
767
 
        # easily exhaust memory.
768
 
        split_lines = osutils.split_lines
769
 
        for record in self.get_record_stream(needed_parents, 'unordered',
770
 
            True):
771
 
            if record.storage_kind == 'absent':
772
 
                continue
773
 
            mpvf.add_version(split_lines(record.get_bytes_as('fulltext')),
774
 
                record.key, [])
775
 
        for (key, parent_keys, expected_sha1, mpdiff), lines in\
776
 
            zip(records, mpvf.get_line_list(versions)):
777
 
            if len(parent_keys) == 1:
778
 
                left_matching_blocks = list(mpdiff.get_matching_blocks(0,
779
 
                    mpvf.get_diff(parent_keys[0]).num_lines()))
780
 
            else:
781
 
                left_matching_blocks = None
782
 
            version_sha1, _, version_text = self.add_lines(key,
783
 
                parent_keys, lines, vf_parents,
784
 
                left_matching_blocks=left_matching_blocks)
785
 
            if version_sha1 != expected_sha1:
786
 
                raise errors.VersionedFileInvalidChecksum(version)
787
 
            vf_parents[key] = version_text
788
 
 
789
 
    def annotate(self, key):
790
 
        """Return a list of (version-key, line) tuples for the text of key.
791
 
 
792
 
        :raise RevisionNotPresent: If the key is not present.
793
 
        """
794
 
        raise NotImplementedError(self.annotate)
795
 
 
796
 
    def check(self, progress_bar=None):
797
 
        """Check this object for integrity."""
798
 
        raise NotImplementedError(self.check)
799
 
 
800
 
    @staticmethod
801
 
    def check_not_reserved_id(version_id):
802
 
        revision.check_not_reserved_id(version_id)
803
 
 
804
 
    def _check_lines_not_unicode(self, lines):
805
 
        """Check that lines being added to a versioned file are not unicode."""
806
 
        for line in lines:
807
 
            if line.__class__ is not str:
808
 
                raise errors.BzrBadParameterUnicode("lines")
809
 
 
810
 
    def _check_lines_are_lines(self, lines):
811
 
        """Check that the lines really are full lines without inline EOL."""
812
 
        for line in lines:
813
 
            if '\n' in line[:-1]:
814
 
                raise errors.BzrBadParameterContainsNewline("lines")
815
 
 
816
 
    def get_parent_map(self, keys):
817
 
        """Get a map of the parents of keys.
818
 
 
819
 
        :param keys: The keys to look up parents for.
820
 
        :return: A mapping from keys to parents. Absent keys are absent from
821
 
            the mapping.
822
 
        """
823
 
        raise NotImplementedError(self.get_parent_map)
824
 
 
825
 
    def get_record_stream(self, keys, ordering, include_delta_closure):
826
 
        """Get a stream of records for keys.
827
 
 
828
 
        :param keys: The keys to include.
829
 
        :param ordering: Either 'unordered' or 'topological'. A topologically
830
 
            sorted stream has compression parents strictly before their
831
 
            children.
832
 
        :param include_delta_closure: If True then the closure across any
833
 
            compression parents will be included (in the opaque data).
834
 
        :return: An iterator of ContentFactory objects, each of which is only
835
 
            valid until the iterator is advanced.
836
 
        """
837
 
        raise NotImplementedError(self.get_record_stream)
838
 
 
839
 
    def get_sha1s(self, keys):
840
 
        """Get the sha1's of the texts for the given keys.
841
 
 
842
 
        :param keys: The names of the keys to lookup
843
 
        :return: a dict from key to sha1 digest. Keys of texts which are not
844
 
            present in the store are not present in the returned
845
 
            dictionary.
846
 
        """
847
 
        raise NotImplementedError(self.get_sha1s)
848
 
 
849
 
    def insert_record_stream(self, stream):
850
 
        """Insert a record stream into this container.
851
 
 
852
 
        :param stream: A stream of records to insert. 
853
 
        :return: None
854
 
        :seealso VersionedFile.get_record_stream:
855
 
        """
856
 
        raise NotImplementedError
857
 
 
858
 
    def iter_lines_added_or_present_in_keys(self, keys, pb=None):
859
 
        """Iterate over the lines in the versioned files from keys.
860
 
 
861
 
        This may return lines from other keys. Each item the returned
862
 
        iterator yields is a tuple of a line and a text version that that line
863
 
        is present in (not introduced in).
864
 
 
865
 
        Ordering of results is in whatever order is most suitable for the
866
 
        underlying storage format.
867
 
 
868
 
        If a progress bar is supplied, it may be used to indicate progress.
869
 
        The caller is responsible for cleaning up progress bars (because this
870
 
        is an iterator).
871
 
 
872
 
        NOTES:
873
 
         * Lines are normalised by the underlying store: they will all have \n
874
 
           terminators.
875
 
         * Lines are returned in arbitrary order.
876
 
 
877
 
        :return: An iterator over (line, key).
878
 
        """
879
 
        raise NotImplementedError(self.iter_lines_added_or_present_in_keys)
880
 
 
881
 
    def keys(self):
882
 
        """Return a iterable of the keys for all the contained texts."""
883
 
        raise NotImplementedError(self.keys)
884
 
 
885
 
    def make_mpdiffs(self, keys):
886
 
        """Create multiparent diffs for specified keys."""
887
 
        keys_order = tuple(keys)
888
 
        keys = frozenset(keys)
889
 
        knit_keys = set(keys)
890
 
        parent_map = self.get_parent_map(keys)
891
 
        for parent_keys in parent_map.itervalues():
892
 
            if parent_keys:
893
 
                knit_keys.update(parent_keys)
894
 
        missing_keys = keys - set(parent_map)
895
 
        if missing_keys:
896
 
            raise errors.RevisionNotPresent(list(missing_keys)[0], self)
897
 
        # We need to filter out ghosts, because we can't diff against them.
898
 
        maybe_ghosts = knit_keys - keys
899
 
        ghosts = maybe_ghosts - set(self.get_parent_map(maybe_ghosts))
900
 
        knit_keys.difference_update(ghosts)
901
 
        lines = {}
902
 
        split_lines = osutils.split_lines
903
 
        for record in self.get_record_stream(knit_keys, 'topological', True):
904
 
            lines[record.key] = split_lines(record.get_bytes_as('fulltext'))
905
 
            # line_block_dict = {}
906
 
            # for parent, blocks in record.extract_line_blocks():
907
 
            #   line_blocks[parent] = blocks
908
 
            # line_blocks[record.key] = line_block_dict
909
 
        diffs = []
910
 
        for key in keys_order:
911
 
            target = lines[key]
912
 
            parents = parent_map[key] or []
913
 
            # Note that filtering knit_keys can lead to a parent difference
914
 
            # between the creation and the application of the mpdiff.
915
 
            parent_lines = [lines[p] for p in parents if p in knit_keys]
916
 
            if len(parent_lines) > 0:
917
 
                left_parent_blocks = self._extract_blocks(key, parent_lines[0],
918
 
                    target)
919
 
            else:
920
 
                left_parent_blocks = None
921
 
            diffs.append(multiparent.MultiParent.from_lines(target,
922
 
                parent_lines, left_parent_blocks))
923
 
        return diffs
924
 
 
925
 
    def _extract_blocks(self, version_id, source, target):
926
 
        return None
927
 
 
928
 
 
929
 
class ThunkedVersionedFiles(VersionedFiles):
930
 
    """Storage for many versioned files thunked onto a 'VersionedFile' class.
931
 
 
932
 
    This object allows a single keyspace for accessing the history graph and
933
 
    contents of named bytestrings.
934
 
 
935
 
    Currently no implementation allows the graph of different key prefixes to
936
 
    intersect, but the API does allow such implementations in the future.
937
 
    """
938
 
 
939
 
    def __init__(self, transport, file_factory, mapper, is_locked):
940
 
        """Create a ThunkedVersionedFiles."""
941
 
        self._transport = transport
942
 
        self._file_factory = file_factory
943
 
        self._mapper = mapper
944
 
        self._is_locked = is_locked
945
 
 
946
 
    def add_lines(self, key, parents, lines, parent_texts=None,
947
 
        left_matching_blocks=None, nostore_sha=None, random_id=False,
948
 
        check_content=True):
949
 
        """See VersionedFiles.add_lines()."""
950
 
        path = self._mapper.map(key)
951
 
        version_id = key[-1]
952
 
        parents = [parent[-1] for parent in parents]
953
 
        vf = self._get_vf(path)
954
 
        try:
955
 
            try:
956
 
                return vf.add_lines_with_ghosts(version_id, parents, lines,
957
 
                    parent_texts=parent_texts,
958
 
                    left_matching_blocks=left_matching_blocks,
959
 
                    nostore_sha=nostore_sha, random_id=random_id,
960
 
                    check_content=check_content)
961
 
            except NotImplementedError:
962
 
                return vf.add_lines(version_id, parents, lines,
963
 
                    parent_texts=parent_texts,
964
 
                    left_matching_blocks=left_matching_blocks,
965
 
                    nostore_sha=nostore_sha, random_id=random_id,
966
 
                    check_content=check_content)
967
 
        except errors.NoSuchFile:
968
 
            # parent directory may be missing, try again.
969
 
            self._transport.mkdir(osutils.dirname(path))
970
 
            try:
971
 
                return vf.add_lines_with_ghosts(version_id, parents, lines,
972
 
                    parent_texts=parent_texts,
973
 
                    left_matching_blocks=left_matching_blocks,
974
 
                    nostore_sha=nostore_sha, random_id=random_id,
975
 
                    check_content=check_content)
976
 
            except NotImplementedError:
977
 
                return vf.add_lines(version_id, parents, lines,
978
 
                    parent_texts=parent_texts,
979
 
                    left_matching_blocks=left_matching_blocks,
980
 
                    nostore_sha=nostore_sha, random_id=random_id,
981
 
                    check_content=check_content)
982
 
 
983
 
    def annotate(self, key):
984
 
        """Return a list of (version-key, line) tuples for the text of key.
985
 
 
986
 
        :raise RevisionNotPresent: If the key is not present.
987
 
        """
988
 
        prefix = key[:-1]
989
 
        path = self._mapper.map(prefix)
990
 
        vf = self._get_vf(path)
991
 
        origins = vf.annotate(key[-1])
992
 
        result = []
993
 
        for origin, line in origins:
994
 
            result.append((prefix + (origin,), line))
995
 
        return result
996
 
 
997
 
    def check(self, progress_bar=None):
998
 
        """See VersionedFiles.check()."""
999
 
        for prefix, vf in self._iter_all_components():
1000
 
            vf.check()
1001
 
 
1002
 
    def get_parent_map(self, keys):
1003
 
        """Get a map of the parents of keys.
1004
 
 
1005
 
        :param keys: The keys to look up parents for.
1006
 
        :return: A mapping from keys to parents. Absent keys are absent from
1007
 
            the mapping.
1008
 
        """
1009
 
        prefixes = self._partition_keys(keys)
1010
 
        result = {}
1011
 
        for prefix, suffixes in prefixes.items():
1012
 
            path = self._mapper.map(prefix)
1013
 
            vf = self._get_vf(path)
1014
 
            parent_map = vf.get_parent_map(suffixes)
1015
 
            for key, parents in parent_map.items():
1016
 
                result[prefix + (key,)] = tuple(
1017
 
                    prefix + (parent,) for parent in parents)
1018
 
        return result
1019
 
 
1020
 
    def _get_vf(self, path):
1021
 
        if not self._is_locked():
1022
 
            raise errors.ObjectNotLocked(self)
1023
 
        return self._file_factory(path, self._transport, create=True,
1024
 
            get_scope=lambda:None)
1025
 
 
1026
 
    def _partition_keys(self, keys):
1027
 
        """Turn keys into a dict of prefix:suffix_list."""
1028
 
        result = {}
1029
 
        for key in keys:
1030
 
            prefix_keys = result.setdefault(key[:-1], [])
1031
 
            prefix_keys.append(key[-1])
1032
 
        return result
1033
 
 
1034
 
    def _get_all_prefixes(self):
1035
 
        # Identify all key prefixes.
1036
 
        # XXX: A bit hacky, needs polish.
1037
 
        if type(self._mapper) == ConstantMapper:
1038
 
            paths = [self._mapper.map(())]
1039
 
            prefixes = [()]
1040
 
        else:
1041
 
            relpaths = set()
1042
 
            for quoted_relpath in self._transport.iter_files_recursive():
1043
 
                path, ext = os.path.splitext(quoted_relpath)
1044
 
                relpaths.add(path)
1045
 
            paths = list(relpaths)
1046
 
            prefixes = [self._mapper.unmap(path) for path in paths]
1047
 
        return zip(paths, prefixes)
1048
 
 
1049
 
    def get_record_stream(self, keys, ordering, include_delta_closure):
1050
 
        """See VersionedFiles.get_record_stream()."""
1051
 
        # Ordering will be taken care of by each partitioned store; group keys
1052
 
        # by partition.
1053
 
        keys = sorted(keys)
1054
 
        for prefix, suffixes, vf in self._iter_keys_vf(keys):
1055
 
            suffixes = [(suffix,) for suffix in suffixes]
1056
 
            for record in vf.get_record_stream(suffixes, ordering,
1057
 
                include_delta_closure):
1058
 
                if record.parents is not None:
1059
 
                    record.parents = tuple(
1060
 
                        prefix + parent for parent in record.parents)
1061
 
                record.key = prefix + record.key
1062
 
                yield record
1063
 
 
1064
 
    def _iter_keys_vf(self, keys):
1065
 
        prefixes = self._partition_keys(keys)
1066
 
        sha1s = {}
1067
 
        for prefix, suffixes in prefixes.items():
1068
 
            path = self._mapper.map(prefix)
1069
 
            vf = self._get_vf(path)
1070
 
            yield prefix, suffixes, vf
1071
 
 
1072
 
    def get_sha1s(self, keys):
1073
 
        """See VersionedFiles.get_sha1s()."""
1074
 
        sha1s = {}
1075
 
        for prefix,suffixes, vf in self._iter_keys_vf(keys):
1076
 
            vf_sha1s = vf.get_sha1s(suffixes)
1077
 
            for suffix, sha1 in vf_sha1s.iteritems():
1078
 
                sha1s[prefix + (suffix,)] = sha1
1079
 
        return sha1s
1080
 
 
1081
 
    def insert_record_stream(self, stream):
1082
 
        """Insert a record stream into this container.
1083
 
 
1084
 
        :param stream: A stream of records to insert. 
1085
 
        :return: None
1086
 
        :seealso VersionedFile.get_record_stream:
1087
 
        """
1088
 
        for record in stream:
1089
 
            prefix = record.key[:-1]
1090
 
            key = record.key[-1:]
1091
 
            if record.parents is not None:
1092
 
                parents = [parent[-1:] for parent in record.parents]
1093
 
            else:
1094
 
                parents = None
1095
 
            thunk_record = AdapterFactory(key, parents, record)
1096
 
            path = self._mapper.map(prefix)
1097
 
            # Note that this parses the file many times; we can do better but
1098
 
            # as this only impacts weaves in terms of performance, it is
1099
 
            # tolerable.
1100
 
            vf = self._get_vf(path)
1101
 
            vf.insert_record_stream([thunk_record])
1102
 
 
1103
 
    def iter_lines_added_or_present_in_keys(self, keys, pb=None):
1104
 
        """Iterate over the lines in the versioned files from keys.
1105
 
 
1106
 
        This may return lines from other keys. Each item the returned
1107
 
        iterator yields is a tuple of a line and a text version that that line
1108
 
        is present in (not introduced in).
1109
 
 
1110
 
        Ordering of results is in whatever order is most suitable for the
1111
 
        underlying storage format.
1112
 
 
1113
 
        If a progress bar is supplied, it may be used to indicate progress.
1114
 
        The caller is responsible for cleaning up progress bars (because this
1115
 
        is an iterator).
1116
 
 
1117
 
        NOTES:
1118
 
         * Lines are normalised by the underlying store: they will all have \n
1119
 
           terminators.
1120
 
         * Lines are returned in arbitrary order.
1121
 
 
1122
 
        :return: An iterator over (line, key).
1123
 
        """
1124
 
        for prefix, suffixes, vf in self._iter_keys_vf(keys):
1125
 
            for line, version in vf.iter_lines_added_or_present_in_versions(suffixes):
1126
 
                yield line, prefix + (version,)
1127
 
 
1128
 
    def _iter_all_components(self):
1129
 
        for path, prefix in self._get_all_prefixes():
1130
 
            yield prefix, self._get_vf(path)
1131
 
 
1132
 
    def keys(self):
1133
 
        """See VersionedFiles.keys()."""
1134
 
        result = set()
1135
 
        for prefix, vf in self._iter_all_components():
1136
 
            for suffix in vf.versions():
1137
 
                result.add(prefix + (suffix,))
1138
 
        return result
1139
 
 
1140
 
 
1141
 
class _PlanMergeVersionedFile(VersionedFiles):
1142
 
    """A VersionedFile for uncommitted and committed texts.
1143
 
 
1144
 
    It is intended to allow merges to be planned with working tree texts.
1145
 
    It implements only the small part of the VersionedFiles interface used by
1146
 
    PlanMerge.  It falls back to multiple versionedfiles for data not stored in
1147
 
    _PlanMergeVersionedFile itself.
1148
 
 
1149
 
    :ivar: fallback_versionedfiles a list of VersionedFiles objects that can be
1150
 
        queried for missing texts.
1151
 
    """
1152
 
 
1153
 
    def __init__(self, file_id):
1154
 
        """Create a _PlanMergeVersionedFile.
1155
 
 
1156
 
        :param file_id: Used with _PlanMerge code which is not yet fully
1157
 
            tuple-keyspace aware.
1158
 
        """
1159
 
        self._file_id = file_id
1160
 
        # fallback locations
1161
 
        self.fallback_versionedfiles = []
1162
 
        # Parents for locally held keys.
1163
 
        self._parents = {}
1164
 
        # line data for locally held keys.
1165
 
        self._lines = {}
1166
 
        # key lookup providers
1167
 
        self._providers = [DictParentsProvider(self._parents)]
1168
 
 
1169
 
    def plan_merge(self, ver_a, ver_b, base=None):
1170
 
        """See VersionedFile.plan_merge"""
1171
 
        from bzrlib.merge import _PlanMerge
1172
 
        if base is None:
1173
 
            return _PlanMerge(ver_a, ver_b, self, (self._file_id,)).plan_merge()
1174
 
        old_plan = list(_PlanMerge(ver_a, base, self, (self._file_id,)).plan_merge())
1175
 
        new_plan = list(_PlanMerge(ver_a, ver_b, self, (self._file_id,)).plan_merge())
1176
 
        return _PlanMerge._subtract_plans(old_plan, new_plan)
1177
 
 
1178
 
    def plan_lca_merge(self, ver_a, ver_b, base=None):
1179
 
        from bzrlib.merge import _PlanLCAMerge
1180
 
        graph = Graph(self)
1181
 
        new_plan = _PlanLCAMerge(ver_a, ver_b, self, (self._file_id,), graph).plan_merge()
1182
 
        if base is None:
1183
 
            return new_plan
1184
 
        old_plan = _PlanLCAMerge(ver_a, base, self, (self._file_id,), graph).plan_merge()
1185
 
        return _PlanLCAMerge._subtract_plans(list(old_plan), list(new_plan))
1186
 
 
1187
 
    def add_lines(self, key, parents, lines):
1188
 
        """See VersionedFiles.add_lines
1189
 
 
1190
 
        Lines are added locally, not to fallback versionedfiles.  Also, ghosts
1191
 
        are permitted.  Only reserved ids are permitted.
1192
 
        """
1193
 
        if type(key) is not tuple:
1194
 
            raise TypeError(key)
1195
 
        if not revision.is_reserved_id(key[-1]):
1196
 
            raise ValueError('Only reserved ids may be used')
1197
 
        if parents is None:
1198
 
            raise ValueError('Parents may not be None')
1199
 
        if lines is None:
1200
 
            raise ValueError('Lines may not be None')
1201
 
        self._parents[key] = tuple(parents)
1202
 
        self._lines[key] = lines
1203
 
 
1204
 
    def get_record_stream(self, keys, ordering, include_delta_closure):
1205
 
        pending = set(keys)
1206
 
        for key in keys:
1207
 
            if key in self._lines:
1208
 
                lines = self._lines[key]
1209
 
                parents = self._parents[key]
1210
 
                pending.remove(key)
1211
 
                yield FulltextContentFactory(key, parents, None,
1212
 
                    ''.join(lines))
1213
 
        for versionedfile in self.fallback_versionedfiles:
1214
 
            for record in versionedfile.get_record_stream(
1215
 
                pending, 'unordered', True):
1216
 
                if record.storage_kind == 'absent':
1217
 
                    continue
1218
 
                else:
1219
 
                    pending.remove(record.key)
1220
 
                    yield record
1221
 
            if not pending:
1222
 
                return
1223
 
        # report absent entries
1224
 
        for key in pending:
1225
 
            yield AbsentContentFactory(key)
1226
 
 
1227
 
    def get_parent_map(self, keys):
1228
 
        """See VersionedFiles.get_parent_map"""
1229
 
        # We create a new provider because a fallback may have been added.
1230
 
        # If we make fallbacks private we can update a stack list and avoid
1231
 
        # object creation thrashing.
1232
 
        keys = set(keys)
1233
 
        result = {}
1234
 
        if revision.NULL_REVISION in keys:
1235
 
            keys.remove(revision.NULL_REVISION)
1236
 
            result[revision.NULL_REVISION] = ()
1237
 
        self._providers = self._providers[:1] + self.fallback_versionedfiles
1238
 
        result.update(
1239
 
            _StackedParentsProvider(self._providers).get_parent_map(keys))
1240
 
        for key, parents in result.iteritems():
1241
 
            if parents == ():
1242
 
                result[key] = (revision.NULL_REVISION,)
1243
 
        return result
1244
 
 
1245
 
 
1246
476
class PlanWeaveMerge(TextMerge):
1247
477
    """Weave merge that takes a plan as its input.
1248
478
    
1300
530
            elif state == 'new-b':
1301
531
                ch_b = True
1302
532
                lines_b.append(line)
1303
 
            elif state == 'conflicted-a':
1304
 
                ch_b = ch_a = True
1305
 
                lines_a.append(line)
1306
 
            elif state == 'conflicted-b':
1307
 
                ch_b = ch_a = True
1308
 
                lines_b.append(line)
1309
533
            else:
1310
 
                if state not in ('irrelevant', 'ghost-a', 'ghost-b',
1311
 
                        'killed-base', 'killed-both'):
1312
 
                    raise AssertionError(state)
 
534
                assert state in ('irrelevant', 'ghost-a', 'ghost-b', 
 
535
                                 'killed-base', 'killed-both'), state
1313
536
        for struct in outstanding_struct():
1314
537
            yield struct
1315
538
 
1316
539
 
1317
540
class WeaveMerge(PlanWeaveMerge):
1318
 
    """Weave merge that takes a VersionedFile and two versions as its input."""
 
541
    """Weave merge that takes a VersionedFile and two versions as its input"""
1319
542
 
1320
543
    def __init__(self, versionedfile, ver_a, ver_b, 
1321
544
        a_marker=PlanWeaveMerge.A_MARKER, b_marker=PlanWeaveMerge.B_MARKER):
1323
546
        PlanWeaveMerge.__init__(self, plan, a_marker, b_marker)
1324
547
 
1325
548
 
1326
 
class VirtualVersionedFiles(VersionedFiles):
1327
 
    """Dummy implementation for VersionedFiles that uses other functions for 
1328
 
    obtaining fulltexts and parent maps.
1329
 
 
1330
 
    This is always on the bottom of the stack and uses string keys 
1331
 
    (rather than tuples) internally.
 
549
class InterVersionedFile(InterObject):
 
550
    """This class represents operations taking place between two versionedfiles..
 
551
 
 
552
    Its instances have methods like join, and contain
 
553
    references to the source and target versionedfiles these operations can be 
 
554
    carried out on.
 
555
 
 
556
    Often we will provide convenience methods on 'versionedfile' which carry out
 
557
    operations with another versionedfile - they will always forward to
 
558
    InterVersionedFile.get(other).method_name(parameters).
1332
559
    """
1333
560
 
1334
 
    def __init__(self, get_parent_map, get_lines):
1335
 
        """Create a VirtualVersionedFiles.
1336
 
 
1337
 
        :param get_parent_map: Same signature as Repository.get_parent_map.
1338
 
        :param get_lines: Should return lines for specified key or None if 
1339
 
                          not available.
1340
 
        """
1341
 
        super(VirtualVersionedFiles, self).__init__()
1342
 
        self._get_parent_map = get_parent_map
1343
 
        self._get_lines = get_lines
1344
 
        
1345
 
    def check(self, progressbar=None):
1346
 
        """See VersionedFiles.check.
1347
 
 
1348
 
        :note: Always returns True for VirtualVersionedFiles.
1349
 
        """
1350
 
        return True
1351
 
 
1352
 
    def add_mpdiffs(self, records):
1353
 
        """See VersionedFiles.mpdiffs.
1354
 
 
1355
 
        :note: Not implemented for VirtualVersionedFiles.
1356
 
        """
1357
 
        raise NotImplementedError(self.add_mpdiffs)
1358
 
 
1359
 
    def get_parent_map(self, keys):
1360
 
        """See VersionedFiles.get_parent_map."""
1361
 
        return dict([((k,), tuple([(p,) for p in v]))
1362
 
            for k,v in self._get_parent_map([k for (k,) in keys]).iteritems()])
1363
 
 
1364
 
    def get_sha1s(self, keys):
1365
 
        """See VersionedFiles.get_sha1s."""
1366
 
        ret = {}
1367
 
        for (k,) in keys:
1368
 
            lines = self._get_lines(k)
1369
 
            if lines is not None:
1370
 
                if not isinstance(lines, list):
1371
 
                    raise AssertionError
1372
 
                ret[(k,)] = osutils.sha_strings(lines)
1373
 
        return ret
1374
 
 
1375
 
    def get_record_stream(self, keys, ordering, include_delta_closure):
1376
 
        """See VersionedFiles.get_record_stream."""
1377
 
        for (k,) in list(keys):
1378
 
            lines = self._get_lines(k)
1379
 
            if lines is not None:
1380
 
                if not isinstance(lines, list):
1381
 
                    raise AssertionError
1382
 
                yield FulltextContentFactory((k,), None, 
1383
 
                        sha1=osutils.sha_strings(lines),
1384
 
                        text=''.join(lines))
 
561
    _optimisers = set()
 
562
    """The available optimised InterVersionedFile types."""
 
563
 
 
564
    def join(self, pb=None, msg=None, version_ids=None, ignore_missing=False):
 
565
        """Integrate versions from self.source into self.target.
 
566
 
 
567
        If version_ids is None all versions from source should be
 
568
        incorporated into this versioned file.
 
569
 
 
570
        Must raise RevisionNotPresent if any of the specified versions
 
571
        are not present in the other files history unless ignore_missing is 
 
572
        supplied when they are silently skipped.
 
573
        """
 
574
        # the default join: 
 
575
        # - if the target is empty, just add all the versions from 
 
576
        #   source to target, otherwise:
 
577
        # - make a temporary versioned file of type target
 
578
        # - insert the source content into it one at a time
 
579
        # - join them
 
580
        if not self.target.versions():
 
581
            target = self.target
 
582
        else:
 
583
            # Make a new target-format versioned file. 
 
584
            temp_source = self.target.create_empty("temp", MemoryTransport())
 
585
            target = temp_source
 
586
        version_ids = self._get_source_version_ids(version_ids, ignore_missing)
 
587
        graph = self.source.get_graph(version_ids)
 
588
        order = topo_sort(graph.items())
 
589
        pb = ui.ui_factory.nested_progress_bar()
 
590
        parent_texts = {}
 
591
        try:
 
592
            # TODO for incremental cross-format work:
 
593
            # make a versioned file with the following content:
 
594
            # all revisions we have been asked to join
 
595
            # all their ancestors that are *not* in target already.
 
596
            # the immediate parents of the above two sets, with 
 
597
            # empty parent lists - these versions are in target already
 
598
            # and the incorrect version data will be ignored.
 
599
            # TODO: for all ancestors that are present in target already,
 
600
            # check them for consistent data, this requires moving sha1 from
 
601
            # 
 
602
            # TODO: remove parent texts when they are not relevant any more for 
 
603
            # memory pressure reduction. RBC 20060313
 
604
            # pb.update('Converting versioned data', 0, len(order))
 
605
            # deltas = self.source.get_deltas(order)
 
606
            for index, version in enumerate(order):
 
607
                pb.update('Converting versioned data', index, len(order))
 
608
                parent_text = target.add_lines(version,
 
609
                                               self.source.get_parents(version),
 
610
                                               self.source.get_lines(version),
 
611
                                               parent_texts=parent_texts)
 
612
                parent_texts[version] = parent_text
 
613
                #delta_parent, sha1, noeol, delta = deltas[version]
 
614
                #target.add_delta(version,
 
615
                #                 self.source.get_parents(version),
 
616
                #                 delta_parent,
 
617
                #                 sha1,
 
618
                #                 noeol,
 
619
                #                 delta)
 
620
                #target.get_lines(version)
 
621
            
 
622
            # this should hit the native code path for target
 
623
            if target is not self.target:
 
624
                return self.target.join(temp_source,
 
625
                                        pb,
 
626
                                        msg,
 
627
                                        version_ids,
 
628
                                        ignore_missing)
 
629
        finally:
 
630
            pb.finished()
 
631
 
 
632
    def _get_source_version_ids(self, version_ids, ignore_missing):
 
633
        """Determine the version ids to be used from self.source.
 
634
 
 
635
        :param version_ids: The caller-supplied version ids to check. (None 
 
636
                            for all). If None is in version_ids, it is stripped.
 
637
        :param ignore_missing: if True, remove missing ids from the version 
 
638
                               list. If False, raise RevisionNotPresent on
 
639
                               a missing version id.
 
640
        :return: A set of version ids.
 
641
        """
 
642
        if version_ids is None:
 
643
            # None cannot be in source.versions
 
644
            return set(self.source.versions())
 
645
        else:
 
646
            if ignore_missing:
 
647
                return set(self.source.versions()).intersection(set(version_ids))
1385
648
            else:
1386
 
                yield AbsentContentFactory((k,))
1387
 
 
1388
 
 
1389
 
 
 
649
                new_version_ids = set()
 
650
                for version in version_ids:
 
651
                    if version is None:
 
652
                        continue
 
653
                    if not self.source.has_version(version):
 
654
                        raise errors.RevisionNotPresent(version, str(self.source))
 
655
                    else:
 
656
                        new_version_ids.add(version)
 
657
                return new_version_ids
 
658
 
 
659
 
 
660
class InterVersionedFileTestProviderAdapter(object):
 
661
    """A tool to generate a suite testing multiple inter versioned-file classes.
 
662
 
 
663
    This is done by copying the test once for each InterVersionedFile provider
 
664
    and injecting the transport_server, transport_readonly_server,
 
665
    versionedfile_factory and versionedfile_factory_to classes into each copy.
 
666
    Each copy is also given a new id() to make it easy to identify.
 
667
    """
 
668
 
 
669
    def __init__(self, transport_server, transport_readonly_server, formats):
 
670
        self._transport_server = transport_server
 
671
        self._transport_readonly_server = transport_readonly_server
 
672
        self._formats = formats
 
673
    
 
674
    def adapt(self, test):
 
675
        result = TestSuite()
 
676
        for (interversionedfile_class,
 
677
             versionedfile_factory,
 
678
             versionedfile_factory_to) in self._formats:
 
679
            new_test = deepcopy(test)
 
680
            new_test.transport_server = self._transport_server
 
681
            new_test.transport_readonly_server = self._transport_readonly_server
 
682
            new_test.interversionedfile_class = interversionedfile_class
 
683
            new_test.versionedfile_factory = versionedfile_factory
 
684
            new_test.versionedfile_factory_to = versionedfile_factory_to
 
685
            def make_new_test_id():
 
686
                new_id = "%s(%s)" % (new_test.id(), interversionedfile_class.__name__)
 
687
                return lambda: new_id
 
688
            new_test.id = make_new_test_id()
 
689
            result.addTest(new_test)
 
690
        return result
 
691
 
 
692
    @staticmethod
 
693
    def default_test_list():
 
694
        """Generate the default list of interversionedfile permutations to test."""
 
695
        from bzrlib.weave import WeaveFile
 
696
        from bzrlib.knit import KnitVersionedFile
 
697
        result = []
 
698
        # test the fallback InterVersionedFile from annotated knits to weave
 
699
        result.append((InterVersionedFile, 
 
700
                       KnitVersionedFile,
 
701
                       WeaveFile))
 
702
        for optimiser in InterVersionedFile._optimisers:
 
703
            result.append((optimiser,
 
704
                           optimiser._matching_file_from_factory,
 
705
                           optimiser._matching_file_to_factory
 
706
                           ))
 
707
        # if there are specific combinations we want to use, we can add them 
 
708
        # here.
 
709
        return result