~bzr-pqm/bzr/bzr.dev

« back to all changes in this revision

Viewing changes to bzrlib/versionedfile.py

(vila) Revise legal option names to be less drastic. (Vincent Ladeuil)

Show diffs side-by-side

added added

removed removed

Lines of Context:
1
 
# Copyright (C) 2005, 2006 by Canonical Ltd
2
 
#
3
 
# Authors:
4
 
#   Johan Rydberg <jrydberg@gnu.org>
 
1
# Copyright (C) 2006-2011 Canonical Ltd
5
2
#
6
3
# This program is free software; you can redistribute it and/or modify
7
4
# it under the terms of the GNU General Public License as published by
15
12
#
16
13
# You should have received a copy of the GNU General Public License
17
14
# along with this program; if not, write to the Free Software
18
 
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 
15
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
19
16
 
20
17
"""Versioned text file storage api."""
21
18
 
22
 
 
23
 
from copy import deepcopy
24
 
from unittest import TestSuite
25
 
 
26
 
 
27
 
import bzrlib.errors as errors
28
 
from bzrlib.inter import InterObject
 
19
from __future__ import absolute_import
 
20
 
 
21
from copy import copy
 
22
from cStringIO import StringIO
 
23
import os
 
24
import struct
 
25
from zlib import adler32
 
26
 
 
27
from bzrlib.lazy_import import lazy_import
 
28
lazy_import(globals(), """
 
29
from bzrlib import (
 
30
    annotate,
 
31
    bencode,
 
32
    errors,
 
33
    graph as _mod_graph,
 
34
    groupcompress,
 
35
    index,
 
36
    knit,
 
37
    osutils,
 
38
    multiparent,
 
39
    tsort,
 
40
    revision,
 
41
    urlutils,
 
42
    )
 
43
""")
 
44
from bzrlib.registry import Registry
29
45
from bzrlib.textmerge import TextMerge
30
 
from bzrlib.transport.memory import MemoryTransport
31
 
from bzrlib.tsort import topo_sort
32
 
from bzrlib import ui
33
 
from bzrlib.symbol_versioning import (deprecated_function,
34
 
        deprecated_method,
35
 
        zero_eight,
36
 
        )
 
46
 
 
47
 
 
48
adapter_registry = Registry()
 
49
adapter_registry.register_lazy(('knit-delta-gz', 'fulltext'), 'bzrlib.knit',
 
50
    'DeltaPlainToFullText')
 
51
adapter_registry.register_lazy(('knit-ft-gz', 'fulltext'), 'bzrlib.knit',
 
52
    'FTPlainToFullText')
 
53
adapter_registry.register_lazy(('knit-annotated-delta-gz', 'knit-delta-gz'),
 
54
    'bzrlib.knit', 'DeltaAnnotatedToUnannotated')
 
55
adapter_registry.register_lazy(('knit-annotated-delta-gz', 'fulltext'),
 
56
    'bzrlib.knit', 'DeltaAnnotatedToFullText')
 
57
adapter_registry.register_lazy(('knit-annotated-ft-gz', 'knit-ft-gz'),
 
58
    'bzrlib.knit', 'FTAnnotatedToUnannotated')
 
59
adapter_registry.register_lazy(('knit-annotated-ft-gz', 'fulltext'),
 
60
    'bzrlib.knit', 'FTAnnotatedToFullText')
 
61
# adapter_registry.register_lazy(('knit-annotated-ft-gz', 'chunked'),
 
62
#     'bzrlib.knit', 'FTAnnotatedToChunked')
 
63
 
 
64
 
 
65
class ContentFactory(object):
 
66
    """Abstract interface for insertion and retrieval from a VersionedFile.
 
67
 
 
68
    :ivar sha1: None, or the sha1 of the content fulltext.
 
69
    :ivar storage_kind: The native storage kind of this factory. One of
 
70
        'mpdiff', 'knit-annotated-ft', 'knit-annotated-delta', 'knit-ft',
 
71
        'knit-delta', 'fulltext', 'knit-annotated-ft-gz',
 
72
        'knit-annotated-delta-gz', 'knit-ft-gz', 'knit-delta-gz'.
 
73
    :ivar key: The key of this content. Each key is a tuple with a single
 
74
        string in it.
 
75
    :ivar parents: A tuple of parent keys for self.key. If the object has
 
76
        no parent information, None (as opposed to () for an empty list of
 
77
        parents).
 
78
    """
 
79
 
 
80
    def __init__(self):
 
81
        """Create a ContentFactory."""
 
82
        self.sha1 = None
 
83
        self.storage_kind = None
 
84
        self.key = None
 
85
        self.parents = None
 
86
 
 
87
 
 
88
class ChunkedContentFactory(ContentFactory):
 
89
    """Static data content factory.
 
90
 
 
91
    This takes a 'chunked' list of strings. The only requirement on 'chunked' is
 
92
    that ''.join(lines) becomes a valid fulltext. A tuple of a single string
 
93
    satisfies this, as does a list of lines.
 
94
 
 
95
    :ivar sha1: None, or the sha1 of the content fulltext.
 
96
    :ivar storage_kind: The native storage kind of this factory. Always
 
97
        'chunked'
 
98
    :ivar key: The key of this content. Each key is a tuple with a single
 
99
        string in it.
 
100
    :ivar parents: A tuple of parent keys for self.key. If the object has
 
101
        no parent information, None (as opposed to () for an empty list of
 
102
        parents).
 
103
     """
 
104
 
 
105
    def __init__(self, key, parents, sha1, chunks):
 
106
        """Create a ContentFactory."""
 
107
        self.sha1 = sha1
 
108
        self.storage_kind = 'chunked'
 
109
        self.key = key
 
110
        self.parents = parents
 
111
        self._chunks = chunks
 
112
 
 
113
    def get_bytes_as(self, storage_kind):
 
114
        if storage_kind == 'chunked':
 
115
            return self._chunks
 
116
        elif storage_kind == 'fulltext':
 
117
            return ''.join(self._chunks)
 
118
        raise errors.UnavailableRepresentation(self.key, storage_kind,
 
119
            self.storage_kind)
 
120
 
 
121
 
 
122
class FulltextContentFactory(ContentFactory):
 
123
    """Static data content factory.
 
124
 
 
125
    This takes a fulltext when created and just returns that during
 
126
    get_bytes_as('fulltext').
 
127
 
 
128
    :ivar sha1: None, or the sha1 of the content fulltext.
 
129
    :ivar storage_kind: The native storage kind of this factory. Always
 
130
        'fulltext'.
 
131
    :ivar key: The key of this content. Each key is a tuple with a single
 
132
        string in it.
 
133
    :ivar parents: A tuple of parent keys for self.key. If the object has
 
134
        no parent information, None (as opposed to () for an empty list of
 
135
        parents).
 
136
     """
 
137
 
 
138
    def __init__(self, key, parents, sha1, text):
 
139
        """Create a ContentFactory."""
 
140
        self.sha1 = sha1
 
141
        self.storage_kind = 'fulltext'
 
142
        self.key = key
 
143
        self.parents = parents
 
144
        self._text = text
 
145
 
 
146
    def get_bytes_as(self, storage_kind):
 
147
        if storage_kind == self.storage_kind:
 
148
            return self._text
 
149
        elif storage_kind == 'chunked':
 
150
            return [self._text]
 
151
        raise errors.UnavailableRepresentation(self.key, storage_kind,
 
152
            self.storage_kind)
 
153
 
 
154
 
 
155
class AbsentContentFactory(ContentFactory):
 
156
    """A placeholder content factory for unavailable texts.
 
157
 
 
158
    :ivar sha1: None.
 
159
    :ivar storage_kind: 'absent'.
 
160
    :ivar key: The key of this content. Each key is a tuple with a single
 
161
        string in it.
 
162
    :ivar parents: None.
 
163
    """
 
164
 
 
165
    def __init__(self, key):
 
166
        """Create a ContentFactory."""
 
167
        self.sha1 = None
 
168
        self.storage_kind = 'absent'
 
169
        self.key = key
 
170
        self.parents = None
 
171
 
 
172
    def get_bytes_as(self, storage_kind):
 
173
        raise ValueError('A request was made for key: %s, but that'
 
174
                         ' content is not available, and the calling'
 
175
                         ' code does not handle if it is missing.'
 
176
                         % (self.key,))
 
177
 
 
178
 
 
179
class AdapterFactory(ContentFactory):
 
180
    """A content factory to adapt between key prefix's."""
 
181
 
 
182
    def __init__(self, key, parents, adapted):
 
183
        """Create an adapter factory instance."""
 
184
        self.key = key
 
185
        self.parents = parents
 
186
        self._adapted = adapted
 
187
 
 
188
    def __getattr__(self, attr):
 
189
        """Return a member from the adapted object."""
 
190
        if attr in ('key', 'parents'):
 
191
            return self.__dict__[attr]
 
192
        else:
 
193
            return getattr(self._adapted, attr)
 
194
 
 
195
 
 
196
def filter_absent(record_stream):
 
197
    """Adapt a record stream to remove absent records."""
 
198
    for record in record_stream:
 
199
        if record.storage_kind != 'absent':
 
200
            yield record
 
201
 
 
202
 
 
203
class _MPDiffGenerator(object):
 
204
    """Pull out the functionality for generating mp_diffs."""
 
205
 
 
206
    def __init__(self, vf, keys):
 
207
        self.vf = vf
 
208
        # This is the order the keys were requested in
 
209
        self.ordered_keys = tuple(keys)
 
210
        # keys + their parents, what we need to compute the diffs
 
211
        self.needed_keys = ()
 
212
        # Map from key: mp_diff
 
213
        self.diffs = {}
 
214
        # Map from key: parents_needed (may have ghosts)
 
215
        self.parent_map = {}
 
216
        # Parents that aren't present
 
217
        self.ghost_parents = ()
 
218
        # Map from parent_key => number of children for this text
 
219
        self.refcounts = {}
 
220
        # Content chunks that are cached while we still need them
 
221
        self.chunks = {}
 
222
 
 
223
    def _find_needed_keys(self):
 
224
        """Find the set of keys we need to request.
 
225
 
 
226
        This includes all the original keys passed in, and the non-ghost
 
227
        parents of those keys.
 
228
 
 
229
        :return: (needed_keys, refcounts)
 
230
            needed_keys is the set of all texts we need to extract
 
231
            refcounts is a dict of {key: num_children} letting us know when we
 
232
                no longer need to cache a given parent text
 
233
        """
 
234
        # All the keys and their parents
 
235
        needed_keys = set(self.ordered_keys)
 
236
        parent_map = self.vf.get_parent_map(needed_keys)
 
237
        self.parent_map = parent_map
 
238
        # TODO: Should we be using a different construct here? I think this
 
239
        #       uses difference_update internally, and we expect the result to
 
240
        #       be tiny
 
241
        missing_keys = needed_keys.difference(parent_map)
 
242
        if missing_keys:
 
243
            raise errors.RevisionNotPresent(list(missing_keys)[0], self.vf)
 
244
        # Parents that might be missing. They are allowed to be ghosts, but we
 
245
        # should check for them
 
246
        refcounts = {}
 
247
        setdefault = refcounts.setdefault
 
248
        just_parents = set()
 
249
        for child_key, parent_keys in parent_map.iteritems():
 
250
            if not parent_keys:
 
251
                # parent_keys may be None if a given VersionedFile claims to
 
252
                # not support graph operations.
 
253
                continue
 
254
            just_parents.update(parent_keys)
 
255
            needed_keys.update(parent_keys)
 
256
            for p in parent_keys:
 
257
                refcounts[p] = setdefault(p, 0) + 1
 
258
        just_parents.difference_update(parent_map)
 
259
        # Remove any parents that are actually ghosts from the needed set
 
260
        self.present_parents = set(self.vf.get_parent_map(just_parents))
 
261
        self.ghost_parents = just_parents.difference(self.present_parents)
 
262
        needed_keys.difference_update(self.ghost_parents)
 
263
        self.needed_keys = needed_keys
 
264
        self.refcounts = refcounts
 
265
        return needed_keys, refcounts
 
266
 
 
267
    def _compute_diff(self, key, parent_lines, lines):
 
268
        """Compute a single mp_diff, and store it in self._diffs"""
 
269
        if len(parent_lines) > 0:
 
270
            # XXX: _extract_blocks is not usefully defined anywhere...
 
271
            #      It was meant to extract the left-parent diff without
 
272
            #      having to recompute it for Knit content (pack-0.92,
 
273
            #      etc). That seems to have regressed somewhere
 
274
            left_parent_blocks = self.vf._extract_blocks(key,
 
275
                parent_lines[0], lines)
 
276
        else:
 
277
            left_parent_blocks = None
 
278
        diff = multiparent.MultiParent.from_lines(lines,
 
279
                    parent_lines, left_parent_blocks)
 
280
        self.diffs[key] = diff
 
281
 
 
282
    def _process_one_record(self, key, this_chunks):
 
283
        parent_keys = None
 
284
        if key in self.parent_map:
 
285
            # This record should be ready to diff, since we requested
 
286
            # content in 'topological' order
 
287
            parent_keys = self.parent_map.pop(key)
 
288
            # If a VersionedFile claims 'no-graph' support, then it may return
 
289
            # None for any parent request, so we replace it with an empty tuple
 
