~bzr-pqm/bzr/bzr.dev

« back to all changes in this revision

Viewing changes to bzrlib/versionedfile.py

  • Committer: Tarmac
  • Author(s): Vincent Ladeuil
  • Date: 2017-01-30 14:42:05 UTC
  • mfrom: (6620.1.1 trunk)
  • Revision ID: tarmac-20170130144205-r8fh2xpmiuxyozpv
Merge  2.7 into trunk including fix for bug #1657238 [r=vila]

Show diffs side-by-side

added added

removed removed

Lines of Context:
1
 
# Copyright (C) 2005, 2006 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
 
 
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
 
22
27
from bzrlib.lazy_import import lazy_import
23
28
lazy_import(globals(), """
24
 
 
25
29
from bzrlib import (
 
30
    annotate,
 
31
    bencode,
26
32
    errors,
 
33
    graph as _mod_graph,
 
34
    groupcompress,
 
35
    index,
 
36
    knit,
27
37
    osutils,
28
38
    multiparent,
29
39
    tsort,
30
40
    revision,
31
 
    ui,
 
41
    urlutils,
32
42
    )
33
 
from bzrlib.transport.memory import MemoryTransport
34
43
""")
35
 
 
36
 
from cStringIO import StringIO
37
 
 
38
 
from bzrlib.inter import InterObject
 
44
from bzrlib.registry import Registry
39
45
from bzrlib.textmerge import TextMerge
40
46
 
41
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]
 
333
 
 
334
 
42
335
class VersionedFile(object):
43
336
    """Versioned text file storage.
44
 
    
 
337
 
45
338
    A versioned file manages versions of line-based text files,
46
339
    keeping track of the originating version for each line.
47
340
 
53
346
    Texts are identified by a version-id string.
54
347
    """
55
348
 
56
 
    def __init__(self, access_mode):
57
 
        self.finished = False
58
 
        self._access_mode = access_mode
59
 
 
60
349
    @staticmethod
61
350
    def check_not_reserved_id(version_id):
62
351
        revision.check_not_reserved_id(version_id)
65
354
        """Copy this versioned file to name on transport."""
66
355
        raise NotImplementedError(self.copy_to)
67
356
 
68
 
    def versions(self):
69
 
        """Return a unsorted list of versions."""
70
 
        raise NotImplementedError(self.versions)
 
357
    def get_record_stream(self, versions, ordering, include_delta_closure):
 
358
        """Get a stream of records for versions.
71
359
 
72
 
    def has_ghost(self, version_id):
73
 
        """Returns whether version is present as a ghost."""
74
 
        raise NotImplementedError(self.has_ghost)
 
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.
 
371
        """
 
372
        raise NotImplementedError(self.get_record_stream)
75
373
 
76
374
    def has_version(self, version_id):
77
375
        """Returns whether version is present."""
78
376
        raise NotImplementedError(self.has_version)
79
377
 
 
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
 
80
387
    def add_lines(self, version_id, parents, lines, parent_texts=None,
81
 
                  left_matching_blocks=None, nostore_sha=None):
 
388
        left_matching_blocks=None, nostore_sha=None, random_id=False,
 
389
        check_content=True):
82
390
        """Add a single text on top of the versioned file.
83
391
 
84
392
        Must raise RevisionAlreadyPresent if the new version is
86
394
 
87
395
        Must raise RevisionNotPresent if any of the given parents are
88
396
        not present in file history.
89
 
        :param parent_texts: An optional dictionary containing the opaque 
90
 
             representations of some or all of the parents of 
91
 
             version_id to allow delta optimisations. 
92
 
             VERY IMPORTANT: the texts must be those returned
93
 
             by add_lines or data corruption can be caused.
 
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.
94
410
        :param left_matching_blocks: a hint about which areas are common
95
411
            between the text and its left-hand-parent.  The format is
96
412
            the SequenceMatcher.get_matching_blocks format.
97
413
        :param nostore_sha: Raise ExistingContent and do not add the lines to
98
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.
99
423
        :return: The text sha1, the number of bytes in the text, and an opaque
100
424
                 representation of the inserted version which can be provided
101
425
                 back to future add_lines calls in the parent_texts dictionary.
102
426
        """
103
 
        version_id = osutils.safe_revision_id(version_id)
104
 
        parents = [osutils.safe_revision_id(v) for v in parents]
105
427
        self._check_write_ok()
