/brz/remove-bazaar

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

« back to all changes in this revision

Viewing changes to bzrlib/versionedfile.py

  • Committer: Andrew Bennetts
  • Date: 2008-11-27 09:00:45 UTC
  • mfrom: (3865 +trunk)
  • mto: This revision was merged to the branch mainline in revision 3866.
  • Revision ID: andrew.bennetts@canonical.com-20081127090045-qxatg46jzwrbh2lg
Merge bzr.dev, resolving NEWS conflict.  (And improve the wording of the new NEWS entry too.)

Show diffs side-by-side

added added

removed removed

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