290
            if parent_keys is None:
 
291
                parent_keys = ()
 
292
            parent_lines = []
 
293
            for p in parent_keys:
 
294
                # Alternatively we could check p not in self.needed_keys, but
 
295
                # ghost_parents should be tiny versus huge
 
296
                if p in self.ghost_parents:
 
297
                    continue
 
298
                refcount = self.refcounts[p]
 
299
                if refcount == 1: # Last child reference
 
300
                    self.refcounts.pop(p)
 
301
                    parent_chunks = self.chunks.pop(p)
 
302
                else:
 
303
                    self.refcounts[p] = refcount - 1
 
304
                    parent_chunks = self.chunks[p]
 
305
                p_lines = osutils.chunks_to_lines(parent_chunks)
 
306
                # TODO: Should we cache the line form? We did the
 
307
                #       computation to get it, but storing it this way will
 
308
                #       be less memory efficient...
 
309
                parent_lines.append(p_lines)
 
310
                del p_lines
 
311
            lines = osutils.chunks_to_lines(this_chunks)
 
312
            # Since we needed the lines, we'll go ahead and cache them this way
 
313
            this_chunks = lines
 
314
            self._compute_diff(key, parent_lines, lines)
 
315
            del lines
 
316
        # Is this content required for any more children?
 
317
        if key in self.refcounts:
 
318
            self.chunks[key] = this_chunks
 
319
 
 
320
    def _extract_diffs(self):
 
321
        needed_keys, refcounts = self._find_needed_keys()
 
322
        for record in self.vf.get_record_stream(needed_keys,
 
323
                                                'topological', True):
 
324
            if record.storage_kind == 'absent':
 
325
                raise errors.RevisionNotPresent(record.key, self.vf)
 
326
            self._process_one_record(record.key,
 
327
                                     record.get_bytes_as('chunked'))
 
328
        
 
329
    def compute_diffs(self):
 
330
        self._extract_diffs()
 
331
        dpop = self.diffs.pop
 
332
        return [dpop(k) for k in self.ordered_keys]
37
333
 
38
334
 
39
335
class VersionedFile(object):
40
336
    """Versioned text file storage.
41
 
    
 
337
 
42
338
    A versioned file manages versions of line-based text files,
43
339
    keeping track of the originating version for each line.
44
340
 
50
346
    Texts are identified by a version-id string.
51
347
    """
52
348
 
53
 
    def __init__(self, access_mode):
54
 
        self.finished = False
55
 
        self._access_mode = access_mode
 
349
    @staticmethod
 
350
    def check_not_reserved_id(version_id):
 
351
        revision.check_not_reserved_id(version_id)
56
352
 
57
353
    def copy_to(self, name, transport):
58
354
        """Copy this versioned file to name on transport."""
59
355
        raise NotImplementedError(self.copy_to)
60
356
 
61
 
    @deprecated_method(zero_eight)
62
 
    def names(self):
63
 
        """Return a list of all the versions in this versioned file.
 
357
    def get_record_stream(self, versions, ordering, include_delta_closure):
 
358
        """Get a stream of records for versions.
64
359
 
65
 
        Please use versionedfile.versions() now.
 
360
        :param versions: The versions to include. Each version is a tuple
 
361
            (version,).
 
362
        :param ordering: Either 'unordered' or 'topological'. A topologically
 
363
            sorted stream has compression parents strictly before their
 
364
            children.
 
365
        :param include_delta_closure: If True then the closure across any
 
366
            compression parents will be included (in the data content of the
 
367
            stream, not in the emitted records). This guarantees that
 
368
            'fulltext' can be used successfully on every record.
 
369
        :return: An iterator of ContentFactory objects, each of which is only
 
370
            valid until the iterator is advanced.
66
371
        """
67
 
        return self.versions()
68
 
 
69
 
    def versions(self):
70
 
        """Return a unsorted list of versions."""
71
 
        raise NotImplementedError(self.versions)
72
 
 
73
 
    def has_ghost(self, version_id):
74
 
        """Returns whether version is present as a ghost."""
75
 
        raise NotImplementedError(self.has_ghost)
 
372
        raise NotImplementedError(self.get_record_stream)
76
373
 
77
374
    def has_version(self, version_id):
78
375
        """Returns whether version is present."""
79
376
        raise NotImplementedError(self.has_version)
80
377
 
81
 
    def add_delta(self, version_id, parents, delta_parent, sha1, noeol, delta):
82
 
        """Add a text to the versioned file via a pregenerated delta.
83
 
 
84
 
        :param version_id: The version id being added.
85
 
        :param parents: The parents of the version_id.
86
 
        :param delta_parent: The parent this delta was created against.
87
 
        :param sha1: The sha1 of the full text.
88
 
        :param delta: The delta instructions. See get_delta for details.
89
 
        """
90
 
        self._check_write_ok()
91
 
        if self.has_version(version_id):
92
 
            raise errors.RevisionAlreadyPresent(version_id, self)
93
 
        return self._add_delta(version_id, parents, delta_parent, sha1, noeol, delta)
94
 
 
95
 
    def _add_delta(self, version_id, parents, delta_parent, sha1, noeol, delta):
96
 
        """Class specific routine to add a delta.
97
 
 
98
 
        This generic version simply applies the delta to the delta_parent and
99
 
        then inserts it.
100
 
        """
101
 
        # strip annotation from delta
102
 
        new_delta = []
103
 
        for start, stop, delta_len, delta_lines in delta:
104
 
            new_delta.append((start, stop, delta_len, [text for origin, text in delta_lines]))
105
 
        if delta_parent is not None:
106
 
            parent_full = self.get_lines(delta_parent)
107
 
        else:
108
 
            parent_full = []
109
 
        new_full = self._apply_delta(parent_full, new_delta)
110
 
        # its impossible to have noeol on an empty file
111
 
        if noeol and new_full[-1][-1] == '\n':
112
 
            new_full[-1] = new_full[-1][:-1]
113
 
        self.add_lines(version_id, parents, new_full)
114
 
 
115
 
    def add_lines(self, version_id, parents, lines, parent_texts=None):
 
378
    def insert_record_stream(self, stream):
 
379
        """Insert a record stream into this versioned file.
 
380
 
 
381
        :param stream: A stream of records to insert.
 
382
        :return: None
 
383
        :seealso VersionedFile.get_record_stream:
 
384
        """
 
385
        raise NotImplementedError
 
386
 
 
387
    def add_lines(self, version_id, parents, lines, parent_texts=None,
 
388
        left_matching_blocks=None, nostore_sha=None, random_id=False,
 
389
        check_content=True):
116
390
        """Add a single text on top of the versioned file.
117
391
 
118
392
        Must raise RevisionAlreadyPresent if the new version is
120
394
 
121
395
        Must raise RevisionNotPresent if any of the given parents are
122
396
        not present in file history.
123
 
        :param parent_texts: An optional dictionary containing the opaque 
124
 
             representations of some or all of the parents of 
125
 
             version_id to allow delta optimisations. 
126
 
             VERY IMPORTANT: the texts must be those returned
127
 
             by add_lines or data corruption can be caused.
128
 
        :return: An opaque representation of the inserted version which can be
129
 
                 provided back to future add_lines calls in the parent_texts
130
 
                 dictionary.
 
397
 
 
398
        :param lines: A list of lines. Each line must be a bytestring. And all
 
399
            of them except the last must be terminated with \n and contain no
 
400
            other \n's. The last line may either contain no \n's or a single
 
401
            terminated \n. If the lines list does meet this constraint the add
 
402
            routine may error or may succeed - but you will be unable to read
 
403
            the data back accurately. (Checking the lines have been split
 
404
            correctly is expensive and extremely unlikely to catch bugs so it
 
405
            is not done at runtime unless check_content is True.)
 
406
        :param parent_texts: An optional dictionary containing the opaque
 
407
            representations of some or all of the parents of version_id to
 
408
            allow delta optimisations.  VERY IMPORTANT: the texts must be those
 
409
            returned by add_lines or data corruption can be caused.
 
410
        :param left_matching_blocks: a hint about which areas are common
 
411
            between the text and its left-hand-parent.  The format is
 
412
            the SequenceMatcher.get_matching_blocks format.
 
413
        :param nostore_sha: Raise ExistingContent and do not add the lines to
 
414
            the versioned file if the digest of the lines matches this.
 
415
        :param random_id: If True a random id has been selected rather than
 
416
            an id determined by some deterministic process such as a converter
 
417
            from a foreign VCS. When True the backend may choose not to check
 
418
            for uniqueness of the resulting key within the versioned file, so
 
419
            this should only be done when the result is expected to be unique
 
420
            anyway.
 
421
        :param check_content: If True, the lines supplied are verified to be
 
422
            bytestrings that are correctly formed lines.
 
423
        :return: The text sha1, the number of bytes in the text, and an opaque
 
424
                 representation of the inserted version which can be provided
 
425
                 back to future add_lines calls in the parent_texts dictionary.
131
426
        """
132
427
        self._check_write_ok()
133
 
        return self._add_lines(version_id, parents, lines, parent_texts)
 
428
        return self._add_lines(version_id, parents, lines, parent_texts,
 
429
            left_matching_blocks, nostore_sha, random_id, check_content)
134
430
 
135
 
    def _add_lines(self, version_id, parents, lines, parent_texts):
 
431
    def _add_lines(self, version_id, parents, lines, parent_texts,
 
432
        left_matching_blocks, nostore_sha, random_id, check_content):
136
433
        """Helper to do the class specific add_lines."""
137
434
        raise NotImplementedError(self.add_lines)
138
435
 
139
436
    def add_lines_with_ghosts(self, version_id, parents, lines,
140
 
                              parent_texts=None):
 
437
        parent_texts=None, nostore_sha=None, random_id=False,
 
438
        check_content=True, left_matching_blocks=None):
141
439
        """Add lines to the versioned file, allowing ghosts to be present.
142
 
        
143
 
        This takes the same parameters as add_lines.
 
440
 
 
441
        This takes the same parameters as add_lines and returns the same.
144
442
        """
145
443
        self._check_write_ok()
146
444
        return self._add_lines_with_ghosts(version_id, parents, lines,
147
 
                                           parent_texts)
 
445
            parent_texts, nostore_sha, random_id, check_content, left_matching_blocks)
148
446
 
149
 
    def _add_lines_with_ghosts(self, version_id, parents, lines, parent_texts):
 
447
    def _add_lines_with_ghosts(self, version_id, parents, lines, parent_texts,
 
448
        nostore_sha, random_id, check_content, left_matching_blocks):
150
449
        """Helper to do class specific add_lines_with_ghosts."""
151
450
        raise NotImplementedError(self.add_lines_with_ghosts)
152
451
 
166
465
            if '\n' in line[:-1]:
167
466
                raise errors.BzrBadParameterContainsNewline("lines")
168
467
 
169
 
    def _check_write_ok(self):
170
 
        """Is the versioned file marked as 'finished' ? Raise if it is."""
171
 
        if self.finished:
172
 
            raise errors.OutSideTransaction()
173
 
        if self._access_mode != 'w':
174
 
            raise errors.ReadOnlyObjectDirtiedError(self)
175
 
 
176
 
    def enable_cache(self):
177
 
        """Tell this versioned file that it should cache any data it reads.
178
 
        
179
 
        This is advisory, implementations do not have to support caching.
180
 
        """
181
 
        pass
182
 
    
183
 
    def clear_cache(self):
184
 
        """Remove any data cached in the versioned file object.
185
 
 
186
 
        This only needs to be supported if caches are supported
187
 
        """
188
 
        pass
189
 
 
190
 
    def clone_text(self, new_version_id, old_version_id, parents):
191
 
        """Add an identical text to old_version_id as new_version_id.
192
 
 
193
 
        Must raise RevisionNotPresent if the old version or any of the
194
 
        parents are not present in file history.
195
 
 
196
 
        Must raise RevisionAlreadyPresent if the new version is
197
 
        already present in file history."""
198
 
        self._check_write_ok()
199
 
        return self._clone_text(new_version_id, old_version_id, parents)
200
 
 
201
 
    def _clone_text(self, new_version_id, old_version_id, parents):
202
 
        """Helper function to do the _clone_text work."""
203
 
        raise NotImplementedError(self.clone_text)
204
 
 
205
 
    def create_empty(self, name, transport, mode=None):
206
 
        """Create a new versioned file of this exact type.
207
 
 
208
 
        :param name: the file name
209
 
        :param transport: the transport
210
 
        :param mode: optional file mode.
211
 
        """
212
 
        raise NotImplementedError(self.create_empty)
213
 
 
214
 
    def fix_parents(self, version, new_parents):
215
 
        """Fix the parents list for version.
216
 
        
217
 
        This is done by appending a new version to the index
218
 
        with identical data except for the parents list.
219
 
        the parents list must be a superset of the current
220
 
        list.
221
 
        """
222
 
        self._check_write_ok()
223
 
        return self._fix_parents(version, new_parents)
224
 
 
225
 
    def _fix_parents(self, version, new_parents):
226
 
        """Helper for fix_parents."""
227
 
        raise NotImplementedError(self.fix_parents)
228
 
 
229
 
    def get_delta(self, version):
230
 
        """Get a delta for constructing version from some other version.
231
 
        
232
 
        :return: (delta_parent, sha1, noeol, delta)