106
428
        return self._add_lines(version_id, parents, lines, parent_texts,
107
 
            left_matching_blocks, nostore_sha)
 
429
            left_matching_blocks, nostore_sha, random_id, check_content)
108
430
 
109
431
    def _add_lines(self, version_id, parents, lines, parent_texts,
110
 
        left_matching_blocks, nostore_sha):
 
432
        left_matching_blocks, nostore_sha, random_id, check_content):
111
433
        """Helper to do the class specific add_lines."""
112
434
        raise NotImplementedError(self.add_lines)
113
435
 
114
436
    def add_lines_with_ghosts(self, version_id, parents, lines,
115
 
                              parent_texts=None, nostore_sha=None):
 
437
        parent_texts=None, nostore_sha=None, random_id=False,
 
438
        check_content=True, left_matching_blocks=None):
116
439
        """Add lines to the versioned file, allowing ghosts to be present.
117
 
        
 
440
 
118
441
        This takes the same parameters as add_lines and returns the same.
119
442
        """
120
 
        version_id = osutils.safe_revision_id(version_id)
121
 
        parents = [osutils.safe_revision_id(v) for v in parents]
122
443
        self._check_write_ok()
123
444
        return self._add_lines_with_ghosts(version_id, parents, lines,
124
 
            parent_texts, nostore_sha)
 
445
            parent_texts, nostore_sha, random_id, check_content, left_matching_blocks)
125
446
 
126
447
    def _add_lines_with_ghosts(self, version_id, parents, lines, parent_texts,
127
 
        nostore_sha):
 
448
        nostore_sha, random_id, check_content, left_matching_blocks):
128
449
        """Helper to do class specific add_lines_with_ghosts."""
129
450
        raise NotImplementedError(self.add_lines_with_ghosts)
130
451
 
144
465
            if '\n' in line[:-1]:
145
466
                raise errors.BzrBadParameterContainsNewline("lines")
146
467
 
147
 
    def _check_write_ok(self):
148
 
        """Is the versioned file marked as 'finished' ? Raise if it is."""
149
 
        if self.finished:
150
 
            raise errors.OutSideTransaction()
151
 
        if self._access_mode != 'w':
152
 
            raise errors.ReadOnlyObjectDirtiedError(self)
153
 
 
154
 
    def enable_cache(self):
155
 
        """Tell this versioned file that it should cache any data it reads.
156
 
        
157
 
        This is advisory, implementations do not have to support caching.
158
 
        """
159
 
        pass
160
 
    
161
 
    def clear_cache(self):
162
 
        """Remove any data cached in the versioned file object.
163
 
 
164
 
        This only needs to be supported if caches are supported
165
 
        """
166
 
        pass
167
 
 
168
 
    def clone_text(self, new_version_id, old_version_id, parents):
169
 
        """Add an identical text to old_version_id as new_version_id.
170
 
 
171
 
        Must raise RevisionNotPresent if the old version or any of the
172
 
        parents are not present in file history.
173
 
 
174
 
        Must raise RevisionAlreadyPresent if the new version is
175
 
        already present in file history."""
176
 
        new_version_id = osutils.safe_revision_id(new_version_id)
177
 
        old_version_id = osutils.safe_revision_id(old_version_id)
178
 
        self._check_write_ok()
179
 
        return self._clone_text(new_version_id, old_version_id, parents)
180
 
 
181
 
    def _clone_text(self, new_version_id, old_version_id, parents):
182
 
        """Helper function to do the _clone_text work."""
183
 
        raise NotImplementedError(self.clone_text)
184
 
 
185
 
    def create_empty(self, name, transport, mode=None):
186
 
        """Create a new versioned file of this exact type.
187
 
 
188
 
        :param name: the file name
189
 
        :param transport: the transport
190
 
        :param mode: optional file mode.
191
 
        """
192
 
        raise NotImplementedError(self.create_empty)
193
 
 
194
 
    def fix_parents(self, version_id, new_parents):
195
 
        """Fix the parents list for version.
196
 
        
197
 
        This is done by appending a new version to the index
198
 
        with identical data except for the parents list.
199
 
        the parents list must be a superset of the current
200
 
        list.
201
 
        """
202
 
        version_id = osutils.safe_revision_id(version_id)
203
 
        new_parents = [osutils.safe_revision_id(p) for p in new_parents]
204
 
        self._check_write_ok()
205
 
        return self._fix_parents(version_id, new_parents)
206
 
 
207
 
    def _fix_parents(self, version_id, new_parents):
