~bzr-pqm/bzr/bzr.dev

« back to all changes in this revision

Viewing changes to bzrlib/versionedfile.py

  • Committer: Martin Pool
  • Date: 2007-04-04 01:22:11 UTC
  • mfrom: (2393.1.1 bzr.docs)
  • mto: This revision was merged to the branch mainline in revision 2397.
  • Revision ID: mbp@sourcefrog.net-20070404012211-sq269me6bai9m6xk
merge trunk and doc fix from elliot

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