233
 
        Where delta_parent is a version id or None to indicate no parent.
234
 
        """
235
 
        raise NotImplementedError(self.get_delta)
236
 
 
237
 
    def get_deltas(self, versions):
238
 
        """Get multiple deltas at once for constructing versions.
239
 
        
240
 
        :return: dict(version_id:(delta_parent, sha1, noeol, delta))
241
 
        Where delta_parent is a version id or None to indicate no parent, and
242
 
        version_id is the version_id created by that delta.
243
 
        """
244
 
        result = {}
245
 
        for version in versions:
246
 
            result[version] = self.get_delta(version)
247
 
        return result
248
 
 
249
 
    def get_sha1(self, version_id):
250
 
        """Get the stored sha1 sum for the given revision.
251
 
        
252
 
        :param name: The name of the version to lookup
253
 
        """
254
 
        raise NotImplementedError(self.get_sha1)
255
 
 
256
 
    def get_suffixes(self):
257
 
        """Return the file suffixes associated with this versioned file."""
258
 
        raise NotImplementedError(self.get_suffixes)
259
 
    
 
468
    def get_format_signature(self):
 
469
        """Get a text description of the data encoding in this file.
 
470
 
 
471
        :since: 0.90
 
472
        """
 
473
        raise NotImplementedError(self.get_format_signature)
 
474
 
 
475
    def make_mpdiffs(self, version_ids):
 
476
        """Create multiparent diffs for specified versions."""
 
477
        # XXX: Can't use _MPDiffGenerator just yet. This is because version_ids
 
478
        #      is a list of strings, not keys. And while self.get_record_stream
 
479
        #      is supported, it takes *keys*, while self.get_parent_map() takes
 
480
        #      strings... *sigh*
 
481
        knit_versions = set()
 
482
        knit_versions.update(version_ids)
 
483
        parent_map = self.get_parent_map(version_ids)
 
484
        for version_id in version_ids:
 
485
            try:
 
486
                knit_versions.update(parent_map[version_id])
 
487
            except KeyError:
 
488
                raise errors.RevisionNotPresent(version_id, self)
 
489
        # We need to filter out ghosts, because we can't diff against them.
 
490
        knit_versions = set(self.get_parent_map(knit_versions).keys())
 
491
        lines = dict(zip(knit_versions,
 
492
            self._get_lf_split_line_list(knit_versions)))
 
493
        diffs = []
 
494
        for version_id in version_ids:
 
495
            target = lines[version_id]
 
496
            try:
 
497
                parents = [lines[p] for p in parent_map[version_id] if p in
 
498
                    knit_versions]
 
499
            except KeyError:
 
500
                # I don't know how this could ever trigger.
 
501
                # parent_map[version_id] was already triggered in the previous
 
502
                # for loop, and lines[p] has the 'if p in knit_versions' check,
 
503
                # so we again won't have a KeyError.
 
504
                raise errors.RevisionNotPresent(version_id, self)
 
505
            if len(parents) > 0:
 
506
                left_parent_blocks = self._extract_blocks(version_id,
 
507
                                                          parents[0], target)
 
508
            else:
 
509
                left_parent_blocks = None
 
510
            diffs.append(multiparent.MultiParent.from_lines(target, parents,
 
511
                         left_parent_blocks))
 
512
        return diffs
 
513
 
 
514
    def _extract_blocks(self, version_id, source, target):
 
515
        return None
 
516
 
 
517
    def add_mpdiffs(self, records):
 
518
        """Add mpdiffs to this VersionedFile.
 
519
 
 
520
        Records should be iterables of version, parents, expected_sha1,
 
521
        mpdiff. mpdiff should be a MultiParent instance.
 
522
        """
 
523
        # Does this need to call self._check_write_ok()? (IanC 20070919)
 
524
        vf_parents = {}
 
525
        mpvf = multiparent.MultiMemoryVersionedFile()
 
526
        versions = []
 
527
        for version, parent_ids, expected_sha1, mpdiff in records:
 
528
            versions.append(version)
 
529
            mpvf.add_diff(mpdiff, version, parent_ids)
 
530
        needed_parents = set()
 
531
        for version, parent_ids, expected_sha1, mpdiff in records:
 
532
            needed_parents.update(p for p in parent_ids
 
533
                                  if not mpvf.has_version(p))
 
534
        present_parents = set(self.get_parent_map(needed_parents).keys())
 
535
        for parent_id, lines in zip(present_parents,
 
536
                                 self._get_lf_split_line_list(present_parents)):
 
537
            mpvf.add_version(lines, parent_id, [])
 
538
        for (version, parent_ids, expected_sha1, mpdiff), lines in\
 
539
            zip(records, mpvf.get_line_list(versions)):
 
540
            if len(parent_ids) == 1:
 
541
                left_matching_blocks = list(mpdiff.get_matching_blocks(0,
 
542
                    mpvf.get_diff(parent_ids[0]).num_lines()))
 
543
            else:
 
544
                left_matching_blocks = None
 
545
            try:
 
546
                _, _, version_text = self.add_lines_with_ghosts(version,
 
547
                    parent_ids, lines, vf_parents,
 
548
                    left_matching_blocks=left_matching_blocks)
 
549
            except NotImplementedError:
 
550
                # The vf can't handle ghosts, so add lines normally, which will
 
551
                # (reasonably) fail if there are ghosts in the data.
 
552
                _, _, version_text = self.add_lines(version,
 
553
                    parent_ids, lines, vf_parents,
 
554
                    left_matching_blocks=left_matching_blocks)
 
555
            vf_parents[version] = version_text
 
556
        sha1s = self.get_sha1s(versions)
 
557
        for version, parent_ids, expected_sha1, mpdiff in records:
 
558
            if expected_sha1 != sha1s[version]:
 
559
                raise errors.VersionedFileInvalidChecksum(version)
 
560
 
260
561
    def get_text(self, version_id):
261
562
        """Return version contents as a text string.
262
563
 
282
583
        """
283
584
        raise NotImplementedError(self.get_lines)
284
585
 
285
 
    def get_ancestry(self, version_ids):
 
586
    def _get_lf_split_line_list(self, version_ids):
 
587
        return [StringIO(t).readlines() for t in self.get_texts(version_ids)]
 
588
 
 
589
    def get_ancestry(self, version_ids, topo_sorted=True):
286
590
        """Return a list of all ancestors of given version(s). This
287
591
        will not include the null revision.
288
592
 
 
593
        This list will not be topologically sorted if topo_sorted=False is
 
594
        passed.
 
595
 
289
596
        Must raise RevisionNotPresent if any of the given versions are
290
597
        not present in file history."""
291
598
        if isinstance(version_ids, basestring):
292
599
            version_ids = [version_ids]
293
600
        raise NotImplementedError(self.get_ancestry)
294
 
        
 
601
 
295
602
    def get_ancestry_with_ghosts(self, version_ids):
296
603
        """Return a list of all ancestors of given version(s). This
297
604
        will not include the null revision.
298
605
 
299
606
        Must raise RevisionNotPresent if any of the given versions are
300
607
        not present in file history.
301
 
        
 
608
 
302
609
        Ghosts that are known about will be included in ancestry list,
303
610
        but are not explicitly marked.
304
611
        """
305
612
        raise NotImplementedError(self.get_ancestry_with_ghosts)
306
 
        
307
 
    def get_graph(self, version_ids=None):
308
 
        """Return a graph from the versioned file. 
309
 
        
310
 
        Ghosts are not listed or referenced in the graph.
311
 
        :param version_ids: Versions to select.
312
 
                            None means retrieve all versions.
313
 
        """
314
 
        result = {}
315
 
        if version_ids is None:
316
 
            for version in self.versions():
317
 
                result[version] = self.get_parents(version)
318
 
        else:
319
 
            pending = set(version_ids)
320
 
            while pending:
321
 
                version = pending.pop()
322
 
                if version in result:
323
 
                    continue
324
 
                parents = self.get_parents(version)
325
 
                for parent in parents:
326
 
                    if parent in result:
327
 
                        continue
328
 
                    pending.add(parent)
329
 
                result[version] = parents
330
 
        return result
331
 
 
332
 
    def get_graph_with_ghosts(self):
333
 
        """Return a graph for the entire versioned file.
334
 
        
335
 
        Ghosts are referenced in parents list but are not
336
 
        explicitly listed.
337
 
        """
338
 
        raise NotImplementedError(self.get_graph_with_ghosts)
339
 
 
340
 
    @deprecated_method(zero_eight)
341
 
    def parent_names(self, version):
342
 
        """Return version names for parents of a version.
343
 
        
344
 
        See get_parents for the current api.
345
 
        """
346
 
        return self.get_parents(version)
347
 
 
348
 
    def get_parents(self, version_id):
349
 
        """Return version names for parents of a version.
350
 
 
351
 
        Must raise RevisionNotPresent if version is not present in
352
 
        file history.
353
 
        """
354
 
        raise NotImplementedError(self.get_parents)
 
613
 
 
614
    def get_parent_map(self, version_ids):
 
615
        """Get a map of the parents of version_ids.
 
616
 
 
617
        :param version_ids: The version ids to look up parents for.
 
618
        :return: A mapping from version id to parents.
 
619
        """
 
620
        raise NotImplementedError(self.get_parent_map)
355
621
 
356
622
    def get_parents_with_ghosts(self, version_id):
357
623
        """Return version names for parents of version_id.
362
628
        Ghosts that are known about will be included in the parent list,
363
629
        but are not explicitly marked.
364
630
        """
365
 
        raise NotImplementedError(self.get_parents_with_ghosts)
366
 
 
367
 
    def annotate_iter(self, version_id):
368
 
        """Yield list of (version-id, line) pairs for the specified
369
 
        version.
370
 
 
371
 
        Must raise RevisionNotPresent if any of the given versions are
372
 
        not present in file history.
373
 
        """
374
 
        raise NotImplementedError(self.annotate_iter)
 
631
        try:
 
632
            return list(self.get_parent_map([version_id])[version_id])
 
633
        except KeyError:
 
634
            raise errors.RevisionNotPresent(version_id, self)
375
635
 
376
636
    def annotate(self, version_id):
377
 
        return list(self.annotate_iter(version_id))
378
 
 
379
 
    def _apply_delta(self, lines, delta):
380
 
        """Apply delta to lines."""
381
 
        lines = list(lines)
382
 
        offset = 0
383
 
        for start, end, count, delta_lines in delta:
384
 
            lines[offset+start:offset+end] = delta_lines
385
 
            offset = offset + (start - end) + count
386
 
        return lines
387
 
 
388
 
    def join(self, other, pb=None, msg=None, version_ids=None,
389
 
             ignore_missing=False):
390
 
        """Integrate versions from other into this versioned file.
391
 
 
392
 
        If version_ids is None all versions from other should be
393
 
        incorporated into this versioned file.
394
 
 
395
 
        Must raise RevisionNotPresent if any of the specified versions
396
 
        are not present in the other files history unless ignore_missing
397
 
        is supplied when they are silently skipped.
 
637
        """Return a list of (version-id, line) tuples for version_id.
 
638
 
 
639
        :raise RevisionNotPresent: If the given version is
 
640
        not present in file history.
398
641
        """
399
 
        self._check_write_ok()
400
 
        return InterVersionedFile.get(other, self).join(
401
 
            pb,
402
 
            msg,
403
 
            version_ids,
404
 
            ignore_missing)
 
642
        raise NotImplementedError(self.annotate)
405
643
 