208
 
        """Helper for fix_parents."""
209
 
        raise NotImplementedError(self.fix_parents)
210
 
 
211
468
    def get_format_signature(self):
212
469
        """Get a text description of the data encoding in this file.
213
 
        
214
 
        :since: 0.19
 
470
 
 
471
        :since: 0.90
215
472
        """
216
473
        raise NotImplementedError(self.get_format_signature)
217
474
 
218
475
    def make_mpdiffs(self, version_ids):
219
 
        """Create multiparent diffs for specified versions"""
 
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*
220
481
        knit_versions = set()
 
482
        knit_versions.update(version_ids)
 
483
        parent_map = self.get_parent_map(version_ids)
221
484
        for version_id in version_ids:
222
 
            knit_versions.add(version_id)
223
 
            knit_versions.update(self.get_parents(version_id))
 
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())
224
491
        lines = dict(zip(knit_versions,
225
492
            self._get_lf_split_line_list(knit_versions)))
226
493
        diffs = []
227
494
        for version_id in version_ids:
228
495
            target = lines[version_id]
229
 
            parents = [lines[p] for p in self.get_parents(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)
230
505
            if len(parents) > 0:
231
506
                left_parent_blocks = self._extract_blocks(version_id,
232
507
                                                          parents[0], target)
240
515
        return None
241
516
 
242
517
    def add_mpdiffs(self, records):
243
 
        """Add mpdiffs to this versionedfile
 
518
        """Add mpdiffs to this VersionedFile.
244
519
 
245
520
        Records should be iterables of version, parents, expected_sha1,
246
 
        mpdiff.  mpdiff should be a MultiParent instance.
 
521
        mpdiff. mpdiff should be a MultiParent instance.
247
522
        """
 
523
        # Does this need to call self._check_write_ok()? (IanC 20070919)
248
524
        vf_parents = {}
249
525
        mpvf = multiparent.MultiMemoryVersionedFile()
250
526
        versions = []
255
531
        for version, parent_ids, expected_sha1, mpdiff in records:
256
532
            needed_parents.update(p for p in parent_ids
257
533
                                  if not mpvf.has_version(p))
258
 
        for parent_id, lines in zip(needed_parents,
259
 
                                 self._get_lf_split_line_list(needed_parents)):
 
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)):
260
537
            mpvf.add_version(lines, parent_id, [])
261
538
        for (version, parent_ids, expected_sha1, mpdiff), lines in\
262
539
            zip(records, mpvf.get_line_list(versions)):
265
542
                    mpvf.get_diff(parent_ids[0]).num_lines()))
266
543
            else:
267
544
                left_matching_blocks = None
268
 
            _, _, version_text = self.add_lines(version, parent_ids, lines,
269
 
                vf_parents, left_matching_blocks=left_matching_blocks)
 
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)
270
555
            vf_parents[version] = version_text
271
 
        for (version, parent_ids, expected_sha1, mpdiff), sha1 in\
272
 
             zip(records, self.get_sha1s(versions)):
273
 
            if expected_sha1 != sha1:
 
556
        sha1s = self.get_sha1s(versions)
 
557
        for version, parent_ids, expected_sha1, mpdiff in records:
 
558
            if expected_sha1 != sha1s[version]:
274
559
                raise errors.VersionedFileInvalidChecksum(version)
275
560
 
276
 
    def get_sha1(self, version_id):
277
 
        """Get the stored sha1 sum for the given revision.
278
 
        
279
 
        :param name: The name of the version to lookup
280
 
        """
281
 
        raise NotImplementedError(self.get_sha1)
282
 
 
283
 
    def get_sha1s(self, version_ids):
284
 
        """Get the stored sha1 sums for the given revisions.
285
 
 
286
 
        :param version_ids: The names of the versions to lookup
287
 
        :return: a list of sha1s in order according to the version_ids
288
 
        """
289
 
        raise NotImplementedError(self.get_sha1)
290
 
 
291
 
    def get_suffixes(self):
292
 
        """Return the file suffixes associated with this versioned file."""
293
 
        raise NotImplementedError(self.get_suffixes)
294
 
    
295
561
    def get_text(self, version_id):
296
562
        """Return version contents as a text string.
297
563
 
332
598
        if isinstance(version_ids, basestring):
333
599
            version_ids = [version_ids]
334
600
        raise NotImplementedError(self.get_ancestry)
335
 
        
 
601
 
336
602
    def get_ancestry_with_ghosts(self, version_ids):
337
603
        """Return a list of all ancestors of given version(s). This
338
604
        will not include the null revision.
339
605
 
340
606
        Must raise RevisionNotPresent if any of the given versions are
341
607
        not present in file history.
342
 
        
 
608
 
343
609
        Ghosts that are known about will be included in ancestry list,
344
610
        but are not explicitly marked.
345
611
        """
346
612
        raise NotImplementedError(self.get_ancestry_with_ghosts)
347
 
        
348
 
    def get_graph(self, version_ids=None):
349
 
        """Return a graph from the versioned file. 
350
 
        
351
 
        Ghosts are not listed or referenced in the graph.
352
 
        :param version_ids: Versions to select.
353
 
                            None means retrieve all versions.
354
 
        """
355
 
        if version_ids is None:
356
 
            return dict(self.iter_parents(self.versions()))
357
 
        result = {}
358
 
        pending = set(osutils.safe_revision_id(v) for v in version_ids)
359
 
        while pending:
360
 
            this_iteration = pending
361
 
            pending = set()
362
 
            for version, parents in self.iter_parents(this_iteration):
363
 
                result[version] = parents
364
 
                for parent in parents:
365
 
                    if parent in result:
366
 
                        continue
367
 
                    pending.add(parent)
368
 
        return result
369
 
 
370
 
    def get_graph_with_ghosts(self):
371
 
        """Return a graph for the entire versioned file.
372
 
        
373
 
        Ghosts are referenced in parents list but are not
374
 
        explicitly listed.
375
 
        """
376
 
        raise NotImplementedError(self.get_graph_with_ghosts)
377
 
 
378
 
    def get_parents(self, version_id):
379
 
        """Return version names for parents of a version.
380
 
 
381
 
        Must raise RevisionNotPresent if version is not present in
382
 
        file history.
383
 
        """
384
 
        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)
385
621
 
386
622
    def get_parents_with_ghosts(self, version_id):
387
623
        """Return version names for parents of version_id.
392
628
        Ghosts that are known about will be included in the parent list,
393
629
        but are not explicitly marked.
394
630
        """
395
 
        raise NotImplementedError(self.get_parents_with_ghosts)
396
 
 
397
 
    def annotate_iter(self, version_id):
398
 
        """Yield list of (version-id, line) pairs for the specified
399
 
        version.
400
 
 
401
 
        Must raise RevisionNotPresent if any of the given versions are
402
 
        not present in file history.
403
 
        """
404
 
        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)
405
635
 
406
636
    def annotate(self, version_id):
407
 
        return list(self.annotate_iter(version_id))
408
 
 
409
 
    def _apply_delta(self, lines, delta):
410
 
        """Apply delta to lines."""
411
 
        lines = list(lines)
412
 
        offset = 0
413
 
        for start, end, count, delta_lines in delta:
414
 
            lines[offset+start:offset+end] = delta_lines
415
 
            offset = offset + (start - end) + count
416
 
        return lines
417
 
 
418
 
    def join(self, other, pb=None, msg=None, version_ids=None,
419
 
             ignore_missing=False):
420
 
        """Integrate versions from other into this versioned file.
421
 
 
422
 
        If version_ids is None all versions from other should be
423
 
        incorporated into this versioned file.
424
 
 
425
 
        Must raise RevisionNotPresent if any of the specified versions
426
 
        are not present in the other files history unless ignore_missing
427
 
        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.
428
641
        """
429
 
        self._check_write_ok()
430
 
        return InterVersionedFile.get(other, self).join(
431
 
            pb,
432
 
            msg,
433
 
            version_ids,
434
 
            ignore_missing)
 
642
        raise NotImplementedError(self.annotate)
435
643
 
436
 
    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,
437
645
                                                pb=None):
438
646
        """Iterate over the lines in the versioned file from version_ids.
439
647
 
440
 
        This may return lines from other versions, and does not return the
441
 
        specific version marker at this point. The api may be changed
442
 
        during development to include the version that the versioned file
443
 
        thinks is relevant, but given that such hints are just guesses,
444
 
        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.
445
654
 
446
655
        If a progress bar is supplied, it may be used to indicate progress.
447
656
        The caller is responsible for cleaning up progress bars (because this
449
658
 
450
659
        NOTES: Lines are normalised: they will all have \n terminators.
451
660
               Lines are returned in arbitrary order.
 
661
 
 
662
        :return: An iterator over (line, version_id).
452
663
        """