406
 
    def iter_lines_added_or_present_in_versions(self, version_ids=None, 
 
644
    def iter_lines_added_or_present_in_versions(self, version_ids=None,
407
645
                                                pb=None):
408
646
        """Iterate over the lines in the versioned file from version_ids.
409
647
 
410
 
        This may return lines from other versions, and does not return the
411
 
        specific version marker at this point. The api may be changed
412
 
        during development to include the version that the versioned file
413
 
        thinks is relevant, but given that such hints are just guesses,
414
 
        its better not to have it if we don't need it.
 
648
        This may return lines from other versions. Each item the returned
 
649
        iterator yields is a tuple of a line and a text version that that line
 
650
        is present in (not introduced in).
 
651
 
 
652
        Ordering of results is in whatever order is most suitable for the
 
653
        underlying storage format.
415
654
 
416
655
        If a progress bar is supplied, it may be used to indicate progress.
417
656
        The caller is responsible for cleaning up progress bars (because this
419
658
 
420
659
        NOTES: Lines are normalised: they will all have \n terminators.
421
660
               Lines are returned in arbitrary order.
 
661
 
 
662
        :return: An iterator over (line, version_id).
422
663
        """
423
664
        raise NotImplementedError(self.iter_lines_added_or_present_in_versions)
424
665
 
425
 
    def transaction_finished(self):
426
 
        """The transaction that this file was opened in has finished.
427
 
 
428
 
        This records self.finished = True and should cause all mutating
429
 
        operations to error.
430
 
        """
431
 
        self.finished = True
432
 
 
433
 
    @deprecated_method(zero_eight)
434
 
    def walk(self, version_ids=None):
435
 
        """Walk the versioned file as a weave-like structure, for
436
 
        versions relative to version_ids.  Yields sequence of (lineno,
437
 
        insert, deletes, text) for each relevant line.
438
 
 
439
 
        Must raise RevisionNotPresent if any of the specified versions
440
 
        are not present in the file history.
441
 
 
442
 
        :param version_ids: the version_ids to walk with respect to. If not
443
 
                            supplied the entire weave-like structure is walked.
444
 
 
445
 
        walk is deprecated in favour of iter_lines_added_or_present_in_versions
446
 
        """
447
 
        raise NotImplementedError(self.walk)
448
 
 
449
 
    @deprecated_method(zero_eight)
450
 
    def iter_names(self):
451
 
        """Walk the names list."""
452
 
        return iter(self.versions())
453
 
 
454
666
    def plan_merge(self, ver_a, ver_b):
455
667
        """Return pseudo-annotation indicating how the two versions merge.
456
668
 
467
679
        unchanged   Alive in both a and b (possibly created in both)
468
680
        new-a       Created in a
469
681
        new-b       Created in b
470
 
        ghost-a     Killed in a, unborn in b    
 
682
        ghost-a     Killed in a, unborn in b
471
683
        ghost-b     Killed in b, unborn in a
472
684
        irrelevant  Not in either revision
473
685
        """
474
686
        raise NotImplementedError(VersionedFile.plan_merge)
475
 
        
476
 
    def weave_merge(self, plan, a_marker=TextMerge.A_MARKER, 
 
687
 
 
688
    def weave_merge(self, plan, a_marker=TextMerge.A_MARKER,
477
689
                    b_marker=TextMerge.B_MARKER):
478
690
        return PlanWeaveMerge(plan, a_marker, b_marker).merge_lines()[0]
479
691
 
480
692
 
 
693
class RecordingVersionedFilesDecorator(object):
 
694
    """A minimal versioned files that records calls made on it.
 
695
 
 
696
    Only enough methods have been added to support tests using it to date.
 
697
 
 
698
    :ivar calls: A list of the calls made; can be reset at any time by
 
699
        assigning [] to it.
 
700
    """
 
701
 
 
702
    def __init__(self, backing_vf):
 
703
        """Create a RecordingVersionedFilesDecorator decorating backing_vf.
 
704
 
 
705
        :param backing_vf: The versioned file to answer all methods.
 
706
        """
 
707
        self._backing_vf = backing_vf
 
708
        self.calls = []
 
709
 
 
710
    def add_lines(self, key, parents, lines, parent_texts=None,
 
711
        left_matching_blocks=None, nostore_sha=None, random_id=False,
 
712
        check_content=True):
 
713
        self.calls.append(("add_lines", key, parents, lines, parent_texts,
 
714
            left_matching_blocks, nostore_sha, random_id, check_content))
 
715
        return self._backing_vf.add_lines(key, parents, lines, parent_texts,
 
716
            left_matching_blocks, nostore_sha, random_id, check_content)
 
717
 
 
718
    def check(self):
 
719
        self._backing_vf.check()
 
720
 
 
721
    def get_parent_map(self, keys):
 
722
        self.calls.append(("get_parent_map", copy(keys)))
 
723
        return self._backing_vf.get_parent_map(keys)
 
724
 
 
725
    def get_record_stream(self, keys, sort_order, include_delta_closure):
 
726
        self.calls.append(("get_record_stream", list(keys), sort_order,
 
727
            include_delta_closure))
 
728
        return self._backing_vf.get_record_stream(keys, sort_order,
 
729
            include_delta_closure)
 
730
 
 
731
    def get_sha1s(self, keys):
 
732
        self.calls.append(("get_sha1s", copy(keys)))
 
733
        return self._backing_vf.get_sha1s(keys)
 
734
 
 
735
    def iter_lines_added_or_present_in_keys(self, keys, pb=None):
 
736
        self.calls.append(("iter_lines_added_or_present_in_keys", copy(keys)))
 
737
        return self._backing_vf.iter_lines_added_or_present_in_keys(keys, pb=pb)
 
738
 
 
739
    def keys(self):
 
740
        self.calls.append(("keys",))
 
741
        return self._backing_vf.keys()
 
742
 
 
743
 
 
744
class OrderingVersionedFilesDecorator(RecordingVersionedFilesDecorator):
 
745
    """A VF that records calls, and returns keys in specific order.
 
746
 
 
747
    :ivar calls: A list of the calls made; can be reset at any time by
 
748
        assigning [] to it.
 
749
    """
 
750
 
 
751
    def __init__(self, backing_vf, key_priority):
 
752
        """Create a RecordingVersionedFilesDecorator decorating backing_vf.
 
753
 
 
754
        :param backing_vf: The versioned file to answer all methods.
 
755
        :param key_priority: A dictionary defining what order keys should be
 
756
            returned from an 'unordered' get_record_stream request.
 
757
            Keys with lower priority are returned first, keys not present in
 
758
            the map get an implicit priority of 0, and are returned in
 
759
            lexicographical order.
 
760
        """
 
761
        RecordingVersionedFilesDecorator.__init__(self, backing_vf)
 
762
        self._key_priority = key_priority
 
763
 
 
764
    def get_record_stream(self, keys, sort_order, include_delta_closure):
 
765
        self.calls.append(("get_record_stream", list(keys), sort_order,
 
766
            include_delta_closure))
 
767
        if sort_order == 'unordered':
 
768
            def sort_key(key):
 
769
                return (self._key_priority.get(key, 0), key)
 
770
            # Use a defined order by asking for the keys one-by-one from the
 
771
            # backing_vf
 
772
            for key in sorted(keys, key=sort_key):
 
773
                for record in self._backing_vf.get_record_stream([key],
 
774
                                'unordered', include_delta_closure):
 
775
                    yield record
 
776
        else:
 
777
            for record in self._backing_vf.get_record_stream(keys, sort_order,
 
778
                            include_delta_closure):
 
779
                yield record
 
780
 
 
781
 
 
782
class KeyMapper(object):
 
783
    """KeyMappers map between keys and underlying partitioned storage."""
 
784
 
 
785
    def map(self, key):
 
786
        """Map key to an underlying storage identifier.
 
787
 
 
788
        :param key: A key tuple e.g. ('file-id', 'revision-id').
 
789
        :return: An underlying storage identifier, specific to the partitioning
 
790
            mechanism.
 
791
        """
 
792
        raise NotImplementedError(self.map)
 
793
 
 
794
    def unmap(self, partition_id):
 
795
        """Map a partitioned storage id back to a key prefix.
 
796
 
 
797
        :param partition_id: The underlying partition id.
 
798
        :return: As much of a key (or prefix) as is derivable from the partition
 
799
            id.
 
800
        """
 
801
        raise NotImplementedError(self.unmap)
 
802
 
 
803
 
 
804
class ConstantMapper(KeyMapper):
 
805
    """A key mapper that maps to a constant result."""
 
806
 
 
807
    def __init__(self, result):
 
808
        """Create a ConstantMapper which will return result for all maps."""
 
809
        self._result = result
 
810
 
 
811
    def map(self, key):
 
812
        """See KeyMapper.map()."""
 
813
        return self._result
 
814
 
 
815
 
 
816
class URLEscapeMapper(KeyMapper):
 
817
    """Base class for use with transport backed storage.
 
818
 
 
819
    This provides a map and unmap wrapper that respectively url escape and
 
820
    unescape their outputs and inputs.
 
821
    """
 
822
 
 
823
    def map(self, key):
 
824
        """See KeyMapper.map()."""
 
825
        return urlutils.quote(self._map(key))
 
826
 
 
827
    def unmap(self, partition_id):
 
828
        """See KeyMapper.unmap()."""
 
829
        return self._unmap(urlutils.unquote(partition_id))
 
830
 
 
831
 
 
832
class PrefixMapper(URLEscapeMapper):
 
833
    """A key mapper that extracts the first component of a key.
 
834
 
 
835
    This mapper is for use with a transport based backend.
 
836
    """
 
837
 
 
838
    def _map(self, key):
 
839
        """See KeyMapper.map()."""
 
840
        return key[0]
 
841
 
 
842
    def _unmap(self, partition_id):
 
843
        """See KeyMapper.unmap()."""
 
844
        return (partition_id,)
 
845
 
 
846
 
 
847
class HashPrefixMapper(URLEscapeMapper):
 
848
    """A key mapper that combines the first component of a key with a hash.
 
849
 
 
850
    This mapper is for use with a transport based backend.
 
851
    """
 
852
 
 
853
    def _map(self, key):
 
854
        """See KeyMapper.map()."""
 
855
        prefix = self._escape(key[0])
 
856
        return "%02x/%s" % (adler32(prefix) & 0xff, prefix)
 
857
 
 
858
    def _escape(self, prefix):
 
859
        """No escaping needed here."""
 
860
        return prefix
 
861
 
 
862
    def _unmap(self, partition_id):
 
863
        """See KeyMapper.unmap()."""
 
864
        return (self._unescape(osutils.basename(partition_id)),)
 
865
 
 
866
    def _unescape(self, basename):
 
867
        """No unescaping needed for HashPrefixMapper."""
 
868
        return basename
 
869
 
 
870
 
 
871
class HashEscapedPrefixMapper(HashPrefixMapper):
 
872
    """Combines the escaped first component of a key with a hash.
 
873
 
 
874
    This mapper is for use with a transport based backend.
 
875
    """
 
876
 
 
877
    _safe = "abcdefghijklmnopqrstuvwxyz0123456789-_@,."
 
878
 
 
879
    def _escape(self, prefix):
 
880
        """Turn a key element into a filesystem safe string.
 
881
 
 
882
        This is similar to a plain urlutils.quote, except
 
883
        it uses specific safe characters, so that it doesn't
 
884
        have to translate a lot of valid file ids.
 
885
        """
 
886
        # @ does not get escaped. This is because it is a valid
 
887
        # filesystem character we use all the time, and it looks
 
888
        # a lot better than seeing %40 all the time.
 
889
        r = [((c in self._safe) and c or ('%%%02x' % ord(c)))
 
890
             for c in prefix]
 
891
        return ''.join(r)
 
892
 
 
893
    def _unescape(self, basename):
 
894
        """Escaped names are easily unescaped by urlutils."""
 
895
        return urlutils.unquote(basename)
 
896
 
 
897
 
 
898
def make_versioned_files_factory(versioned_file_factory, mapper):
 
899
    """Create a ThunkedVersionedFiles factory.
 
900
 
 
901
    This will create a callable which when called creates a
 
902
    ThunkedVersionedFiles on a transport, using mapper to access individual
 
903
    versioned files, and versioned_file_factory to create each individual file.
 
904
    """
 
905
    def factory(transport):
 
906
        return ThunkedVersionedFiles(transport, versioned_file_factory, mapper,
 
907
            lambda:True)
 
908
    return factory
 
909
 
 
910
 
 
911
class VersionedFiles(object):
 
912
    """Storage for many versioned files.
 
913
 
 
914
    This object allows a single keyspace for accessing the history graph and
 
915
    contents of named bytestrings.
 
916
 
 
917
    Currently no implementation allows the graph of different key prefixes to
 
918
    intersect, but the API does allow such implementations in the future.
 
919
 
 
920
    The keyspace is expressed via simple tuples. Any instance of VersionedFiles
 
921
    may have a different length key-size, but that size will be constant for
 
922
    all texts added to or retrieved from it. For instance, bzrlib uses
 
923
    instances with a key-size of 2 for storing user files in a repository, with
 
924
    the first element the fileid, and the second the version of that file.
 
925
 
 
926
    The use of tuples allows a single code base to support several different
 
927
    uses with only the mapping logic changing from instance to instance.
 
928
 
 
929
    :ivar _immediate_fallback_vfs: For subclasses that support stacking,
 
930
        this is a list of other VersionedFiles immediately underneath this
 
931
        one.  They may in turn each have further fallbacks.
 
932
    """
 
933
 
 
934
    def add_lines(self, key, parents, lines, parent_texts=None,
 
935
        left_matching_blocks=None, nostore_sha=None, random_id=False,
 
936
        check_content=True):
 
937
        """Add a text to the store.
 
938
 
 
939
        :param key: The key tuple of the text to add. If the last element is
 
940
            None, a CHK string will be generated during the addition.
 
941
        :param parents: The parents key tuples of the text to add.
 
942
        :param lines: A list of lines. Each line must be a bytestring. And all
 
943
            of them except the last must be terminated with \n and contain no
 
944
            other \n's. The last line may either contain no \n's or a single
 
945
            terminating \n. If the lines list does meet this constraint the add
 
946
            routine may error or may succeed - but you will be unable to read
 
947
            the data back accurately. (Checking the lines have been split
 
948
            correctly is expensive and extremely unlikely to catch bugs so it
 
949
            is not done at runtime unless check_content is True.)
 
950
        :param parent_texts: An optional dictionary containing the opaque
 
951
            representations of some or all of the parents of version_id to
 
952
            allow delta optimisations.  VERY IMPORTANT: the texts must be those
 
953
            returned by add_lines or data corruption can be caused.
 
954
        :param left_matching_blocks: a hint about which areas are common
 
955
            between the text and its left-hand-parent.  The format is
 
956
            the SequenceMatcher.get_matching_blocks format.
 
957
        :param nostore_sha: Raise ExistingContent and do not add the lines to
 
958
            the versioned file if the digest of the lines matches this.
 
959
        :param random_id: If True a random id has been selected rather than
 
960
            an id determined by some deterministic process such as a converter
 
961
            from a foreign VCS. When True the backend may choose not to check
 
962
            for uniqueness of the resulting key within the versioned file, so
 
963
            this should only be done when the result is expected to be unique
 
964
            anyway.
 
965
        :param check_content: If True, the lines supplied are verified to be
 
966
            bytestrings that are correctly formed lines.
 
967
        :return: The text sha1, the number of bytes in the text, and an opaque
 
968
                 representation of the inserted version which can be provided
 
969
                 back to future add_lines calls in the parent_texts dictionary.
 
970
        """
 
971
        raise NotImplementedError(self.add_lines)
 
972
 
 
973
    def _add_text(self, key, parents, text, nostore_sha=None, random_id=False):
 
974
        """Add a text to the store.
 
975
 
 
976
        This is a private function for use by VersionedFileCommitBuilder.
 
977
 
 
978
        :param key: The key tuple of the text to add. If the last element is
 
979
            None, a CHK string will be generated during the addition.
 
980
        :param parents: The parents key tuples of the text to add.
 
981
        :param text: A string containing the text to be committed.
 
982
        :param nostore_sha: Raise ExistingContent and do not add the lines to
 
983
            the versioned file if the digest of the lines matches this.
 
984
        :param random_id: If True a random id has been selected rather than
 
985
            an id determined by some deterministic process such as a converter
 
986
            from a foreign VCS. When True the backend may choose not to check
 
987
            for uniqueness of the resulting key within the versioned file, so
 
988
            this should only be done when the result is expected to be unique
 
989
            anyway.
 
990
        :param check_content: If True, the lines supplied are verified to be
 
991
            bytestrings that are correctly formed lines.
 
992
        :return: The text sha1, the number of bytes in the text, and an opaque
 
993
                 representation of the inserted version which can be provided
 
994
                 back to future _add_text calls in the parent_texts dictionary.
 
995
        """
 
996
        # The default implementation just thunks over to .add_lines(),
 
997
        # inefficient, but it works.
 
998
        return self.add_lines(key, parents, osutils.split_lines(text),
 
999
                              nostore_sha=nostore_sha,
 
1000
                              random_id=random_id,
 
1001
                              check_content=True)
 
1002
 
 
1003
    def add_mpdiffs(self, records):
 
1004
        """Add mpdiffs to this VersionedFile.
 
1005
 
 
1006
        Records should be iterables of version, parents, expected_sha1,
 
1007
        mpdiff. mpdiff should be a MultiParent instance.
 
1008
        """
 
1009
        vf_parents = {}
 
1010
        mpvf = multiparent.MultiMemoryVersionedFile()
 
1011
        versions = []
 
1012
        for version, parent_ids, expected_sha1, mpdiff in records:
 
1013
            versions.append(version)
 
1014
            mpvf.add_diff(mpdiff, version, parent_ids)
 
1015
        needed_parents = set()
 
1016
        for version, parent_ids, expected_sha1, mpdiff in records:
 
1017
            needed_parents.update(p for p in parent_ids
 
1018
                                  if not mpvf.has_version(p))
 
1019
        # It seems likely that adding all the present parents as fulltexts can
 
1020
        # easily exhaust memory.
 
1021
        chunks_to_lines = osutils.chunks_to_lines
 
1022
        for record in self.get_record_stream(needed_parents, 'unordered',
 
1023
            True):
 
1024
            if record.storage_kind == 'absent':
 
1025
                continue
 
1026
            mpvf.add_version(chunks_to_lines(record.get_bytes_as('chunked')),
 
1027
                record.key, [])
 
1028
        for (key, parent_keys, expected_sha1, mpdiff), lines in\
 
1029
            zip(records, mpvf.get_line_list(versions)):
 
1030
            if len(parent_keys) == 1:
 
1031
                left_matching_blocks = list(mpdiff.get_matching_blocks(0,
 
1032
                    mpvf.get_diff(parent_keys[0]).num_lines()))
 
1033
            else:
 
1034
                left_matching_blocks = None
 
1035
            version_sha1, _, version_text = self.add_lines(key,
 
1036
                parent_keys, lines, vf_parents,
 
1037
                left_matching_blocks=left_matching_blocks)
 
1038
            if version_sha1 != expected_sha1:
 
1039
                raise errors.VersionedFileInvalidChecksum(version)
 
1040
            vf_parents[key] = version_text
 
1041
 
 
1042
    def annotate(self, key):
 
1043
        """Return a list of (version-key, line) tuples for the text of key.
 
1044
 
 
1045
        :raise RevisionNotPresent: If the key is not present.
 
1046
        """
 
1047
        raise NotImplementedError(self.annotate)
 
1048
 
 
1049
    def check(self, progress_bar=None):
 
1050
        """Check this object for integrity.
 
1051
        
 
1052
        :param progress_bar: A progress bar to output as the check progresses.
 
1053
        :param keys: Specific keys within the VersionedFiles to check. When
 
1054
            this parameter is not None, check() becomes a generator as per
 
1055
            get_record_stream. The difference to get_record_stream is that
 
1056
            more or deeper checks will be performed.
 
1057
        :return: None, or if keys was supplied a generator as per
 
1058
            get_record_stream.
 
1059
        """
 
1060
        raise NotImplementedError(self.check)
 
1061
 
 
1062
    @staticmethod
 
1063
    def check_not_reserved_id(version_id):
 
1064
        revision.check_not_reserved_id(version_id)
 
1065
 
 
1066
    def clear_cache(self):
 
1067
        """Clear whatever caches this VersionedFile holds.
 
1068
 
 
1069
        This is generally called after an operation has been performed, when we
 
1070
        don't expect to be using this versioned file again soon.
 
1071
        """
 
1072
 
 
1073
    def _check_lines_not_unicode(self, lines):
 
1074
        """Check that lines being added to a versioned file are not unicode."""
 
1075
        for line in lines:
 
1076
            if line.__class__ is not str:
 
1077
                raise errors.BzrBadParameterUnicode("lines")
 
1078
 
 
1079
    def _check_lines_are_lines(self, lines):
 
1080
        """Check that the lines really are full lines without inline EOL."""
 
1081
        for line in lines:
 
1082
            if '\n' in line[:-1]:
 
1083
                raise errors.BzrBadParameterContainsNewline("lines")
 
1084
 
 
1085
    def get_known_graph_ancestry(self, keys):
 
1086
        """Get a KnownGraph instance with the ancestry of keys."""
 
1087
        # most basic implementation is a loop around get_parent_map
 
1088
        pending = set(keys)
 
1089
        parent_map = {}
 
1090
        while pending:
 
1091
            this_parent_map = self.get_parent_map(pending)
 
1092
            parent_map.update(this_parent_map)
 
1093
            pending = set()
 
1094
            map(pending.update, this_parent_map.itervalues())
 
1095
            pending = pending.difference(parent_map)
 
1096
        kg = _mod_graph.KnownGraph(parent_map)
 
1097
        return kg
 
1098
 
 
1099
    def get_parent_map(self, keys):
 
1100
        """Get a map of the parents of keys.
 
1101
 
 
1102
        :param keys: The keys to look up parents for.
 
1103
        :return: A mapping from keys to parents. Absent keys are absent from
 
1104
            the mapping.
 
1105
        """
 
1106
        raise NotImplementedError(self.get_parent_map)
 
1107
 
 
1108
    def get_record_stream(self, keys, ordering, include_delta_closure):
 
1109
        """Get a stream of records for keys.
 
1110
 
 
1111
        :param keys: The keys to include.
 
1112
        :param ordering: Either 'unordered' or 'topological'. A topologically
 
1113
            sorted stream has compression parents strictly before their
 
1114
            children.
 
1115
        :param include_delta_closure: If True then the closure across any
 
1116
            compression parents will be included (in the opaque data).
 
1117
        :return: An iterator of ContentFactory objects, each of which is only
 
1118
            valid until the iterator is advanced.
 
1119
        """
 
1120
        raise NotImplementedError(self.get_record_stream)
 
1121
 
 
1122
    def get_sha1s(self, keys):
 
1123
        """Get the sha1's of the texts for the given keys.
 
1124
 
 
1125
        :param keys: The names of the keys to lookup
 
1126
        :return: a dict from key to sha1 digest. Keys of texts which are not
 
1127
            present in the store are not present in the returned
 
1128
            dictionary.
 
1129
        """
 
1130
        raise NotImplementedError(self.get_sha1s)
 
1131
 
 
1132
    has_key = index._has_key_from_parent_map
 
1133
 
 
1134
    def get_missing_compression_parent_keys(self):
 
1135
        """Return an iterable of keys of missing compression parents.
 
1136
 
 
1137
        Check this after calling insert_record_stream to find out if there are
 
1138
        any missing compression parents.  If there are, the records that
 
1139
        depend on them are not able to be inserted safely. The precise
 
1140
        behaviour depends on the concrete VersionedFiles class in use.
 
1141
 
 
1142
        Classes that do not support this will raise NotImplementedError.
 
1143
        """
 
1144
        raise NotImplementedError(self.get_missing_compression_parent_keys)
 
1145
 
 
1146
    def insert_record_stream(self, stream):
 
1147
        """Insert a record stream into this container.
 
1148
 
 
1149
        :param stream: A stream of records to insert.
 
1150
        :return: None
 
1151
        :seealso VersionedFile.get_record_stream:
 
1152
        """
 
1153
        raise NotImplementedError
 
1154
 
 
1155
    def iter_lines_added_or_present_in_keys(self, keys, pb=None):
 
1156
        """Iterate over the lines in the versioned files from keys.
 
1157
 
 
1158
        This may return lines from other keys. Each item the returned
 
1159
        iterator yields is a tuple of a line and a text version that that line
 
1160
        is present in (not introduced in).
 
1161
 
 
1162
        Ordering of results is in whatever order is most suitable for the
 
1163
        underlying storage format.
 
1164
 
 
1165
        If a progress bar is supplied, it may be used to indicate progress.
 
1166
        The caller is responsible for cleaning up progress bars (because this
 
1167
        is an iterator).
 
1168
 
 
1169
        NOTES:
 
1170
         * Lines are normalised by the underlying store: they will all have \n
 
1171
           terminators.
 
1172
         * Lines are returned in arbitrary order.
 
1173
 
 
1174
        :return: An iterator over (line, key).
 
1175
        """
 
1176
        raise NotImplementedError(self.iter_lines_added_or_present_in_keys)
 
1177
 
 
1178
    def keys(self):
 
1179
        """Return a iterable of the keys for all the contained texts."""
 
1180
        raise NotImplementedError(self.keys)
 
1181
 
 
1182
    def make_mpdiffs(self, keys):
 
1183
        """Create multiparent diffs for specified keys."""
 
1184
        generator = _MPDiffGenerator(self, keys)
 
1185
        return generator.compute_diffs()
 
1186
 
 
1187
    def get_annotator(self):
 
1188
        return annotate.Annotator(self)
 
1189
 
 
1190
    missing_keys = index._missing_keys_from_parent_map
 
1191
 
 
1192
    def _extract_blocks(self, version_id, source, target):
 
1193
        return None
 
1194
 
 
1195
    def _transitive_fallbacks(self):
 
1196
        """Return the whole stack of fallback versionedfiles.
 
1197
 
 
1198
        This VersionedFiles may have a list of fallbacks, but it doesn't
 
1199
        necessarily know about the whole stack going down, and it can't know
 
1200
        at open time because they may change after the objects are opened.
 
1201
        """
 
1202
        all_fallbacks = []
 
1203
        for a_vfs in self._immediate_fallback_vfs:
 
1204
            all_fallbacks.append(a_vfs)
 
1205
            all_fallbacks.extend(a_vfs._transitive_fallbacks())
 
1206
        return all_fallbacks
 
1207
 
 
1208
 
 
1209
class ThunkedVersionedFiles(VersionedFiles):
 
1210
    """Storage for many versioned files thunked onto a 'VersionedFile' class.
 
1211
 
 
1212
    This object allows a single keyspace for accessing the history graph and
 
1213
    contents of named bytestrings.
 
1214
 
 
1215
    Currently no implementation allows the graph of different key prefixes to
 
1216
    intersect, but the API does allow such implementations in the future.
 
1217
    """
 
1218
 
 
1219
    def __init__(self, transport, file_factory, mapper, is_locked):
 
1220
        """Create a ThunkedVersionedFiles."""
 
1221
        self._transport = transport
 
1222
        self._file_factory = file_factory
 
1223
        self._mapper = mapper
 
1224
        self._is_locked = is_locked
 
1225
 
 
1226
    def add_lines(self, key, parents, lines, parent_texts=None,
 
1227
        left_matching_blocks=None, nostore_sha=None, random_id=False,
 
1228
        check_content=True):
 
1229
        """See VersionedFiles.add_lines()."""
 
1230
        path = self._mapper.map(key)
 
1231
        version_id = key[-1]
 
1232
        parents = [parent[-1] for parent in parents]
 
1233
        vf = self._get_vf(path)
 
1234
        try:
 
1235
            try:
 
1236
                return vf.add_lines_with_ghosts(version_id, parents, lines,
 
1237
                    parent_texts=parent_texts,
 
1238
                    left_matching_blocks=left_matching_blocks,
 
1239
                    nostore_sha=nostore_sha, random_id=random_id,
 
1240
                    check_content=check_content)
 
1241
            except NotImplementedError:
 
1242
                return vf.add_lines(version_id, parents, lines,
 
1243
                    parent_texts=parent_texts,
 
1244
                    left_matching_blocks=left_matching_blocks,
 
1245
                    nostore_sha=nostore_sha, random_id=random_id,
 
1246
                    check_content=check_content)
 
1247
        except errors.NoSuchFile:
 
1248
            # parent directory may be missing, try again.
 
1249
            self._transport.mkdir(osutils.dirname(path))
 
1250
            try:
 
1251
                return vf.add_lines_with_ghosts(version_id, parents, lines,
 
1252
                    parent_texts=parent_texts,
 
1253
                    left_matching_blocks=left_matching_blocks,
 
1254
                    nostore_sha=nostore_sha, random_id=random_id,
 
1255
                    check_content=check_content)
 
1256
            except NotImplementedError:
 
1257
                return vf.add_lines(version_id, parents, lines,
 
1258
                    parent_texts=parent_texts,
 
1259
                    left_matching_blocks=left_matching_blocks,
 
1260
                    nostore_sha=nostore_sha, random_id=random_id,
 
1261
                    check_content=check_content)
 
1262
 
 
1263
    def annotate(self, key):
 
1264
        """Return a list of (version-key, line) tuples for the text of key.
 
1265
 
 
1266
        :raise RevisionNotPresent: If the key is not present.
 
1267
        """
 
1268
        prefix = key[:-1]
 
1269
        path = self._mapper.map(prefix)
 
1270
        vf = self._get_vf(path)
 
1271
        origins = vf.annotate(key[-1])
 
1272
        result = []
 
1273
        for origin, line in origins:
 
1274
            result.append((prefix + (origin,), line))
 
1275
        return result
 
1276
 
 
1277
    def check(self, progress_bar=None, keys=None):
 
1278
        """See VersionedFiles.check()."""
 
1279
        # XXX: This is over-enthusiastic but as we only thunk for Weaves today
 
1280
        # this is tolerable. Ideally we'd pass keys down to check() and 
 
1281
        # have the older VersiondFile interface updated too.
 
1282
        for prefix, vf in self._iter_all_components():
 
1283
            vf.check()
 
1284
        if keys is not None:
 
1285
            return self.get_record_stream(keys, 'unordered', True)
 
1286
 
 
1287
    def get_parent_map(self, keys):
 
1288
        """Get a map of the parents of keys.
 
1289
 
 
1290
        :param keys: The keys to look up parents for.
 
1291
        :return: A mapping from keys to parents. Absent keys are absent from
 
1292
            the mapping.
 
1293
        """
 
1294
        prefixes = self._partition_keys(keys)
 
1295
        result = {}
 
1296
        for prefix, suffixes in prefixes.items():
 
1297
            path = self._mapper.map(prefix)
 
1298
            vf = self._get_vf(path)
 
1299
            parent_map = vf.get_parent_map(suffixes)
 
1300
            for key, parents in parent_map.items():
 
1301
                result[prefix + (key,)] = tuple(
 
1302
                    prefix + (parent,) for parent in parents)
 
1303
        return result
 
1304
 
 
1305
    def _get_vf(self, path):
 
1306
        if not self._is_locked():
 
1307
            raise errors.ObjectNotLocked(self)
 
1308
        return self._file_factory(path, self._transport, create=True,
 
1309
            get_scope=lambda:None)
 
1310
 
 
1311
    def _partition_keys(self, keys):
 
1312
        """Turn keys into a dict of prefix:suffix_list."""
 
1313
        result = {}
 
1314
        for key in keys:
 
1315
            prefix_keys = result.setdefault(key[:-1], [])
 
1316
            prefix_keys.append(key[-1])
 
1317
        return result
 
1318
 
 
1319
    def _get_all_prefixes(self):
 
1320
        # Identify all key prefixes.
 
1321
        # XXX: A bit hacky, needs polish.
 
1322
        if type(self._mapper) == ConstantMapper:
 
1323
            paths = [self._mapper.map(())]
 
1324
            prefixes = [()]
 
1325
        else:
 
1326
            relpaths = set()
 
1327
            for quoted_relpath in self._transport.iter_files_recursive():
 
1328
                path, ext = os.path.splitext(quoted_relpath)
 
1329
                relpaths.add(path)
 
1330
            paths = list(relpaths)
 
1331
            prefixes = [self._mapper.unmap(path) for path in paths]
 
1332
        return zip(paths, prefixes)
 
1333
 
 
1334
    def get_record_stream(self, keys, ordering, include_delta_closure):
 
1335
        """See VersionedFiles.get_record_stream()."""
 
1336
        # Ordering will be taken care of by each partitioned store; group keys
 
1337
        # by partition.
 
1338
        keys = sorted(keys)
 
1339
        for prefix, suffixes, vf in self._iter_keys_vf(keys):
 
1340
            suffixes = [(suffix,) for suffix in suffixes]
 
1341
            for record in vf.get_record_stream(suffixes, ordering,
 
1342
                include_delta_closure):
 
1343
                if record.parents is not None:
 
1344
                    record.parents = tuple(
 
1345
                        prefix + parent for parent in record.parents)
 
1346
                record.key = prefix + record.key
 
1347
                yield record
 
1348
 
 
1349
    def _iter_keys_vf(self, keys):
 
1350
        prefixes = self._partition_keys(keys)
 
1351
        sha1s = {}
 
1352
        for prefix, suffixes in prefixes.items():
 
1353
            path = self._mapper.map(prefix)
 
1354
            vf = self._get_vf(path)
 
1355
            yield prefix, suffixes, vf
 
1356
 
 
1357
    def get_sha1s(self, keys):
 
1358
        """See VersionedFiles.get_sha1s()."""
 
1359
        sha1s = {}
 
1360
        for prefix,suffixes, vf in self._iter_keys_vf(keys):
 
1361
            vf_sha1s = vf.get_sha1s(suffixes)
 
1362
            for suffix, sha1 in vf_sha1s.iteritems():
 
1363
                sha1s[prefix + (suffix,)] = sha1
 
1364
        return sha1s
 
1365
 
 
1366
    def insert_record_stream(self, stream):
 
1367
        """Insert a record stream into this container.
 
1368
 
 
1369
        :param stream: A stream of records to insert.
 
1370
        :return: None
 
1371
        :seealso VersionedFile.get_record_stream:
 
1372
        """
 
1373
        for record in stream:
 
1374
            prefix = record.key[:-1]
 
1375
            key = record.key[-1:]
 
1376
            if record.parents is not None:
 
1377
                parents = [parent[-1:] for parent in record.parents]
 
1378
            else:
 
1379
                parents = None
 
1380
            thunk_record = AdapterFactory(key, parents, record)
 
1381
            path = self._mapper.map(prefix)
 
1382
            # Note that this parses the file many times; we can do better but
 
1383
            # as this only impacts weaves in terms of performance, it is
 
1384
            # tolerable.
 
1385
            vf = self._get_vf(path)
 
1386
            vf.insert_record_stream([thunk_record])
 
1387
 
 
1388
    def iter_lines_added_or_present_in_keys(self, keys, pb=None):
 
1389
        """Iterate over the lines in the versioned files from keys.
 
1390
 
 
1391
        This may return lines from other keys. Each item the returned
 
1392
        iterator yields is a tuple of a line and a text version that that line
 
1393
        is present in (not introduced in).
 
1394
 
 
1395
        Ordering of results is in whatever order is most suitable for the
 
1396
        underlying storage format.
 
1397
 
 
1398
        If a progress bar is supplied, it may be used to indicate progress.
 
1399
        The caller is responsible for cleaning up progress bars (because this
 
1400
        is an iterator).
 
1401
 
 
1402
        NOTES:
 
1403
         * Lines are normalised by the underlying store: they will all have \n
 
1404
           terminators.
 
1405
         * Lines are returned in arbitrary order.
 
1406
 
 
1407
        :return: An iterator over (line, key).
 
1408
        """
 
1409
        for prefix, suffixes, vf in self._iter_keys_vf(keys):
 
1410
            for line, version in vf.iter_lines_added_or_present_in_versions(suffixes):
 
1411
                yield line, prefix + (version,)
 
1412
 
 
1413
    def _iter_all_components(self):
 
1414
        for path, prefix in self._get_all_prefixes():
 
1415
            yield prefix, self._get_vf(path)
 
1416
 
 
1417
    def keys(self):
 
1418
        """See VersionedFiles.keys()."""
 
1419
        result = set()
 
1420
        for prefix, vf in self._iter_all_components():
 
1421
            for suffix in vf.versions():
 
1422
                result.add(prefix + (suffix,))
 
1423
        return result
 
1424
 
 
1425
 
 
1426
class VersionedFilesWithFallbacks(VersionedFiles):
 
1427
 
 
1428
    def without_fallbacks(self):
 
1429
        """Return a clone of this object without any fallbacks configured."""
 
1430
        raise NotImplementedError(self.without_fallbacks)
 
1431
 
 
1432
    def add_fallback_versioned_files(self, a_versioned_files):
 
1433
        """Add a source of texts for texts not present in this knit.
 
1434
 
 
1435
        :param a_versioned_files: A VersionedFiles object.
 
1436
        """
 
1437
        raise NotImplementedError(self.add_fallback_versioned_files)
 
1438
 
 
1439
    def get_known_graph_ancestry(self, keys):
 
1440
        """Get a KnownGraph instance with the ancestry of keys."""
 
1441
        parent_map, missing_keys = self._index.find_ancestry(keys)
 
1442
        for fallback in self._transitive_fallbacks():
 
1443
            if not missing_keys:
 
1444
                break
 
1445
            (f_parent_map, f_missing_keys) = fallback._index.find_ancestry(
 
1446
                                                missing_keys)
 
1447
            parent_map.update(f_parent_map)
 
1448
            missing_keys = f_missing_keys
 
1449
        kg = _mod_graph.KnownGraph(parent_map)
 
1450
        return kg
 
1451
 
 
1452
 
 
1453
class _PlanMergeVersionedFile(VersionedFiles):
 
1454
    """A VersionedFile for uncommitted and committed texts.
 
1455
 
 
1456
    It is intended to allow merges to be planned with working tree texts.
 
1457
    It implements only the small part of the VersionedFiles interface used by
 
1458
    PlanMerge.  It falls back to multiple versionedfiles for data not stored in
 
1459
    _PlanMergeVersionedFile itself.
 
1460
 
 
1461
    :ivar: fallback_versionedfiles a list of VersionedFiles objects that can be
 
1462
        queried for missing texts.
 
1463
    """
 
1464
 
 
1465
    def __init__(self, file_id):
 
1466
        """Create a _PlanMergeVersionedFile.
 
1467
 
 
1468
        :param file_id: Used with _PlanMerge code which is not yet fully
 
1469
            tuple-keyspace aware.
 
1470
        """
 
1471
        self._file_id = file_id
 
1472
        # fallback locations
 
1473
        self.fallback_versionedfiles = []
 
1474
        # Parents for locally held keys.
 
1475
        self._parents = {}
 
1476
        # line data for locally held keys.
 
1477
        self._lines = {}
 
1478
        # key lookup providers
 
1479
        self._providers = [_mod_graph.DictParentsProvider(self._parents)]
 
1480
 
 
1481
    def plan_merge(self, ver_a, ver_b, base=None):
 
1482
        """See VersionedFile.plan_merge"""
 
1483
        from bzrlib.merge import _PlanMerge
 
1484
        if base is None:
 
1485
            return _PlanMerge(ver_a, ver_b, self, (self._file_id,)).plan_merge()
 
1486
        old_plan = list(_PlanMerge(ver_a, base, self, (self._file_id,)).plan_merge())
 
1487
        new_plan = list(_PlanMerge(ver_a, ver_b, self, (self._file_id,)).plan_merge())
 
1488
        return _PlanMerge._subtract_plans(old_plan, new_plan)
 
1489
 
 
1490
    def plan_lca_merge(self, ver_a, ver_b, base=None):
 
1491
        from bzrlib.merge import _PlanLCAMerge
 
1492
        graph = _mod_graph.Graph(self)
 
1493
        new_plan = _PlanLCAMerge(ver_a, ver_b, self, (self._file_id,), graph).plan_merge()
 
1494
        if base is None:
 
1495
            return new_plan
 
1496
        old_plan = _PlanLCAMerge(ver_a, base, self, (self._file_id,), graph).plan_merge()
 
1497
        return _PlanLCAMerge._subtract_plans(list(old_plan), list(new_plan))
 
1498
 
 
1499
    def add_lines(self, key, parents, lines):
 
1500
        """See VersionedFiles.add_lines
 
1501
 
 
1502
        Lines are added locally, not to fallback versionedfiles.  Also, ghosts
 
1503
        are permitted.  Only reserved ids are permitted.
 
1504
        """
 
1505
        if type(key) is not tuple:
 
1506
            raise TypeError(key)
 
1507
        if not revision.is_reserved_id(key[-1]):
 
1508
            raise ValueError('Only reserved ids may be used')
 
1509
        if parents is None:
 
1510
            raise ValueError('Parents may not be None')
 
1511
        if lines is None:
 
1512
            raise ValueError('Lines may not be None')
 
1513
        self._parents[key] = tuple(parents)
 
1514
        self._lines[key] = lines
 
1515
 
 
1516
    def get_record_stream(self, keys, ordering, include_delta_closure):
 
1517
        pending = set(keys)
 
1518
        for key in keys:
 
1519
            if key in self._lines:
 
1520
                lines = self._lines[key]
 
1521
                parents = self._parents[key]
 
1522
                pending.remove(key)
 
1523
                yield ChunkedContentFactory(key, parents, None, lines)
 
1524
        for versionedfile in self.fallback_versionedfiles:
 
1525
            for record in versionedfile.get_record_stream(
 
1526
                pending, 'unordered', True):
 
1527
                if record.storage_kind == 'absent':
 
1528
                    continue
 
1529
                else:
 
1530
                    pending.remove(record.key)
 
1531
                    yield record
 
1532
            if not pending:
 
1533
                return
 
1534
        # report absent entries
 
1535
        for key in pending:
 
1536
            yield AbsentContentFactory(key)
 
1537
 
 
1538
    def get_parent_map(self, keys):
 
1539
        """See VersionedFiles.get_parent_map"""
 
1540
        # We create a new provider because a fallback may have been added.
 
1541
        # If we make fallbacks private we can update a stack list and avoid
 
1542
        # object creation thrashing.
 
1543
        keys = set(keys)
 
1544
        result = {}
 
1545
        if revision.NULL_REVISION in keys:
 
1546
            keys.remove(revision.NULL_REVISION)
 
1547
            result[revision.NULL_REVISION] = ()
 
1548
        self._providers = self._providers[:1] + self.fallback_versionedfiles
 
1549
        result.update(
 
1550
            _mod_graph.StackedParentsProvider(
 
1551
                self._providers).get_parent_map(keys))
 
1552
        for key, parents in result.iteritems():
 
1553
            if parents == ():
 
1554
                result[key] = (revision.NULL_REVISION,)
 
1555
        return result
 
1556
 
 
1557
 
481
1558
class PlanWeaveMerge(TextMerge):
482
1559
    """Weave merge that takes a plan as its input.
483
 
    
 
1560
 
484
1561
    This exists so that VersionedFile.plan_merge is implementable.
485
1562
    Most callers will want to use WeaveMerge instead.
486
1563
    """
488
1565
    def __init__(self, plan, a_marker=TextMerge.A_MARKER,
489
1566
                 b_marker=TextMerge.B_MARKER):
490
1567
        TextMerge.__init__(self, a_marker, b_marker)
491
 
        self.plan = plan
 
1568
        self.plan = list(plan)
492
1569
 
493
1570
    def _merge_struct(self):
494
1571
        lines_a = []
507
1584
                yield(lines_a,)
508
1585
            else:
509
1586
                yield (lines_a, lines_b)
510
 
       
 
1587
 
511
1588
        # We previously considered either 'unchanged' or 'killed-both' lines
512
1589
        # to be possible places to resynchronize.  However, assuming agreement
513
1590
        # on killed-both lines may be too aggressive. -- mbp 20060324
519
1596
                lines_a = []
520
1597
                lines_b = []
521
1598
                ch_a = ch_b = False
522
 
                
 
1599
 
523
1600
            if state == 'unchanged':
524
1601
                if line:
525
1602
                    yield ([line],)
535
1612
            elif state == 'new-b':
536
1613
                ch_b = True
537
1614
                lines_b.append(line)
 
1615
            elif state == 'conflicted-a':
 
1616
                ch_b = ch_a = True
 
1617
                lines_a.append(line)
 
1618
            elif state == 'conflicted-b':
 
1619
                ch_b = ch_a = True
 
1620
                lines_b.append(line)
 
1621
            elif state == 'killed-both':
 
1622
                # This counts as a change, even though there is no associated
 
1623
                # line
 
1624
                ch_b = ch_a = True
538
1625
            else:
539
 
                assert state in ('irrelevant', 'ghost-a', 'ghost-b', 
540
 
                                 'killed-base', 'killed-both'), state
 
1626
                if state not in ('irrelevant', 'ghost-a', 'ghost-b',
 
1627
                        'killed-base'):
 
1628
                    raise AssertionError(state)
541
1629
        for struct in outstanding_struct():
542
1630
            yield struct
543
1631
 
 
1632
    def base_from_plan(self):
 
1633
        """Construct a BASE file from the plan text."""
 
1634
        base_lines = []
 
1635
        for state, line in self.plan:
 
1636
            if state in ('killed-a', 'killed-b', 'killed-both', 'unchanged'):
 
1637
                # If unchanged, then this line is straight from base. If a or b
 
1638
                # or both killed the line, then it *used* to be in base.
 
1639
                base_lines.append(line)
 
1640
            else:
 
1641
                if state not in ('killed-base', 'irrelevant',
 
1642
                                 'ghost-a', 'ghost-b',
 
1643
                                 'new-a', 'new-b',
 
1644
                                 'conflicted-a', 'conflicted-b'):
 
1645
                    # killed-base, irrelevant means it doesn't apply
 
1646
                    # ghost-a/ghost-b are harder to say for sure, but they
 
1647
                    # aren't in the 'inc_c' which means they aren't in the
 
1648
                    # shared base of a & b. So we don't include them.  And
 
1649
                    # obviously if the line is newly inserted, it isn't in base
 
1650
 
 
1651
                    # If 'conflicted-a' or b, then it is new vs one base, but
 
1652
                    # old versus another base. However, if we make it present
 
1653
                    # in the base, it will be deleted from the target, and it
 
1654
                    # seems better to get a line doubled in the merge result,
 
1655
                    # rather than have it deleted entirely.
 
1656
                    # Example, each node is the 'text' at that point:
 
1657
                    #           MN
 
1658
                    #          /   \
 
1659
                    #        MaN   MbN
 
1660
                    #         |  X  |
 
1661
                    #        MabN MbaN
 
1662
                    #          \   /
 
1663
                    #           ???
 
1664
                    # There was a criss-cross conflict merge. Both sides
 
1665
                    # include the other, but put themselves first.
 
1666
                    # Weave marks this as a 'clean' merge, picking OTHER over
 
1667
                    # THIS. (Though the details depend on order inserted into
 
1668
                    # weave, etc.)
 
1669
                    # LCA generates a plan:
 
1670
                    # [('unchanged', M),
 
1671
                    #  ('conflicted-b', b),
 
1672
                    #  ('unchanged', a),
 
1673
                    #  ('conflicted-a', b),
 
1674
                    #  ('unchanged', N)]
 
1675
                    # If you mark 'conflicted-*' as part of BASE, then a 3-way
 
1676
                    # merge tool will cleanly generate "MaN" (as BASE vs THIS
 
1677
                    # removes one 'b', and BASE vs OTHER removes the other)
 
1678
                    # If you include neither, 3-way creates a clean "MbabN" as
 
1679
                    # THIS adds one 'b', and OTHER does too.
 
1680
                    # It seems that having the line 2 times is better than
 
1681
                    # having it omitted. (Easier to manually delete than notice
 
1682
                    # it needs to be added.)
 
1683
                    raise AssertionError('Unknown state: %s' % (state,))
 
1684
        return base_lines
 
1685
 
544
1686
 
545
1687
class WeaveMerge(PlanWeaveMerge):
546
 
    """Weave merge that takes a VersionedFile and two versions as its input"""
 
1688
    """Weave merge that takes a VersionedFile and two versions as its input."""
547
1689
 
548
 
    def __init__(self, versionedfile, ver_a, ver_b, 
 
1690
    def __init__(self, versionedfile, ver_a, ver_b,
549
1691
        a_marker=PlanWeaveMerge.A_MARKER, b_marker=PlanWeaveMerge.B_MARKER):
550
1692
        plan = versionedfile.plan_merge(ver_a, ver_b)
551
1693
        PlanWeaveMerge.__init__(self, plan, a_marker, b_marker)
552
1694
 
553
1695
 
554
 
class InterVersionedFile(InterObject):
555
 
    """This class represents operations taking place between two versionedfiles..
556
 
 
557
 
    Its instances have methods like join, and contain
558
 
    references to the source and target versionedfiles these operations can be 
559
 
    carried out on.
560
 
 
561
 
    Often we will provide convenience methods on 'versionedfile' which carry out
562
 
    operations with another versionedfile - they will always forward to
563
 
    InterVersionedFile.get(other).method_name(parameters).
 
1696
class VirtualVersionedFiles(VersionedFiles):
 
1697
    """Dummy implementation for VersionedFiles that uses other functions for
 
1698
    obtaining fulltexts and parent maps.
 
1699
 
 
1700
    This is always on the bottom of the stack and uses string keys
 
1701
    (rather than tuples) internally.
564
1702
    """
565
1703
 
566
 
    _optimisers = []
567
 
    """The available optimised InterVersionedFile types."""
568
 
 
569
 
    def join(self, pb=None, msg=None, version_ids=None, ignore_missing=False):
570
 
        """Integrate versions from self.source into self.target.
571
 
 
572
 
        If version_ids is None all versions from source should be
573
 
        incorporated into this versioned file.
574
 
 
575
 
        Must raise RevisionNotPresent if any of the specified versions
576
 
        are not present in the other files history unless ignore_missing is 
577
 
        supplied when they are silently skipped.
578
 
        """
579
 
        # the default join: 
580
 
        # - if the target is empty, just add all the versions from 
581
 
        #   source to target, otherwise:
582
 
        # - make a temporary versioned file of type target
583
 
        # - insert the source content into it one at a time
584
 
        # - join them
585
 
        if not self.target.versions():
586
 
            target = self.target
587
 
        else:
588
 
            # Make a new target-format versioned file. 
589
 
            temp_source = self.target.create_empty("temp", MemoryTransport())
590
 
            target = temp_source
591
 
        version_ids = self._get_source_version_ids(version_ids, ignore_missing)
592
 
        graph = self.source.get_graph(version_ids)
593
 
        order = topo_sort(graph.items())
594
 
        pb = ui.ui_factory.nested_progress_bar()
595
 
        parent_texts = {}
596
 
        try:
597
 
            # TODO for incremental cross-format work:
598
 
            # make a versioned file with the following content:
599
 
            # all revisions we have been asked to join
600
 
            # all their ancestors that are *not* in target already.
601
 
            # the immediate parents of the above two sets, with 
602
 
            # empty parent lists - these versions are in target already
603
 
            # and the incorrect version data will be ignored.
604
 
            # TODO: for all ancestors that are present in target already,
605
 
            # check them for consistent data, this requires moving sha1 from
606
 
            # 
607
 
            # TODO: remove parent texts when they are not relevant any more for 
608
 
            # memory pressure reduction. RBC 20060313
609
 
            # pb.update('Converting versioned data', 0, len(order))
610
 
            # deltas = self.source.get_deltas(order)
611
 
            for index, version in enumerate(order):
612
 
                pb.update('Converting versioned data', index, len(order))
613
 
                parent_text = target.add_lines(version,
614
 
                                               self.source.get_parents(version),
615
 
                                               self.source.get_lines(version),
616
 
                                               parent_texts=parent_texts)
617
 
                parent_texts[version] = parent_text
618
 
                #delta_parent, sha1, noeol, delta = deltas[version]
619
 
                #target.add_delta(version,
620
 
                #                 self.source.get_parents(version),
621
 
                #                 delta_parent,
622
 
                #                 sha1,
623
 
                #                 noeol,
624
 
                #                 delta)
625
 
                #target.get_lines(version)
626
 
            
627
 
            # this should hit the native code path for target
628
 
            if target is not self.target:
629
 
                return self.target.join(temp_source,
630
 
                                        pb,
631
 
                                        msg,
632
 
                                        version_ids,
633
 
                                        ignore_missing)
634
 
        finally:
635
 
            pb.finished()
636
 
 
637
 
    def _get_source_version_ids(self, version_ids, ignore_missing):
638
 
        """Determine the version ids to be used from self.source.
639
 
 
640
 
        :param version_ids: The caller-supplied version ids to check. (None 
641
 
                            for all). If None is in version_ids, it is stripped.
642
 
        :param ignore_missing: if True, remove missing ids from the version 
643
 
                               list. If False, raise RevisionNotPresent on
644
 
                               a missing version id.
645
 
        :return: A set of version ids.
646
 
        """
647
 
        if version_ids is None:
648
 
            # None cannot be in source.versions
649
 
            return set(self.source.versions())
650
 
        else:
651
 
            if ignore_missing:
652
 
                return set(self.source.versions()).intersection(set(version_ids))
 
1704
    def __init__(self, get_parent_map, get_lines):
 
1705
        """Create a VirtualVersionedFiles.
 
1706
 
 
1707
        :param get_parent_map: Same signature as Repository.get_parent_map.
 
1708
        :param get_lines: Should return lines for specified key or None if
 
1709
                          not available.
 
1710
        """
 
1711
        super(VirtualVersionedFiles, self).__init__()
 
1712
        self._get_parent_map = get_parent_map
 
1713
        self._get_lines = get_lines
 
1714
 
 
1715
    def check(self, progressbar=None):
 
1716
        """See VersionedFiles.check.
 
1717
 
 
1718
        :note: Always returns True for VirtualVersionedFiles.
 
1719
        """
 
1720
        return True
 
1721
 
 
1722
    def add_mpdiffs(self, records):
 
1723
        """See VersionedFiles.mpdiffs.
 
1724
 
 
1725
        :note: Not implemented for VirtualVersionedFiles.
 
1726
        """
 
1727
        raise NotImplementedError(self.add_mpdiffs)
 
1728
 
 
1729
    def get_parent_map(self, keys):
 
1730
        """See VersionedFiles.get_parent_map."""
 
1731
        return dict([((k,), tuple([(p,) for p in v]))
 
1732
            for k,v in self._get_parent_map([k for (k,) in keys]).iteritems()])
 
1733
 
 
1734
    def get_sha1s(self, keys):
 
1735
        """See VersionedFiles.get_sha1s."""
 
1736
        ret = {}
 
1737
        for (k,) in keys:
 
1738
            lines = self._get_lines(k)
 
1739
            if lines is not None:
 
1740
                if not isinstance(lines, list):
 
1741
                    raise AssertionError
 
1742
                ret[(k,)] = osutils.sha_strings(lines)
 
1743
        return ret
 
1744
 
 
1745
    def get_record_stream(self, keys, ordering, include_delta_closure):
 
1746
        """See VersionedFiles.get_record_stream."""
 
1747
        for (k,) in list(keys):
 
1748
            lines = self._get_lines(k)
 
1749
            if lines is not None:
 
1750
                if not isinstance(lines, list):
 
1751
                    raise AssertionError
 
1752
                yield ChunkedContentFactory((k,), None,
 
1753
                        sha1=osutils.sha_strings(lines),
 
1754
                        chunks=lines)
653
1755
            else:
654
 
                new_version_ids = set()
655
 
                for version in version_ids:
656
 
                    if version is None:
657
 
                        continue
658
 
                    if not self.source.has_version(version):
659
 
                        raise errors.RevisionNotPresent(version, str(self.source))
660
 
                    else:
661
 
                        new_version_ids.add(version)
662
 
                return new_version_ids
663
 
 
664
 
 
665
 
class InterVersionedFileTestProviderAdapter(object):
666
 
    """A tool to generate a suite testing multiple inter versioned-file classes.
667
 
 
668
 
    This is done by copying the test once for each InterVersionedFile provider
669
 
    and injecting the transport_server, transport_readonly_server,
670
 
    versionedfile_factory and versionedfile_factory_to classes into each copy.
671
 
    Each copy is also given a new id() to make it easy to identify.
672
 
    """
673
 
 
674
 
    def __init__(self, transport_server, transport_readonly_server, formats):
675
 
        self._transport_server = transport_server
676
 
        self._transport_readonly_server = transport_readonly_server
677
 
        self._formats = formats
 
1756
                yield AbsentContentFactory((k,))
 
1757
 
 
1758
    def iter_lines_added_or_present_in_keys(self, keys, pb=None):
 
1759
        """See VersionedFile.iter_lines_added_or_present_in_versions()."""
 
1760
        for i, (key,) in enumerate(keys):
 
1761
            if pb is not None:
 
1762
                pb.update("Finding changed lines", i, len(keys))
 
1763
            for l in self._get_lines(key):
 
1764
                yield (l, key)
 
1765
 
 
1766
 
 
1767
class NoDupeAddLinesDecorator(object):
 
1768
    """Decorator for a VersionedFiles that skips doing an add_lines if the key
 
1769
    is already present.
 
1770
    """
 
1771
 
 
1772
    def __init__(self, store):
 
1773
        self._store = store
 
1774
 
 
1775
    def add_lines(self, key, parents, lines, parent_texts=None,
 
1776
            left_matching_blocks=None, nostore_sha=None, random_id=False,
 
1777
            check_content=True):
 
1778
        """See VersionedFiles.add_lines.
 
1779
        
 
1780
        This implementation may return None as the third element of the return
 
1781
        value when the original store wouldn't.
 
1782
        """
 
1783
        if nostore_sha:
 
1784
            raise NotImplementedError(
 
1785
                "NoDupeAddLinesDecorator.add_lines does not implement the "
 
1786
                "nostore_sha behaviour.")
 
1787
        if key[-1] is None:
 
1788
            sha1 = osutils.sha_strings(lines)
 
1789
            key = ("sha1:" + sha1,)
 
1790
        else:
 
1791
            sha1 = None
 
1792
        if key in self._store.get_parent_map([key]):
 
1793
            # This key has already been inserted, so don't do it again.
 
1794
            if sha1 is None:
 
1795
                sha1 = osutils.sha_strings(lines)
 
1796
            return sha1, sum(map(len, lines)), None
 
1797
        return self._store.add_lines(key, parents, lines,
 
1798
                parent_texts=parent_texts,
 
1799
                left_matching_blocks=left_matching_blocks,
 
1800
                nostore_sha=nostore_sha, random_id=random_id,
 
1801
                check_content=check_content)
 
1802
 
 
1803
    def __getattr__(self, name):
 
1804
        return getattr(self._store, name)
 
1805
 
 
1806
 
 
1807
def network_bytes_to_kind_and_offset(network_bytes):
 
1808
    """Strip of a record kind from the front of network_bytes.
 
1809
 
 
1810
    :param network_bytes: The bytes of a record.
 
1811
    :return: A tuple (storage_kind, offset_of_remaining_bytes)
 
1812
    """
 
1813
    line_end = network_bytes.find('\n')
 
1814
    storage_kind = network_bytes[:line_end]
 
1815
    return storage_kind, line_end + 1
 
1816
 
 
1817
 
 
1818
class NetworkRecordStream(object):
 
1819
    """A record_stream which reconstitures a serialised stream."""
 
1820
 
 
1821
    def __init__(self, bytes_iterator):
 
1822
        """Create a NetworkRecordStream.
 
1823
 
 
1824
        :param bytes_iterator: An iterator of bytes. Each item in this
 
1825
            iterator should have been obtained from a record_streams'
 
1826
            record.get_bytes_as(record.storage_kind) call.
 
1827
        """
 
1828
        self._bytes_iterator = bytes_iterator
 
1829
        self._kind_factory = {
 
1830
            'fulltext': fulltext_network_to_record,
 
1831
            'groupcompress-block': groupcompress.network_block_to_records,
 
1832
            'knit-ft-gz': knit.knit_network_to_record,
 
1833
            'knit-delta-gz': knit.knit_network_to_record,
 
1834
            'knit-annotated-ft-gz': knit.knit_network_to_record,
 
1835
            'knit-annotated-delta-gz': knit.knit_network_to_record,
 
1836
            'knit-delta-closure': knit.knit_delta_closure_to_records,
 
1837
            }
 
1838
 
 
1839
    def read(self):
 
1840
        """Read the stream.
 
1841
 
 
1842
        :return: An iterator as per VersionedFiles.get_record_stream().
 
1843
        """
 
1844
        for bytes in self._bytes_iterator:
 
1845
            storage_kind, line_end = network_bytes_to_kind_and_offset(bytes)
 
1846
            for record in self._kind_factory[storage_kind](
 
1847
                storage_kind, bytes, line_end):
 
1848
                yield record
 
1849
 
 
1850
 
 
1851
def fulltext_network_to_record(kind, bytes, line_end):
 
1852
    """Convert a network fulltext record to record."""
 
1853
    meta_len, = struct.unpack('!L', bytes[line_end:line_end+4])
 
1854
    record_meta = bytes[line_end+4:line_end+4+meta_len]
 
1855
    key, parents = bencode.bdecode_as_tuple(record_meta)
 
1856
    if parents == 'nil':
 
1857
        parents = None
 
1858
    fulltext = bytes[line_end+4+meta_len:]
 
1859
    return [FulltextContentFactory(key, parents, None, fulltext)]
 
1860
 
 
1861
 
 
1862
def _length_prefix(bytes):
 
1863
    return struct.pack('!L', len(bytes))
 
1864
 
 
1865
 
 
1866
def record_to_fulltext_bytes(record):
 
1867
    if record.parents is None:
 
1868
        parents = 'nil'
 
1869
    else:
 
1870
        parents = record.parents
 
1871
    record_meta = bencode.bencode((record.key, parents))
 
1872
    record_content = record.get_bytes_as('fulltext')
 
1873
    return "fulltext\n%s%s%s" % (
 
1874
        _length_prefix(record_meta), record_meta, record_content)
 
1875
 
 
1876
 
 
1877
def sort_groupcompress(parent_map):
 
1878
    """Sort and group the keys in parent_map into groupcompress order.
 
1879
 
 
1880
    groupcompress is defined (currently) as reverse-topological order, grouped
 
1881
    by the key prefix.
 
1882
 
 
1883
    :return: A sorted-list of keys
 
1884
    """
 
1885
    # gc-optimal ordering is approximately reverse topological,
 
1886
    # properly grouped by file-id.
 
1887
    per_prefix_map = {}
 
1888
    for item in parent_map.iteritems():
 
1889
        key = item[0]
 
1890
        if isinstance(key, str) or len(key) == 1:
 
1891
            prefix = ''
 
1892
        else:
 
1893
            prefix = key[0]
 
1894
        try:
 
1895
            per_prefix_map[prefix].append(item)
 
1896
        except KeyError:
 
1897
            per_prefix_map[prefix] = [item]
 
1898
 
 
1899
    present_keys = []
 
1900
    for prefix in sorted(per_prefix_map):
 
1901
        present_keys.extend(reversed(tsort.topo_sort(per_prefix_map[prefix])))
 
1902
    return present_keys
 
1903
 
 
1904
 
 
1905
class _KeyRefs(object):
 
1906
 
 
1907
    def __init__(self, track_new_keys=False):
 
1908
        # dict mapping 'key' to 'set of keys referring to that key'
 
1909
        self.refs = {}
 
1910
        if track_new_keys:
 
1911
            # set remembering all new keys
 
1912
            self.new_keys = set()
 
1913
        else:
 
1914
            self.new_keys = None
 
1915
 
 
1916
    def clear(self):
 
1917
        if self.refs:
 
1918
            self.refs.clear()
 
1919
        if self.new_keys:
 
1920
            self.new_keys.clear()
 
1921
 
 
1922
    def add_references(self, key, refs):
 
1923
        # Record the new references
 
1924
        for referenced in refs:
 
1925
            try:
 
1926
                needed_by = self.refs[referenced]
 
1927
            except KeyError:
 
1928
                needed_by = self.refs[referenced] = set()
 
1929
            needed_by.add(key)
 
1930
        # Discard references satisfied by the new key
 
1931
        self.add_key(key)
 
1932
 
 
1933
    def get_new_keys(self):
 
1934
        return self.new_keys
678
1935
    
679
 
    def adapt(self, test):
680
 
        result = TestSuite()
681
 
        for (interversionedfile_class,
682
 
             versionedfile_factory,
683
 
             versionedfile_factory_to) in self._formats:
684
 
            new_test = deepcopy(test)
685
 
            new_test.transport_server = self._transport_server
686
 
            new_test.transport_readonly_server = self._transport_readonly_server
687
 
            new_test.interversionedfile_class = interversionedfile_class
688
 
            new_test.versionedfile_factory = versionedfile_factory
689
 
            new_test.versionedfile_factory_to = versionedfile_factory_to
690
 
            def make_new_test_id():
691
 
                new_id = "%s(%s)" % (new_test.id(), interversionedfile_class.__name__)
692
 
                return lambda: new_id
693
 
            new_test.id = make_new_test_id()
694
 
            result.addTest(new_test)
695
 
        return result
696
 
 
697
 
    @staticmethod
698
 
    def default_test_list():
699
 
        """Generate the default list of interversionedfile permutations to test."""
700
 
        from bzrlib.weave import WeaveFile
701
 
        from bzrlib.knit import KnitVersionedFile
702
 
        result = []
703
 
        # test the fallback InterVersionedFile from annotated knits to weave
704
 
        result.append((InterVersionedFile, 
705
 
                       KnitVersionedFile,
706
 
                       WeaveFile))
707
 
        for optimiser in InterVersionedFile._optimisers:
708
 
            result.append((optimiser,
709
 
                           optimiser._matching_file_from_factory,
710
 
                           optimiser._matching_file_to_factory
711
 
                           ))
712
 
        # if there are specific combinations we want to use, we can add them 
713
 
        # here.
714
 
        return result
 
1936
    def get_unsatisfied_refs(self):
 
1937
        return self.refs.iterkeys()
 
1938
 
 
1939
    def _satisfy_refs_for_key(self, key):
 
1940
        try:
 
1941
            del self.refs[key]
 
1942
        except KeyError:
 
1943
            # No keys depended on this key.  That's ok.
 
1944
            pass
 
1945
 
 
1946
    def add_key(self, key):
 
1947
        # satisfy refs for key, and remember that we've seen this key.
 
1948
        self._satisfy_refs_for_key(key)
 
1949
        if self.new_keys is not None:
 
1950
            self.new_keys.add(key)
 
1951
 
 
1952
    def satisfy_refs_for_keys(self, keys):
 
1953
        for key in keys:
 
1954
            self._satisfy_refs_for_key(key)
 
1955
 
 
1956
    def get_referrers(self):
 
1957
        result = set()
 
1958
        for referrers in self.refs.itervalues():
 
1959
            result.update(referrers)
 
1960
        return result
 
1961
 
 
1962
 
 
1963