453
664
        raise NotImplementedError(self.iter_lines_added_or_present_in_versions)
454
665
 
455
 
    def iter_parents(self, version_ids):
456
 
        """Iterate through the parents for many version ids.
457
 
 
458
 
        :param version_ids: An iterable yielding version_ids.
459
 
        :return: An iterator that yields (version_id, parents). Requested 
460
 
            version_ids not present in the versioned file are simply skipped.
461
 
            The order is undefined, allowing for different optimisations in
462
 
            the underlying implementation.
463
 
        """
464
 
        for version_id in version_ids:
465
 
            try:
466
 
                yield version_id, tuple(self.get_parents(version_id))
467
 
            except errors.RevisionNotPresent:
468
 
                pass
469
 
 
470
 
    def transaction_finished(self):
471
 
        """The transaction that this file was opened in has finished.
472
 
 
473
 
        This records self.finished = True and should cause all mutating
474
 
        operations to error.
475
 
        """
476
 
        self.finished = True
477
 
 
478
666
    def plan_merge(self, ver_a, ver_b):
479
667
        """Return pseudo-annotation indicating how the two versions merge.
480
668
 
491
679
        unchanged   Alive in both a and b (possibly created in both)
492
680
        new-a       Created in a
493
681
        new-b       Created in b
494
 
        ghost-a     Killed in a, unborn in b    
 
682
        ghost-a     Killed in a, unborn in b
495
683
        ghost-b     Killed in b, unborn in a
496
684
        irrelevant  Not in either revision
497
685
        """
498
686
        raise NotImplementedError(VersionedFile.plan_merge)
499
 
        
 
687
 
500
688
    def weave_merge(self, plan, a_marker=TextMerge.A_MARKER,
501
689
                    b_marker=TextMerge.B_MARKER):
502
690
        return PlanWeaveMerge(plan, a_marker, b_marker).merge_lines()[0]
503
691
 
504
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
 
505
1558
class PlanWeaveMerge(TextMerge):
506
1559
    """Weave merge that takes a plan as its input.
507
 
    
 
1560
 
508
1561
    This exists so that VersionedFile.plan_merge is implementable.
509
1562
    Most callers will want to use WeaveMerge instead.
510
1563
    """
512
1565
    def __init__(self, plan, a_marker=TextMerge.A_MARKER,
513
1566
                 b_marker=TextMerge.B_MARKER):
514
1567
        TextMerge.__init__(self, a_marker, b_marker)
515
 
        self.plan = plan
 
1568
        self.plan = list(plan)
516
1569
 
517
1570
    def _merge_struct(self):
518
1571
        lines_a = []
531
1584
                yield(lines_a,)
532
1585
            else:
533
1586
                yield (lines_a, lines_b)
534
 
       
 
1587
 
535
1588
        # We previously considered either 'unchanged' or 'killed-both' lines
536
1589
        # to be possible places to resynchronize.  However, assuming agreement
537
1590
        # on killed-both lines may be too aggressive. -- mbp 20060324
543
1596
                lines_a = []
544
1597
                lines_b = []
545
1598
                ch_a = ch_b = False
546
 
                
 
1599
 
547
1600
            if state == 'unchanged':
548
1601
                if line:
549
1602
                    yield ([line],)
559
1612
            elif state == 'new-b':
560
1613
                ch_b = True
561
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
562
1625
            else:
563
 
                assert state in ('irrelevant', 'ghost-a', 'ghost-b', 
564
 
                                 'killed-base', 'killed-both'), state
 
1626
                if state not in ('irrelevant', 'ghost-a', 'ghost-b',
 
1627
                        'killed-base'):
 
1628
                    raise AssertionError(state)
565
1629
        for struct in outstanding_struct():
566
1630
            yield struct
567
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
 
568
1686
 
569
1687
class WeaveMerge(PlanWeaveMerge):
570
 
    """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."""
571
1689
 
572
 
    def __init__(self, versionedfile, ver_a, ver_b, 
 
1690
    def __init__(self, versionedfile, ver_a, ver_b,
573
1691
        a_marker=PlanWeaveMerge.A_MARKER, b_marker=PlanWeaveMerge.B_MARKER):
574
1692
        plan = versionedfile.plan_merge(ver_a, ver_b)
575
1693
        PlanWeaveMerge.__init__(self, plan, a_marker, b_marker)
576
1694
 
577
1695
 
578
 
class InterVersionedFile(InterObject):
579
 
    """This class represents operations taking place between two versionedfiles..
580
 
 
581
 
    Its instances have methods like join, and contain
582
 
    references to the source and target versionedfiles these operations can be 
583
 
    carried out on.
584
 
 
585
 
    Often we will provide convenience methods on 'versionedfile' which carry out
586
 
    operations with another versionedfile - they will always forward to
587
 
    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.
588
1702
    """
589
1703
 
590
 
    _optimisers = []
591
 
    """The available optimised InterVersionedFile types."""
592
 
 
593
 
    def join(self, pb=None, msg=None, version_ids=None, ignore_missing=False):
594
 
        """Integrate versions from self.source into self.target.
595
 
 
596
 
        If version_ids is None all versions from source should be
597
 
        incorporated into this versioned file.
598
 
 
599
 
        Must raise RevisionNotPresent if any of the specified versions
600
 
        are not present in the other files history unless ignore_missing is 
601
 
        supplied when they are silently skipped.
602
 
        """
603
 
        # the default join: 
604
 
        # - if the target is empty, just add all the versions from 
605
 
        #   source to target, otherwise:
606
 
        # - make a temporary versioned file of type target
607
 
        # - insert the source content into it one at a time
608
 
        # - join them
609
 
        if not self.target.versions():
610
 
            target = self.target
611
 
        else:
612
 
            # Make a new target-format versioned file. 
613
 
            temp_source = self.target.create_empty("temp", MemoryTransport())
614
 
            target = temp_source
615
 
        version_ids = self._get_source_version_ids(version_ids, ignore_missing)
616
 
        graph = self.source.get_graph(version_ids)
617
 
        order = tsort.topo_sort(graph.items())
618
 
        pb = ui.ui_factory.nested_progress_bar()
619
 
        parent_texts = {}
620
 
        try:
621
 
            # TODO for incremental cross-format work:
622
 
            # make a versioned file with the following content:
623
 
            # all revisions we have been asked to join
624
 
            # all their ancestors that are *not* in target already.
625
 
            # the immediate parents of the above two sets, with 
626
 
            # empty parent lists - these versions are in target already
627
 
            # and the incorrect version data will be ignored.
628
 
            # TODO: for all ancestors that are present in target already,
629
 
            # check them for consistent data, this requires moving sha1 from
630
 
            # 
631
 
            # TODO: remove parent texts when they are not relevant any more for 
632
 
            # memory pressure reduction. RBC 20060313
633
 
            # pb.update('Converting versioned data', 0, len(order))
634
 
            for index, version in enumerate(order):
635
 
                pb.update('Converting versioned data', index, len(order))
636
 
                _, _, parent_text = target.add_lines(version,
637
 
                                               self.source.get_parents(version),
638
 
                                               self.source.get_lines(version),
639
 
                                               parent_texts=parent_texts)
640
 
                parent_texts[version] = parent_text
641
 
            
642
 
            # this should hit the native code path for target
643
 
            if target is not self.target:
644
 
                return self.target.join(temp_source,
645
 
                                        pb,
646
 
                                        msg,
647
 
                                        version_ids,
648
 
                                        ignore_missing)
649
 
        finally:
650
 
            pb.finished()
651
 
 
652
 
    def _get_source_version_ids(self, version_ids, ignore_missing):
653
 
        """Determine the version ids to be used from self.source.
654
 
 
655
 
        :param version_ids: The caller-supplied version ids to check. (None 
656
 
                            for all). If None is in version_ids, it is stripped.
657
 
        :param ignore_missing: if True, remove missing ids from the version 
658
 
                               list. If False, raise RevisionNotPresent on
659
 
                               a missing version id.
660
 
        :return: A set of version ids.
661
 
        """
662
 
        if version_ids is None:
663
 
            # None cannot be in source.versions
664
 
            return set(self.source.versions())
665
 
        else:
666
 
            version_ids = [osutils.safe_revision_id(v) for v in version_ids]
667
 
            if ignore_missing:
668
 
                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)
669
1755
            else:
670
 
                new_version_ids = set()
671
 
                for version in version_ids:
672
 
                    if version is None:
673
 
                        continue
674
 
                    if not self.source.has_version(version):
675
 
                        raise errors.RevisionNotPresent(version, str(self.source))
676
 
                    else:
677
 
                        new_version_ids.add(version)
678
 
                return new_version_ids
 
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
 
1935
    
 
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