/brz/remove-bazaar

To get this branch, use:
bzr branch http://gegoxaren.bato24.eu/bzr/brz/remove-bazaar
3830.3.20 by John Arbash Meinel
Minor PEP8 and copyright updates.
1
# Copyright (C) 2005, 2006, 2007, 2008 Canonical Ltd
1563.2.1 by Robert Collins
Merge in a variation of the versionedfile api from versioned-file.
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.
1887.1.1 by Adeodato Simó
Do not separate paragraphs in the copyright statement with blank lines,
10
#
1563.2.1 by Robert Collins
Merge in a variation of the versionedfile api from versioned-file.
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.
1887.1.1 by Adeodato Simó
Do not separate paragraphs in the copyright statement with blank lines,
15
#
1563.2.1 by Robert Collins
Merge in a variation of the versionedfile api from versioned-file.
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
3350.8.2 by Robert Collins
stacked get_parent_map.
22
from copy import copy
3350.6.1 by Robert Collins
* New ``versionedfile.KeyMapper`` interface to abstract out the access to
23
from cStringIO import StringIO
3350.6.4 by Robert Collins
First cut at pluralised VersionedFiles. Some rather massive API incompatabilities, primarily because of the difficulty of coherence among competing stores.
24
import os
3350.6.1 by Robert Collins
* New ``versionedfile.KeyMapper`` interface to abstract out the access to
25
from zlib import adler32
26
1996.3.7 by John Arbash Meinel
lazy import versionedfile, late-load bzrlib.merge
27
from bzrlib.lazy_import import lazy_import
28
lazy_import(globals(), """
3224.5.20 by Andrew Bennetts
Remove or lazyify a couple more imports.
29
import urllib
1996.3.7 by John Arbash Meinel
lazy import versionedfile, late-load bzrlib.merge
30
31
from bzrlib import (
32
    errors,
3830.3.12 by Martin Pool
Review cleanups: unify has_key impls, add missing_keys(), clean up exception blocks
33
    index,
2249.5.12 by John Arbash Meinel
Change the APIs for VersionedFile, Store, and some of Repository into utf-8
34
    osutils,
2520.4.3 by Aaron Bentley
Implement plain strategy for extracting and installing multiparent diffs
35
    multiparent,
1996.3.7 by John Arbash Meinel
lazy import versionedfile, late-load bzrlib.merge
36
    tsort,
2229.2.1 by Aaron Bentley
Reject reserved ids in versiondfile, tree, branch and repository
37
    revision,
1996.3.7 by John Arbash Meinel
lazy import versionedfile, late-load bzrlib.merge
38
    ui,
39
    )
3350.6.4 by Robert Collins
First cut at pluralised VersionedFiles. Some rather massive API incompatabilities, primarily because of the difficulty of coherence among competing stores.
40
from bzrlib.graph import DictParentsProvider, Graph, _StackedParentsProvider
1996.3.7 by John Arbash Meinel
lazy import versionedfile, late-load bzrlib.merge
41
from bzrlib.transport.memory import MemoryTransport
42
""")
1563.2.12 by Robert Collins
Checkpointing: created InterObject to factor out common inter object worker code, added InterVersionedFile and tests to allow making join work between any versionedfile.
43
from bzrlib.inter import InterObject
3350.3.7 by Robert Collins
Create a registry of versioned file record adapters.
44
from bzrlib.registry import Registry
3287.5.2 by Robert Collins
Deprecate VersionedFile.get_parents, breaking pulling from a ghost containing knit or pack repository to weaves, which improves correctness and allows simplification of core code.
45
from bzrlib.symbol_versioning import *
1551.6.7 by Aaron Bentley
Implemented two-way merge, refactored weave merge
46
from bzrlib.textmerge import TextMerge
1563.2.11 by Robert Collins
Consolidate reweave and join as we have no separate usage, make reweave tests apply to all versionedfile implementations and deprecate the old reweave apis.
47
48
3350.3.7 by Robert Collins
Create a registry of versioned file record adapters.
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
3350.3.3 by Robert Collins
Functional get_record_stream interface tests covering full interface.
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).
3350.6.4 by Robert Collins
First cut at pluralised VersionedFiles. Some rather massive API incompatabilities, primarily because of the difficulty of coherence among competing stores.
77
    """
3350.3.3 by Robert Collins
Functional get_record_stream interface tests covering full interface.
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
3350.6.4 by Robert Collins
First cut at pluralised VersionedFiles. Some rather massive API incompatabilities, primarily because of the difficulty of coherence among competing stores.
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):
3350.3.12 by Robert Collins
Generate streams with absent records.
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
3350.6.4 by Robert Collins
First cut at pluralised VersionedFiles. Some rather massive API incompatabilities, primarily because of the difficulty of coherence among competing stores.
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
3350.3.14 by Robert Collins
Deprecate VersionedFile.join.
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
1563.2.1 by Robert Collins
Merge in a variation of the versionedfile api from versioned-file.
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
2229.2.1 by Aaron Bentley
Reject reserved ids in versiondfile, tree, branch and repository
174
    @staticmethod
2229.2.3 by Aaron Bentley
change reserved_id to is_reserved_id, add check_not_reserved for DRY
175
    def check_not_reserved_id(version_id):
176
        revision.check_not_reserved_id(version_id)
2229.2.1 by Aaron Bentley
Reject reserved ids in versiondfile, tree, branch and repository
177
1563.2.15 by Robert Collins
remove the weavestore assumptions about the number and nature of files it manages.
178
    def copy_to(self, name, transport):
179
        """Copy this versioned file to name on transport."""
180
        raise NotImplementedError(self.copy_to)
1863.1.1 by John Arbash Meinel
Allow Versioned files to do caching if explicitly asked, and implement for Knit
181
3350.3.3 by Robert Collins
Functional get_record_stream interface tests covering full interface.
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
3350.3.22 by Robert Collins
Review feedback.
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.
3350.3.3 by Robert Collins
Functional get_record_stream interface tests covering full interface.
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)
1563.2.1 by Robert Collins
Merge in a variation of the versionedfile api from versioned-file.
198
199
    def has_version(self, version_id):
200
        """Returns whether version is present."""
201
        raise NotImplementedError(self.has_version)
202
3350.3.8 by Robert Collins
Basic stream insertion, no fast path yet for knit to knit.
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
2520.4.140 by Aaron Bentley
Use matching blocks from mpdiff for knit delta creation
212
    def add_lines(self, version_id, parents, lines, parent_texts=None,
2805.6.7 by Robert Collins
Review feedback.
213
        left_matching_blocks=None, nostore_sha=None, random_id=False,
214
        check_content=True):
1563.2.1 by Robert Collins
Merge in a variation of the versionedfile api from versioned-file.
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
1594.2.21 by Robert Collins
Teach versioned files to prevent mutation after finishing.
221
        not present in file history.
2805.6.3 by Robert Collins
* The ``VersionedFile`` interface no longer protects against misuse when
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
2805.6.7 by Robert Collins
Review feedback.
229
            correctly is expensive and extremely unlikely to catch bugs so it
230
            is not done at runtime unless check_content is True.)
1596.2.32 by Robert Collins
Reduce re-extraction of texts during weave to knit joins by providing a memoisation facility.
231
        :param parent_texts: An optional dictionary containing the opaque 
2805.6.3 by Robert Collins
* The ``VersionedFile`` interface no longer protects against misuse when
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.
2520.4.148 by Aaron Bentley
Updates from review
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.
2794.1.1 by Robert Collins
Allow knits to be instructed not to add a text based on a sha, for commit.
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.
2805.6.4 by Robert Collins
Don't check for existing versions when adding texts with random revision ids.
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.
2805.6.7 by Robert Collins
Review feedback.
246
        :param check_content: If True, the lines supplied are verified to be
247
            bytestrings that are correctly formed lines.
2776.1.1 by Robert Collins
* The ``add_lines`` methods on ``VersionedFile`` implementations has changed
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.
1594.2.21 by Robert Collins
Teach versioned files to prevent mutation after finishing.
251
        """
1594.2.23 by Robert Collins
Test versioned file storage handling of clean/dirty status for accessed versioned files.
252
        self._check_write_ok()
2520.4.140 by Aaron Bentley
Use matching blocks from mpdiff for knit delta creation
253
        return self._add_lines(version_id, parents, lines, parent_texts,
2805.6.7 by Robert Collins
Review feedback.
254
            left_matching_blocks, nostore_sha, random_id, check_content)
1594.2.21 by Robert Collins
Teach versioned files to prevent mutation after finishing.
255
2520.4.140 by Aaron Bentley
Use matching blocks from mpdiff for knit delta creation
256
    def _add_lines(self, version_id, parents, lines, parent_texts,
2805.6.7 by Robert Collins
Review feedback.
257
        left_matching_blocks, nostore_sha, random_id, check_content):
1594.2.21 by Robert Collins
Teach versioned files to prevent mutation after finishing.
258
        """Helper to do the class specific add_lines."""
1563.2.4 by Robert Collins
First cut at including the knit implementation of versioned_file.
259
        raise NotImplementedError(self.add_lines)
1563.2.1 by Robert Collins
Merge in a variation of the versionedfile api from versioned-file.
260
1596.2.32 by Robert Collins
Reduce re-extraction of texts during weave to knit joins by providing a memoisation facility.
261
    def add_lines_with_ghosts(self, version_id, parents, lines,
2805.6.7 by Robert Collins
Review feedback.
262
        parent_texts=None, nostore_sha=None, random_id=False,
3287.5.2 by Robert Collins
Deprecate VersionedFile.get_parents, breaking pulling from a ghost containing knit or pack repository to weaves, which improves correctness and allows simplification of core code.
263
        check_content=True, left_matching_blocks=None):
1596.2.32 by Robert Collins
Reduce re-extraction of texts during weave to knit joins by providing a memoisation facility.
264
        """Add lines to the versioned file, allowing ghosts to be present.
265
        
2794.1.1 by Robert Collins
Allow knits to be instructed not to add a text based on a sha, for commit.
266
        This takes the same parameters as add_lines and returns the same.
1596.2.32 by Robert Collins
Reduce re-extraction of texts during weave to knit joins by providing a memoisation facility.
267
        """
1594.2.23 by Robert Collins
Test versioned file storage handling of clean/dirty status for accessed versioned files.
268
        self._check_write_ok()
1596.2.32 by Robert Collins
Reduce re-extraction of texts during weave to knit joins by providing a memoisation facility.
269
        return self._add_lines_with_ghosts(version_id, parents, lines,
3287.5.2 by Robert Collins
Deprecate VersionedFile.get_parents, breaking pulling from a ghost containing knit or pack repository to weaves, which improves correctness and allows simplification of core code.
270
            parent_texts, nostore_sha, random_id, check_content, left_matching_blocks)
1594.2.21 by Robert Collins
Teach versioned files to prevent mutation after finishing.
271
2794.1.1 by Robert Collins
Allow knits to be instructed not to add a text based on a sha, for commit.
272
    def _add_lines_with_ghosts(self, version_id, parents, lines, parent_texts,
3287.5.2 by Robert Collins
Deprecate VersionedFile.get_parents, breaking pulling from a ghost containing knit or pack repository to weaves, which improves correctness and allows simplification of core code.
273
        nostore_sha, random_id, check_content, left_matching_blocks):
1594.2.21 by Robert Collins
Teach versioned files to prevent mutation after finishing.
274
        """Helper to do class specific add_lines_with_ghosts."""
1594.2.8 by Robert Collins
add ghost aware apis to knits.
275
        raise NotImplementedError(self.add_lines_with_ghosts)
276
1563.2.19 by Robert Collins
stub out a check for knits.
277
    def check(self, progress_bar=None):
278
        """Check the versioned file for integrity."""
279
        raise NotImplementedError(self.check)
280
1666.1.6 by Robert Collins
Make knit the default format.
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
2535.3.1 by Andrew Bennetts
Add get_format_signature to VersionedFile
293
    def get_format_signature(self):
294
        """Get a text description of the data encoding in this file.
295
        
2831.7.1 by Ian Clatworthy
versionedfile.py code cleanups
296
        :since: 0.90
2535.3.1 by Andrew Bennetts
Add get_format_signature to VersionedFile
297
        """
298
        raise NotImplementedError(self.get_format_signature)
299
2520.4.41 by Aaron Bentley
Accelerate mpdiff generation
300
    def make_mpdiffs(self, version_ids):
2831.7.1 by Ian Clatworthy
versionedfile.py code cleanups
301
        """Create multiparent diffs for specified versions."""
2520.4.41 by Aaron Bentley
Accelerate mpdiff generation
302
        knit_versions = set()
3287.5.2 by Robert Collins
Deprecate VersionedFile.get_parents, breaking pulling from a ghost containing knit or pack repository to weaves, which improves correctness and allows simplification of core code.
303
        knit_versions.update(version_ids)
304
        parent_map = self.get_parent_map(version_ids)
2520.4.41 by Aaron Bentley
Accelerate mpdiff generation
305
        for version_id in version_ids:
3287.5.2 by Robert Collins
Deprecate VersionedFile.get_parents, breaking pulling from a ghost containing knit or pack repository to weaves, which improves correctness and allows simplification of core code.
306
            try:
307
                knit_versions.update(parent_map[version_id])
308
            except KeyError:
3453.3.1 by Daniel Fischer
Raise the right exception in make_mpdiffs (bug #235687)
309
                raise errors.RevisionNotPresent(version_id, self)
3287.5.2 by Robert Collins
Deprecate VersionedFile.get_parents, breaking pulling from a ghost containing knit or pack repository to weaves, which improves correctness and allows simplification of core code.
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())
2520.4.90 by Aaron Bentley
Handle \r terminated lines in Weaves properly
312
        lines = dict(zip(knit_versions,
313
            self._get_lf_split_line_list(knit_versions)))
2520.4.41 by Aaron Bentley
Accelerate mpdiff generation
314
        diffs = []
315
        for version_id in version_ids:
316
            target = lines[version_id]
3287.5.2 by Robert Collins
Deprecate VersionedFile.get_parents, breaking pulling from a ghost containing knit or pack repository to weaves, which improves correctness and allows simplification of core code.
317
            try:
318
                parents = [lines[p] for p in parent_map[version_id] if p in
319
                    knit_versions]
320
            except KeyError:
3453.3.2 by John Arbash Meinel
Add a test case for the first loop, unable to find a way to trigger the second loop
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.
3453.3.1 by Daniel Fischer
Raise the right exception in make_mpdiffs (bug #235687)
325
                raise errors.RevisionNotPresent(version_id, self)
2520.4.48 by Aaron Bentley
Support getting blocks from knit deltas with no final EOL
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
2520.4.41 by Aaron Bentley
Accelerate mpdiff generation
331
            diffs.append(multiparent.MultiParent.from_lines(target, parents,
332
                         left_parent_blocks))
333
        return diffs
334
2520.4.48 by Aaron Bentley
Support getting blocks from knit deltas with no final EOL
335
    def _extract_blocks(self, version_id, source, target):
2520.4.41 by Aaron Bentley
Accelerate mpdiff generation
336
        return None
2520.4.3 by Aaron Bentley
Implement plain strategy for extracting and installing multiparent diffs
337
2520.4.61 by Aaron Bentley
Do bulk insertion of records
338
    def add_mpdiffs(self, records):
2831.7.1 by Ian Clatworthy
versionedfile.py code cleanups
339
        """Add mpdiffs to this VersionedFile.
2520.4.126 by Aaron Bentley
Add more docs
340
341
        Records should be iterables of version, parents, expected_sha1,
2831.7.1 by Ian Clatworthy
versionedfile.py code cleanups
342
        mpdiff. mpdiff should be a MultiParent instance.
2520.4.126 by Aaron Bentley
Add more docs
343
        """
2831.7.1 by Ian Clatworthy
versionedfile.py code cleanups
344
        # Does this need to call self._check_write_ok()? (IanC 20070919)
2520.4.61 by Aaron Bentley
Do bulk insertion of records
345
        vf_parents = {}
2520.4.141 by Aaron Bentley
More batch operations adding mpdiffs
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()
2520.4.142 by Aaron Bentley
Clean up installation of inventory records
352
        for version, parent_ids, expected_sha1, mpdiff in records:
2520.4.141 by Aaron Bentley
More batch operations adding mpdiffs
353
            needed_parents.update(p for p in parent_ids
354
                                  if not mpvf.has_version(p))
3287.5.2 by Robert Collins
Deprecate VersionedFile.get_parents, breaking pulling from a ghost containing knit or pack repository to weaves, which improves correctness and allows simplification of core code.
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)):
2520.4.141 by Aaron Bentley
More batch operations adding mpdiffs
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:
2520.4.140 by Aaron Bentley
Use matching blocks from mpdiff for knit delta creation
362
                left_matching_blocks = list(mpdiff.get_matching_blocks(0,
2520.4.141 by Aaron Bentley
More batch operations adding mpdiffs
363
                    mpvf.get_diff(parent_ids[0]).num_lines()))
2520.4.140 by Aaron Bentley
Use matching blocks from mpdiff for knit delta creation
364
            else:
365
                left_matching_blocks = None
3287.5.2 by Robert Collins
Deprecate VersionedFile.get_parents, breaking pulling from a ghost containing knit or pack repository to weaves, which improves correctness and allows simplification of core code.
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)
2520.4.61 by Aaron Bentley
Do bulk insertion of records
376
            vf_parents[version] = version_text
3350.8.3 by Robert Collins
VF.get_sha1s needed changing to be stackable.
377
        sha1s = self.get_sha1s(versions)
378
        for version, parent_ids, expected_sha1, mpdiff in records:
379
            if expected_sha1 != sha1s[version]:
2520.4.71 by Aaron Bentley
Update test to accept VersionedFileInvalidChecksum instead of TestamentMismatch
380
                raise errors.VersionedFileInvalidChecksum(version)
2520.4.3 by Aaron Bentley
Implement plain strategy for extracting and installing multiparent diffs
381
1563.2.1 by Robert Collins
Merge in a variation of the versionedfile api from versioned-file.
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
1756.2.1 by Aaron Bentley
Implement get_texts
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
1563.2.1 by Robert Collins
Merge in a variation of the versionedfile api from versioned-file.
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
2520.4.90 by Aaron Bentley
Handle \r terminated lines in Weaves properly
407
    def _get_lf_split_line_list(self, version_ids):
408
        return [StringIO(t).readlines() for t in self.get_texts(version_ids)]
2520.4.3 by Aaron Bentley
Implement plain strategy for extracting and installing multiparent diffs
409
2530.1.1 by Aaron Bentley
Make topological sorting optional for get_ancestry
410
    def get_ancestry(self, version_ids, topo_sorted=True):
1563.2.1 by Robert Collins
Merge in a variation of the versionedfile api from versioned-file.
411
        """Return a list of all ancestors of given version(s). This
412
        will not include the null revision.
413
2490.2.32 by Aaron Bentley
Merge of not-sorting-ancestry branch
414
        This list will not be topologically sorted if topo_sorted=False is
415
        passed.
2530.1.1 by Aaron Bentley
Make topological sorting optional for get_ancestry
416
1563.2.1 by Robert Collins
Merge in a variation of the versionedfile api from versioned-file.
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
        
1594.2.8 by Robert Collins
add ghost aware apis to knits.
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)
3316.2.7 by Robert Collins
Actually deprecated VersionedFile.get_graph.
434
    
3287.5.1 by Robert Collins
Add VersionedFile.get_parent_map.
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
1594.2.8 by Robert Collins
add ghost aware apis to knits.
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
        """
3287.5.1 by Robert Collins
Add VersionedFile.get_parent_map.
452
        try:
453
            return list(self.get_parent_map([version_id])[version_id])
454
        except KeyError:
455
            raise errors.RevisionNotPresent(version_id, self)
1594.2.8 by Robert Collins
add ghost aware apis to knits.
456
1563.2.1 by Robert Collins
Merge in a variation of the versionedfile api from versioned-file.
457
    def annotate(self, version_id):
3316.2.13 by Robert Collins
* ``VersionedFile.annotate_iter`` is deprecated. While in principal this
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)
1563.2.1 by Robert Collins
Merge in a variation of the versionedfile api from versioned-file.
464
2975.3.2 by Robert Collins
Review feedback - document the API change and improve readability in pack's _do_copy_nodes.
465
    def iter_lines_added_or_present_in_versions(self, version_ids=None,
2039.1.1 by Aaron Bentley
Clean up progress properly when interrupted during fetch (#54000)
466
                                                pb=None):
1594.2.6 by Robert Collins
Introduce a api specifically for looking at lines in some versions of the inventory, for fileid_involved.
467
        """Iterate over the lines in the versioned file from version_ids.
468
2975.3.2 by Robert Collins
Review feedback - document the API change and improve readability in pack's _do_copy_nodes.
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.
1594.2.6 by Robert Collins
Introduce a api specifically for looking at lines in some versions of the inventory, for fileid_involved.
475
2039.1.1 by Aaron Bentley
Clean up progress properly when interrupted during fetch (#54000)
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
1594.2.6 by Robert Collins
Introduce a api specifically for looking at lines in some versions of the inventory, for fileid_involved.
480
        NOTES: Lines are normalised: they will all have \n terminators.
481
               Lines are returned in arbitrary order.
2975.3.2 by Robert Collins
Review feedback - document the API change and improve readability in pack's _do_copy_nodes.
482
483
        :return: An iterator over (line, version_id).
1594.2.6 by Robert Collins
Introduce a api specifically for looking at lines in some versions of the inventory, for fileid_involved.
484
        """
485
        raise NotImplementedError(self.iter_lines_added_or_present_in_versions)
486
1551.6.15 by Aaron Bentley
Moved plan_merge into Weave
487
    def plan_merge(self, ver_a, ver_b):
1563.2.1 by Robert Collins
Merge in a variation of the versionedfile api from versioned-file.
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.
1664.2.2 by Aaron Bentley
Added legend for plan-merge output
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
1664.2.5 by Aaron Bentley
Update plan-merge legend
503
        ghost-a     Killed in a, unborn in b    
504
        ghost-b     Killed in b, unborn in a
1664.2.2 by Aaron Bentley
Added legend for plan-merge output
505
        irrelevant  Not in either revision
1563.2.1 by Robert Collins
Merge in a variation of the versionedfile api from versioned-file.
506
        """
1551.6.15 by Aaron Bentley
Moved plan_merge into Weave
507
        raise NotImplementedError(VersionedFile.plan_merge)
508
        
1996.3.7 by John Arbash Meinel
lazy import versionedfile, late-load bzrlib.merge
509
    def weave_merge(self, plan, a_marker=TextMerge.A_MARKER,
1551.6.14 by Aaron Bentley
Tweaks from merge review
510
                    b_marker=TextMerge.B_MARKER):
1551.6.12 by Aaron Bentley
Indicate conflicts from merge_lines, insead of guessing
511
        return PlanWeaveMerge(plan, a_marker, b_marker).merge_lines()[0]
1551.6.10 by Aaron Bentley
Renamed WeaveMerge to PlanMerge, added plan method, created planless WeaveMerge
512
1664.2.7 by Aaron Bentley
Merge bzr.dev
513
3350.6.4 by Robert Collins
First cut at pluralised VersionedFiles. Some rather massive API incompatabilities, primarily because of the difficulty of coherence among competing stores.
514
class RecordingVersionedFilesDecorator(object):
515
    """A minimal versioned files that records calls made on it.
3350.3.4 by Robert Collins
Finish adapters for annotated knits to unannotated knits and full texts.
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):
3871.4.1 by John Arbash Meinel
Add a VFDecorator that can yield records in a specified order
524
        """Create a RecordingVersionedFilesDecorator decorating backing_vf.
3350.3.4 by Robert Collins
Finish adapters for annotated knits to unannotated knits and full texts.
525
        
526
        :param backing_vf: The versioned file to answer all methods.
527
        """
528
        self._backing_vf = backing_vf
529
        self.calls = []
530
3350.8.2 by Robert Collins
stacked get_parent_map.
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
3517.4.19 by Martin Pool
Update test for knit.check() to expect it to recurse into fallback vfs
539
    def check(self):
540
        self._backing_vf.check()
541
3350.8.2 by Robert Collins
stacked get_parent_map.
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
3350.6.4 by Robert Collins
First cut at pluralised VersionedFiles. Some rather massive API incompatabilities, primarily because of the difficulty of coherence among competing stores.
546
    def get_record_stream(self, keys, sort_order, include_delta_closure):
3350.8.7 by Robert Collins
get_record_stream for fulltexts working (but note extreme memory use!).
547
        self.calls.append(("get_record_stream", list(keys), sort_order,
3350.6.4 by Robert Collins
First cut at pluralised VersionedFiles. Some rather massive API incompatabilities, primarily because of the difficulty of coherence among competing stores.
548
            include_delta_closure))
549
        return self._backing_vf.get_record_stream(keys, sort_order,
550
            include_delta_closure)
551
3350.8.3 by Robert Collins
VF.get_sha1s needed changing to be stackable.
552
    def get_sha1s(self, keys):
553
        self.calls.append(("get_sha1s", copy(keys)))
554
        return self._backing_vf.get_sha1s(keys)
555
3350.8.5 by Robert Collins
Iter_lines_added_or_present_in_keys stacks.
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)))
3350.8.14 by Robert Collins
Review feedback.
558
        return self._backing_vf.iter_lines_added_or_present_in_keys(keys, pb=pb)
3350.8.5 by Robert Collins
Iter_lines_added_or_present_in_keys stacks.
559
3350.8.4 by Robert Collins
Vf.keys() stacking support.
560
    def keys(self):
561
        self.calls.append(("keys",))
562
        return self._backing_vf.keys()
563
3350.6.4 by Robert Collins
First cut at pluralised VersionedFiles. Some rather massive API incompatabilities, primarily because of the difficulty of coherence among competing stores.
564
3871.4.1 by John Arbash Meinel
Add a VFDecorator that can yield records in a specified order
565
class OrderingVersionedFilesDecorator(RecordingVersionedFilesDecorator):
566
    """A VF that records calls, and returns keys in specific order.
567
568
    :ivar calls: A list of the calls made; can be reset at any time by
569
        assigning [] to it.
570
    """
571
572
    def __init__(self, backing_vf, key_priority):
573
        """Create a RecordingVersionedFilesDecorator decorating backing_vf.
574
575
        :param backing_vf: The versioned file to answer all methods.
576
        :param key_priority: A dictionary defining what order keys should be
577
            returned from an 'unordered' get_record_stream request.
578
            Keys with lower priority are returned first, keys not present in
579
            the map get an implicit priority of 0, and are returned in
580
            lexicographical order.
581
        """
582
        RecordingVersionedFilesDecorator.__init__(self, backing_vf)
583
        self._key_priority = key_priority
584
585
    def get_record_stream(self, keys, sort_order, include_delta_closure):
586
        self.calls.append(("get_record_stream", list(keys), sort_order,
587
            include_delta_closure))
588
        if sort_order == 'unordered':
589
            def sort_key(key):
590
                return (self._key_priority.get(key, 0), key)
591
            # Use a defined order by asking for the keys one-by-one from the
592
            # backing_vf
593
            for key in sorted(keys, key=sort_key):
594
                for record in self._backing_vf.get_record_stream([key],
595
                                'unordered', include_delta_closure):
596
                    yield record
597
        else:
598
            for record in self._backing_vf.get_record_stream(keys, sort_order,
599
                            include_delta_closure):
600
                yield record
601
602
3350.6.4 by Robert Collins
First cut at pluralised VersionedFiles. Some rather massive API incompatabilities, primarily because of the difficulty of coherence among competing stores.
603
class KeyMapper(object):
3350.6.10 by Martin Pool
VersionedFiles review cleanups
604
    """KeyMappers map between keys and underlying partitioned storage."""
3350.6.4 by Robert Collins
First cut at pluralised VersionedFiles. Some rather massive API incompatabilities, primarily because of the difficulty of coherence among competing stores.
605
606
    def map(self, key):
607
        """Map key to an underlying storage identifier.
608
609
        :param key: A key tuple e.g. ('file-id', 'revision-id').
610
        :return: An underlying storage identifier, specific to the partitioning
611
            mechanism.
612
        """
613
        raise NotImplementedError(self.map)
614
615
    def unmap(self, partition_id):
616
        """Map a partitioned storage id back to a key prefix.
617
        
618
        :param partition_id: The underlying partition id.
3350.6.10 by Martin Pool
VersionedFiles review cleanups
619
        :return: As much of a key (or prefix) as is derivable from the partition
3350.6.4 by Robert Collins
First cut at pluralised VersionedFiles. Some rather massive API incompatabilities, primarily because of the difficulty of coherence among competing stores.
620
            id.
621
        """
622
        raise NotImplementedError(self.unmap)
623
624
625
class ConstantMapper(KeyMapper):
626
    """A key mapper that maps to a constant result."""
627
628
    def __init__(self, result):
629
        """Create a ConstantMapper which will return result for all maps."""
630
        self._result = result
631
632
    def map(self, key):
633
        """See KeyMapper.map()."""
634
        return self._result
635
636
637
class URLEscapeMapper(KeyMapper):
638
    """Base class for use with transport backed storage.
639
640
    This provides a map and unmap wrapper that respectively url escape and
641
    unescape their outputs and inputs.
642
    """
643
644
    def map(self, key):
645
        """See KeyMapper.map()."""
646
        return urllib.quote(self._map(key))
647
648
    def unmap(self, partition_id):
649
        """See KeyMapper.unmap()."""
650
        return self._unmap(urllib.unquote(partition_id))
651
652
653
class PrefixMapper(URLEscapeMapper):
654
    """A key mapper that extracts the first component of a key.
655
    
656
    This mapper is for use with a transport based backend.
657
    """
658
659
    def _map(self, key):
660
        """See KeyMapper.map()."""
661
        return key[0]
662
663
    def _unmap(self, partition_id):
664
        """See KeyMapper.unmap()."""
665
        return (partition_id,)
666
667
668
class HashPrefixMapper(URLEscapeMapper):
669
    """A key mapper that combines the first component of a key with a hash.
670
671
    This mapper is for use with a transport based backend.
672
    """
673
674
    def _map(self, key):
675
        """See KeyMapper.map()."""
676
        prefix = self._escape(key[0])
677
        return "%02x/%s" % (adler32(prefix) & 0xff, prefix)
678
679
    def _escape(self, prefix):
680
        """No escaping needed here."""
681
        return prefix
682
683
    def _unmap(self, partition_id):
684
        """See KeyMapper.unmap()."""
685
        return (self._unescape(osutils.basename(partition_id)),)
686
687
    def _unescape(self, basename):
688
        """No unescaping needed for HashPrefixMapper."""
689
        return basename
690
691
692
class HashEscapedPrefixMapper(HashPrefixMapper):
693
    """Combines the escaped first component of a key with a hash.
694
    
695
    This mapper is for use with a transport based backend.
696
    """
697
698
    _safe = "abcdefghijklmnopqrstuvwxyz0123456789-_@,."
699
700
    def _escape(self, prefix):
701
        """Turn a key element into a filesystem safe string.
702
703
        This is similar to a plain urllib.quote, except
704
        it uses specific safe characters, so that it doesn't
705
        have to translate a lot of valid file ids.
706
        """
707
        # @ does not get escaped. This is because it is a valid
708
        # filesystem character we use all the time, and it looks
709
        # a lot better than seeing %40 all the time.
710
        r = [((c in self._safe) and c or ('%%%02x' % ord(c)))
711
             for c in prefix]
712
        return ''.join(r)
713
714
    def _unescape(self, basename):
715
        """Escaped names are easily unescaped by urlutils."""
716
        return urllib.unquote(basename)
717
718
719
def make_versioned_files_factory(versioned_file_factory, mapper):
720
    """Create a ThunkedVersionedFiles factory.
721
722
    This will create a callable which when called creates a
723
    ThunkedVersionedFiles on a transport, using mapper to access individual
724
    versioned files, and versioned_file_factory to create each individual file.
725
    """
726
    def factory(transport):
727
        return ThunkedVersionedFiles(transport, versioned_file_factory, mapper,
728
            lambda:True)
729
    return factory
730
731
732
class VersionedFiles(object):
733
    """Storage for many versioned files.
734
735
    This object allows a single keyspace for accessing the history graph and
736
    contents of named bytestrings.
737
738
    Currently no implementation allows the graph of different key prefixes to
739
    intersect, but the API does allow such implementations in the future.
3350.6.7 by Robert Collins
Review feedback, making things more clear, adding documentation on what is used where.
740
741
    The keyspace is expressed via simple tuples. Any instance of VersionedFiles
742
    may have a different length key-size, but that size will be constant for
743
    all texts added to or retrieved from it. For instance, bzrlib uses
744
    instances with a key-size of 2 for storing user files in a repository, with
745
    the first element the fileid, and the second the version of that file.
746
747
    The use of tuples allows a single code base to support several different
748
    uses with only the mapping logic changing from instance to instance.
3350.6.4 by Robert Collins
First cut at pluralised VersionedFiles. Some rather massive API incompatabilities, primarily because of the difficulty of coherence among competing stores.
749
    """
750
751
    def add_lines(self, key, parents, lines, parent_texts=None,
752
        left_matching_blocks=None, nostore_sha=None, random_id=False,
753
        check_content=True):
754
        """Add a text to the store.
755
3735.2.5 by Robert Collins
Teach VersionedFiles how to allocate keys based on content hashes.
756
        :param key: The key tuple of the text to add. If the last element is
757
            None, a CHK string will be generated during the addition.
3350.6.4 by Robert Collins
First cut at pluralised VersionedFiles. Some rather massive API incompatabilities, primarily because of the difficulty of coherence among competing stores.
758
        :param parents: The parents key tuples of the text to add.
759
        :param lines: A list of lines. Each line must be a bytestring. And all
760
            of them except the last must be terminated with \n and contain no
761
            other \n's. The last line may either contain no \n's or a single
762
            terminating \n. If the lines list does meet this constraint the add
763
            routine may error or may succeed - but you will be unable to read
764
            the data back accurately. (Checking the lines have been split
765
            correctly is expensive and extremely unlikely to catch bugs so it
766
            is not done at runtime unless check_content is True.)
767
        :param parent_texts: An optional dictionary containing the opaque 
768
            representations of some or all of the parents of version_id to
769
            allow delta optimisations.  VERY IMPORTANT: the texts must be those
770
            returned by add_lines or data corruption can be caused.
771
        :param left_matching_blocks: a hint about which areas are common
772
            between the text and its left-hand-parent.  The format is
773
            the SequenceMatcher.get_matching_blocks format.
774
        :param nostore_sha: Raise ExistingContent and do not add the lines to
775
            the versioned file if the digest of the lines matches this.
776
        :param random_id: If True a random id has been selected rather than
777
            an id determined by some deterministic process such as a converter
778
            from a foreign VCS. When True the backend may choose not to check
779
            for uniqueness of the resulting key within the versioned file, so
780
            this should only be done when the result is expected to be unique
781
            anyway.
782
        :param check_content: If True, the lines supplied are verified to be
783
            bytestrings that are correctly formed lines.
784
        :return: The text sha1, the number of bytes in the text, and an opaque
785
                 representation of the inserted version which can be provided
786
                 back to future add_lines calls in the parent_texts dictionary.
787
        """
788
        raise NotImplementedError(self.add_lines)
789
790
    def add_mpdiffs(self, records):
791
        """Add mpdiffs to this VersionedFile.
792
793
        Records should be iterables of version, parents, expected_sha1,
794
        mpdiff. mpdiff should be a MultiParent instance.
795
        """
796
        vf_parents = {}
797
        mpvf = multiparent.MultiMemoryVersionedFile()
798
        versions = []
799
        for version, parent_ids, expected_sha1, mpdiff in records:
800
            versions.append(version)
801
            mpvf.add_diff(mpdiff, version, parent_ids)
802
        needed_parents = set()
803
        for version, parent_ids, expected_sha1, mpdiff in records:
804
            needed_parents.update(p for p in parent_ids
805
                                  if not mpvf.has_version(p))
806
        # It seems likely that adding all the present parents as fulltexts can
807
        # easily exhaust memory.
808
        split_lines = osutils.split_lines
3350.8.11 by Robert Collins
Stacked add_mpdiffs.
809
        for record in self.get_record_stream(needed_parents, 'unordered',
3350.6.4 by Robert Collins
First cut at pluralised VersionedFiles. Some rather massive API incompatabilities, primarily because of the difficulty of coherence among competing stores.
810
            True):
3350.8.11 by Robert Collins
Stacked add_mpdiffs.
811
            if record.storage_kind == 'absent':
812
                continue
3350.6.4 by Robert Collins
First cut at pluralised VersionedFiles. Some rather massive API incompatabilities, primarily because of the difficulty of coherence among competing stores.
813
            mpvf.add_version(split_lines(record.get_bytes_as('fulltext')),
814
                record.key, [])
815
        for (key, parent_keys, expected_sha1, mpdiff), lines in\
816
            zip(records, mpvf.get_line_list(versions)):
817
            if len(parent_keys) == 1:
818
                left_matching_blocks = list(mpdiff.get_matching_blocks(0,
819
                    mpvf.get_diff(parent_keys[0]).num_lines()))
820
            else:
821
                left_matching_blocks = None
822
            version_sha1, _, version_text = self.add_lines(key,
823
                parent_keys, lines, vf_parents,
824
                left_matching_blocks=left_matching_blocks)
825
            if version_sha1 != expected_sha1:
826
                raise errors.VersionedFileInvalidChecksum(version)
827
            vf_parents[key] = version_text
828
829
    def annotate(self, key):
830
        """Return a list of (version-key, line) tuples for the text of key.
831
832
        :raise RevisionNotPresent: If the key is not present.
833
        """
834
        raise NotImplementedError(self.annotate)
835
836
    def check(self, progress_bar=None):
837
        """Check this object for integrity."""
838
        raise NotImplementedError(self.check)
839
840
    @staticmethod
841
    def check_not_reserved_id(version_id):
842
        revision.check_not_reserved_id(version_id)
843
844
    def _check_lines_not_unicode(self, lines):
845
        """Check that lines being added to a versioned file are not unicode."""
846
        for line in lines:
847
            if line.__class__ is not str:
848
                raise errors.BzrBadParameterUnicode("lines")
849
850
    def _check_lines_are_lines(self, lines):
851
        """Check that the lines really are full lines without inline EOL."""
852
        for line in lines:
853
            if '\n' in line[:-1]:
854
                raise errors.BzrBadParameterContainsNewline("lines")
855
856
    def get_parent_map(self, keys):
857
        """Get a map of the parents of keys.
858
859
        :param keys: The keys to look up parents for.
860
        :return: A mapping from keys to parents. Absent keys are absent from
861
            the mapping.
862
        """
863
        raise NotImplementedError(self.get_parent_map)
864
865
    def get_record_stream(self, keys, ordering, include_delta_closure):
866
        """Get a stream of records for keys.
867
868
        :param keys: The keys to include.
869
        :param ordering: Either 'unordered' or 'topological'. A topologically
870
            sorted stream has compression parents strictly before their
871
            children.
872
        :param include_delta_closure: If True then the closure across any
873
            compression parents will be included (in the opaque data).
874
        :return: An iterator of ContentFactory objects, each of which is only
875
            valid until the iterator is advanced.
876
        """
877
        raise NotImplementedError(self.get_record_stream)
878
879
    def get_sha1s(self, keys):
880
        """Get the sha1's of the texts for the given keys.
881
882
        :param keys: The names of the keys to lookup
3350.8.3 by Robert Collins
VF.get_sha1s needed changing to be stackable.
883
        :return: a dict from key to sha1 digest. Keys of texts which are not
3350.8.14 by Robert Collins
Review feedback.
884
            present in the store are not present in the returned
3350.8.3 by Robert Collins
VF.get_sha1s needed changing to be stackable.
885
            dictionary.
3350.6.4 by Robert Collins
First cut at pluralised VersionedFiles. Some rather massive API incompatabilities, primarily because of the difficulty of coherence among competing stores.
886
        """
887
        raise NotImplementedError(self.get_sha1s)
888
3830.3.12 by Martin Pool
Review cleanups: unify has_key impls, add missing_keys(), clean up exception blocks
889
    has_key = index._has_key_from_parent_map
890
3350.6.4 by Robert Collins
First cut at pluralised VersionedFiles. Some rather massive API incompatabilities, primarily because of the difficulty of coherence among competing stores.
891
    def insert_record_stream(self, stream):
892
        """Insert a record stream into this container.
893
894
        :param stream: A stream of records to insert. 
895
        :return: None
896
        :seealso VersionedFile.get_record_stream:
897
        """
898
        raise NotImplementedError
899
900
    def iter_lines_added_or_present_in_keys(self, keys, pb=None):
901
        """Iterate over the lines in the versioned files from keys.
902
903
        This may return lines from other keys. Each item the returned
904
        iterator yields is a tuple of a line and a text version that that line
905
        is present in (not introduced in).
906
907
        Ordering of results is in whatever order is most suitable for the
908
        underlying storage format.
909
910
        If a progress bar is supplied, it may be used to indicate progress.
911
        The caller is responsible for cleaning up progress bars (because this
912
        is an iterator).
913
914
        NOTES:
915
         * Lines are normalised by the underlying store: they will all have \n
916
           terminators.
917
         * Lines are returned in arbitrary order.
918
919
        :return: An iterator over (line, key).
920
        """
921
        raise NotImplementedError(self.iter_lines_added_or_present_in_keys)
922
923
    def keys(self):
924
        """Return a iterable of the keys for all the contained texts."""
925
        raise NotImplementedError(self.keys)
926
927
    def make_mpdiffs(self, keys):
928
        """Create multiparent diffs for specified keys."""
929
        keys_order = tuple(keys)
930
        keys = frozenset(keys)
931
        knit_keys = set(keys)
932
        parent_map = self.get_parent_map(keys)
933
        for parent_keys in parent_map.itervalues():
934
            if parent_keys:
935
                knit_keys.update(parent_keys)
936
        missing_keys = keys - set(parent_map)
937
        if missing_keys:
3530.3.2 by Robert Collins
Handling frozen set inputs in mpdiff generation when a key is missing
938
            raise errors.RevisionNotPresent(list(missing_keys)[0], self)
3350.6.4 by Robert Collins
First cut at pluralised VersionedFiles. Some rather massive API incompatabilities, primarily because of the difficulty of coherence among competing stores.
939
        # We need to filter out ghosts, because we can't diff against them.
940
        maybe_ghosts = knit_keys - keys
941
        ghosts = maybe_ghosts - set(self.get_parent_map(maybe_ghosts))
942
        knit_keys.difference_update(ghosts)
943
        lines = {}
944
        split_lines = osutils.split_lines
945
        for record in self.get_record_stream(knit_keys, 'topological', True):
946
            lines[record.key] = split_lines(record.get_bytes_as('fulltext'))
947
            # line_block_dict = {}
948
            # for parent, blocks in record.extract_line_blocks():
949
            #   line_blocks[parent] = blocks
950
            # line_blocks[record.key] = line_block_dict
951
        diffs = []
952
        for key in keys_order:
953
            target = lines[key]
954
            parents = parent_map[key] or []
955
            # Note that filtering knit_keys can lead to a parent difference
956
            # between the creation and the application of the mpdiff.
957
            parent_lines = [lines[p] for p in parents if p in knit_keys]
958
            if len(parent_lines) > 0:
959
                left_parent_blocks = self._extract_blocks(key, parent_lines[0],
960
                    target)
961
            else:
962
                left_parent_blocks = None
963
            diffs.append(multiparent.MultiParent.from_lines(target,
964
                parent_lines, left_parent_blocks))
965
        return diffs
966
3830.3.12 by Martin Pool
Review cleanups: unify has_key impls, add missing_keys(), clean up exception blocks
967
    missing_keys = index._missing_keys_from_parent_map
968
3350.6.4 by Robert Collins
First cut at pluralised VersionedFiles. Some rather massive API incompatabilities, primarily because of the difficulty of coherence among competing stores.
969
    def _extract_blocks(self, version_id, source, target):
970
        return None
971
972
973
class ThunkedVersionedFiles(VersionedFiles):
974
    """Storage for many versioned files thunked onto a 'VersionedFile' class.
975
976
    This object allows a single keyspace for accessing the history graph and
977
    contents of named bytestrings.
978
979
    Currently no implementation allows the graph of different key prefixes to
980
    intersect, but the API does allow such implementations in the future.
981
    """
982
983
    def __init__(self, transport, file_factory, mapper, is_locked):
984
        """Create a ThunkedVersionedFiles."""
985
        self._transport = transport
986
        self._file_factory = file_factory
987
        self._mapper = mapper
988
        self._is_locked = is_locked
989
990
    def add_lines(self, key, parents, lines, parent_texts=None,
991
        left_matching_blocks=None, nostore_sha=None, random_id=False,
992
        check_content=True):
993
        """See VersionedFiles.add_lines()."""
994
        path = self._mapper.map(key)
995
        version_id = key[-1]
996
        parents = [parent[-1] for parent in parents]
997
        vf = self._get_vf(path)
998
        try:
999
            try:
1000
                return vf.add_lines_with_ghosts(version_id, parents, lines,
1001
                    parent_texts=parent_texts,
1002
                    left_matching_blocks=left_matching_blocks,
1003
                    nostore_sha=nostore_sha, random_id=random_id,
1004
                    check_content=check_content)
1005
            except NotImplementedError:
1006
                return vf.add_lines(version_id, parents, lines,
1007
                    parent_texts=parent_texts,
1008
                    left_matching_blocks=left_matching_blocks,
1009
                    nostore_sha=nostore_sha, random_id=random_id,
1010
                    check_content=check_content)
1011
        except errors.NoSuchFile:
1012
            # parent directory may be missing, try again.
1013
            self._transport.mkdir(osutils.dirname(path))
1014
            try:
1015
                return vf.add_lines_with_ghosts(version_id, parents, lines,
1016
                    parent_texts=parent_texts,
1017
                    left_matching_blocks=left_matching_blocks,
1018
                    nostore_sha=nostore_sha, random_id=random_id,
1019
                    check_content=check_content)
1020
            except NotImplementedError:
1021
                return vf.add_lines(version_id, parents, lines,
1022
                    parent_texts=parent_texts,
1023
                    left_matching_blocks=left_matching_blocks,
1024
                    nostore_sha=nostore_sha, random_id=random_id,
1025
                    check_content=check_content)
1026
1027
    def annotate(self, key):
1028
        """Return a list of (version-key, line) tuples for the text of key.
1029
1030
        :raise RevisionNotPresent: If the key is not present.
1031
        """
1032
        prefix = key[:-1]
1033
        path = self._mapper.map(prefix)
1034
        vf = self._get_vf(path)
1035
        origins = vf.annotate(key[-1])
1036
        result = []
1037
        for origin, line in origins:
1038
            result.append((prefix + (origin,), line))
1039
        return result
1040
1041
    def check(self, progress_bar=None):
1042
        """See VersionedFiles.check()."""
1043
        for prefix, vf in self._iter_all_components():
1044
            vf.check()
1045
1046
    def get_parent_map(self, keys):
1047
        """Get a map of the parents of keys.
1048
1049
        :param keys: The keys to look up parents for.
1050
        :return: A mapping from keys to parents. Absent keys are absent from
1051
            the mapping.
1052
        """
1053
        prefixes = self._partition_keys(keys)
1054
        result = {}
1055
        for prefix, suffixes in prefixes.items():
1056
            path = self._mapper.map(prefix)
1057
            vf = self._get_vf(path)
1058
            parent_map = vf.get_parent_map(suffixes)
1059
            for key, parents in parent_map.items():
1060
                result[prefix + (key,)] = tuple(
1061
                    prefix + (parent,) for parent in parents)
1062
        return result
1063
1064
    def _get_vf(self, path):
1065
        if not self._is_locked():
1066
            raise errors.ObjectNotLocked(self)
1067
        return self._file_factory(path, self._transport, create=True,
1068
            get_scope=lambda:None)
1069
1070
    def _partition_keys(self, keys):
1071
        """Turn keys into a dict of prefix:suffix_list."""
1072
        result = {}
1073
        for key in keys:
1074
            prefix_keys = result.setdefault(key[:-1], [])
1075
            prefix_keys.append(key[-1])
1076
        return result
1077
1078
    def _get_all_prefixes(self):
1079
        # Identify all key prefixes.
1080
        # XXX: A bit hacky, needs polish.
1081
        if type(self._mapper) == ConstantMapper:
1082
            paths = [self._mapper.map(())]
1083
            prefixes = [()]
1084
        else:
1085
            relpaths = set()
1086
            for quoted_relpath in self._transport.iter_files_recursive():
1087
                path, ext = os.path.splitext(quoted_relpath)
1088
                relpaths.add(path)
1089
            paths = list(relpaths)
1090
            prefixes = [self._mapper.unmap(path) for path in paths]
1091
        return zip(paths, prefixes)
1092
1093
    def get_record_stream(self, keys, ordering, include_delta_closure):
1094
        """See VersionedFiles.get_record_stream()."""
1095
        # Ordering will be taken care of by each partitioned store; group keys
1096
        # by partition.
1097
        keys = sorted(keys)
1098
        for prefix, suffixes, vf in self._iter_keys_vf(keys):
1099
            suffixes = [(suffix,) for suffix in suffixes]
1100
            for record in vf.get_record_stream(suffixes, ordering,
1101
                include_delta_closure):
1102
                if record.parents is not None:
1103
                    record.parents = tuple(
1104
                        prefix + parent for parent in record.parents)
1105
                record.key = prefix + record.key
1106
                yield record
1107
1108
    def _iter_keys_vf(self, keys):
1109
        prefixes = self._partition_keys(keys)
1110
        sha1s = {}
1111
        for prefix, suffixes in prefixes.items():
1112
            path = self._mapper.map(prefix)
1113
            vf = self._get_vf(path)
1114
            yield prefix, suffixes, vf
1115
1116
    def get_sha1s(self, keys):
1117
        """See VersionedFiles.get_sha1s()."""
1118
        sha1s = {}
1119
        for prefix,suffixes, vf in self._iter_keys_vf(keys):
1120
            vf_sha1s = vf.get_sha1s(suffixes)
3350.8.3 by Robert Collins
VF.get_sha1s needed changing to be stackable.
1121
            for suffix, sha1 in vf_sha1s.iteritems():
3350.6.4 by Robert Collins
First cut at pluralised VersionedFiles. Some rather massive API incompatabilities, primarily because of the difficulty of coherence among competing stores.
1122
                sha1s[prefix + (suffix,)] = sha1
3350.8.3 by Robert Collins
VF.get_sha1s needed changing to be stackable.
1123
        return sha1s
3350.6.4 by Robert Collins
First cut at pluralised VersionedFiles. Some rather massive API incompatabilities, primarily because of the difficulty of coherence among competing stores.
1124
1125
    def insert_record_stream(self, stream):
1126
        """Insert a record stream into this container.
1127
1128
        :param stream: A stream of records to insert. 
1129
        :return: None
1130
        :seealso VersionedFile.get_record_stream:
1131
        """
1132
        for record in stream:
1133
            prefix = record.key[:-1]
1134
            key = record.key[-1:]
1135
            if record.parents is not None:
1136
                parents = [parent[-1:] for parent in record.parents]
1137
            else:
1138
                parents = None
1139
            thunk_record = AdapterFactory(key, parents, record)
1140
            path = self._mapper.map(prefix)
1141
            # Note that this parses the file many times; we can do better but
1142
            # as this only impacts weaves in terms of performance, it is
1143
            # tolerable.
1144
            vf = self._get_vf(path)
1145
            vf.insert_record_stream([thunk_record])
1146
1147
    def iter_lines_added_or_present_in_keys(self, keys, pb=None):
1148
        """Iterate over the lines in the versioned files from keys.
1149
1150
        This may return lines from other keys. Each item the returned
1151
        iterator yields is a tuple of a line and a text version that that line
1152
        is present in (not introduced in).
1153
1154
        Ordering of results is in whatever order is most suitable for the
1155
        underlying storage format.
1156
1157
        If a progress bar is supplied, it may be used to indicate progress.
1158
        The caller is responsible for cleaning up progress bars (because this
1159
        is an iterator).
1160
1161
        NOTES:
1162
         * Lines are normalised by the underlying store: they will all have \n
1163
           terminators.
1164
         * Lines are returned in arbitrary order.
1165
1166
        :return: An iterator over (line, key).
1167
        """
1168
        for prefix, suffixes, vf in self._iter_keys_vf(keys):
1169
            for line, version in vf.iter_lines_added_or_present_in_versions(suffixes):
1170
                yield line, prefix + (version,)
1171
1172
    def _iter_all_components(self):
1173
        for path, prefix in self._get_all_prefixes():
1174
            yield prefix, self._get_vf(path)
1175
1176
    def keys(self):
1177
        """See VersionedFiles.keys()."""
1178
        result = set()
1179
        for prefix, vf in self._iter_all_components():
1180
            for suffix in vf.versions():
1181
                result.add(prefix + (suffix,))
1182
        return result
1183
1184
1185
class _PlanMergeVersionedFile(VersionedFiles):
3062.1.9 by Aaron Bentley
Move PlanMerge into merge and _PlanMergeVersionedFile into versionedfile
1186
    """A VersionedFile for uncommitted and committed texts.
1187
1188
    It is intended to allow merges to be planned with working tree texts.
3350.6.4 by Robert Collins
First cut at pluralised VersionedFiles. Some rather massive API incompatabilities, primarily because of the difficulty of coherence among competing stores.
1189
    It implements only the small part of the VersionedFiles interface used by
3062.1.9 by Aaron Bentley
Move PlanMerge into merge and _PlanMergeVersionedFile into versionedfile
1190
    PlanMerge.  It falls back to multiple versionedfiles for data not stored in
1191
    _PlanMergeVersionedFile itself.
3350.6.4 by Robert Collins
First cut at pluralised VersionedFiles. Some rather massive API incompatabilities, primarily because of the difficulty of coherence among competing stores.
1192
1193
    :ivar: fallback_versionedfiles a list of VersionedFiles objects that can be
1194
        queried for missing texts.
3062.1.9 by Aaron Bentley
Move PlanMerge into merge and _PlanMergeVersionedFile into versionedfile
1195
    """
1196
3350.6.4 by Robert Collins
First cut at pluralised VersionedFiles. Some rather massive API incompatabilities, primarily because of the difficulty of coherence among competing stores.
1197
    def __init__(self, file_id):
1198
        """Create a _PlanMergeVersionedFile.
3062.1.9 by Aaron Bentley
Move PlanMerge into merge and _PlanMergeVersionedFile into versionedfile
1199
3350.6.4 by Robert Collins
First cut at pluralised VersionedFiles. Some rather massive API incompatabilities, primarily because of the difficulty of coherence among competing stores.
1200
        :param file_id: Used with _PlanMerge code which is not yet fully
1201
            tuple-keyspace aware.
3062.1.9 by Aaron Bentley
Move PlanMerge into merge and _PlanMergeVersionedFile into versionedfile
1202
        """
1203
        self._file_id = file_id
3350.6.4 by Robert Collins
First cut at pluralised VersionedFiles. Some rather massive API incompatabilities, primarily because of the difficulty of coherence among competing stores.
1204
        # fallback locations
1205
        self.fallback_versionedfiles = []
1206
        # Parents for locally held keys.
3062.1.9 by Aaron Bentley
Move PlanMerge into merge and _PlanMergeVersionedFile into versionedfile
1207
        self._parents = {}
3350.6.4 by Robert Collins
First cut at pluralised VersionedFiles. Some rather massive API incompatabilities, primarily because of the difficulty of coherence among competing stores.
1208
        # line data for locally held keys.
3062.1.9 by Aaron Bentley
Move PlanMerge into merge and _PlanMergeVersionedFile into versionedfile
1209
        self._lines = {}
3350.6.4 by Robert Collins
First cut at pluralised VersionedFiles. Some rather massive API incompatabilities, primarily because of the difficulty of coherence among competing stores.
1210
        # key lookup providers
1211
        self._providers = [DictParentsProvider(self._parents)]
3062.1.9 by Aaron Bentley
Move PlanMerge into merge and _PlanMergeVersionedFile into versionedfile
1212
3062.2.3 by Aaron Bentley
Sync up with bzr.dev API changes
1213
    def plan_merge(self, ver_a, ver_b, base=None):
3062.1.13 by Aaron Bentley
Make _PlanMerge an implementation detail of _PlanMergeVersionedFile
1214
        """See VersionedFile.plan_merge"""
3144.3.7 by Aaron Bentley
Update from review
1215
        from bzrlib.merge import _PlanMerge
3062.2.3 by Aaron Bentley
Sync up with bzr.dev API changes
1216
        if base is None:
3350.6.4 by Robert Collins
First cut at pluralised VersionedFiles. Some rather massive API incompatabilities, primarily because of the difficulty of coherence among competing stores.
1217
            return _PlanMerge(ver_a, ver_b, self, (self._file_id,)).plan_merge()
1218
        old_plan = list(_PlanMerge(ver_a, base, self, (self._file_id,)).plan_merge())
1219
        new_plan = list(_PlanMerge(ver_a, ver_b, self, (self._file_id,)).plan_merge())
3062.2.3 by Aaron Bentley
Sync up with bzr.dev API changes
1220
        return _PlanMerge._subtract_plans(old_plan, new_plan)
1221
3144.3.1 by Aaron Bentley
Implement LCA merge, with problematic conflict markers
1222
    def plan_lca_merge(self, ver_a, ver_b, base=None):
3144.3.7 by Aaron Bentley
Update from review
1223
        from bzrlib.merge import _PlanLCAMerge
3350.6.4 by Robert Collins
First cut at pluralised VersionedFiles. Some rather massive API incompatabilities, primarily because of the difficulty of coherence among competing stores.
1224
        graph = Graph(self)
1225
        new_plan = _PlanLCAMerge(ver_a, ver_b, self, (self._file_id,), graph).plan_merge()
3144.3.1 by Aaron Bentley
Implement LCA merge, with problematic conflict markers
1226
        if base is None:
1227
            return new_plan
3350.6.4 by Robert Collins
First cut at pluralised VersionedFiles. Some rather massive API incompatabilities, primarily because of the difficulty of coherence among competing stores.
1228
        old_plan = _PlanLCAMerge(ver_a, base, self, (self._file_id,), graph).plan_merge()
3144.3.1 by Aaron Bentley
Implement LCA merge, with problematic conflict markers
1229
        return _PlanLCAMerge._subtract_plans(list(old_plan), list(new_plan))
3062.1.13 by Aaron Bentley
Make _PlanMerge an implementation detail of _PlanMergeVersionedFile
1230
3350.6.4 by Robert Collins
First cut at pluralised VersionedFiles. Some rather massive API incompatabilities, primarily because of the difficulty of coherence among competing stores.
1231
    def add_lines(self, key, parents, lines):
1232
        """See VersionedFiles.add_lines
3062.1.9 by Aaron Bentley
Move PlanMerge into merge and _PlanMergeVersionedFile into versionedfile
1233
3350.6.4 by Robert Collins
First cut at pluralised VersionedFiles. Some rather massive API incompatabilities, primarily because of the difficulty of coherence among competing stores.
1234
        Lines are added locally, not to fallback versionedfiles.  Also, ghosts
1235
        are permitted.  Only reserved ids are permitted.
3062.1.9 by Aaron Bentley
Move PlanMerge into merge and _PlanMergeVersionedFile into versionedfile
1236
        """
3350.6.8 by Martin Pool
Change stray pdb calls to exceptions
1237
        if type(key) is not tuple:
1238
            raise TypeError(key)
3350.6.4 by Robert Collins
First cut at pluralised VersionedFiles. Some rather massive API incompatabilities, primarily because of the difficulty of coherence among competing stores.
1239
        if not revision.is_reserved_id(key[-1]):
3062.1.9 by Aaron Bentley
Move PlanMerge into merge and _PlanMergeVersionedFile into versionedfile
1240
            raise ValueError('Only reserved ids may be used')
1241
        if parents is None:
1242
            raise ValueError('Parents may not be None')
1243
        if lines is None:
1244
            raise ValueError('Lines may not be None')
3350.6.4 by Robert Collins
First cut at pluralised VersionedFiles. Some rather massive API incompatabilities, primarily because of the difficulty of coherence among competing stores.
1245
        self._parents[key] = tuple(parents)
1246
        self._lines[key] = lines
3062.1.9 by Aaron Bentley
Move PlanMerge into merge and _PlanMergeVersionedFile into versionedfile
1247
3350.6.4 by Robert Collins
First cut at pluralised VersionedFiles. Some rather massive API incompatabilities, primarily because of the difficulty of coherence among competing stores.
1248
    def get_record_stream(self, keys, ordering, include_delta_closure):
1249
        pending = set(keys)
1250
        for key in keys:
1251
            if key in self._lines:
1252
                lines = self._lines[key]
1253
                parents = self._parents[key]
1254
                pending.remove(key)
1255
                yield FulltextContentFactory(key, parents, None,
1256
                    ''.join(lines))
3062.1.9 by Aaron Bentley
Move PlanMerge into merge and _PlanMergeVersionedFile into versionedfile
1257
        for versionedfile in self.fallback_versionedfiles:
3350.6.4 by Robert Collins
First cut at pluralised VersionedFiles. Some rather massive API incompatabilities, primarily because of the difficulty of coherence among competing stores.
1258
            for record in versionedfile.get_record_stream(
1259
                pending, 'unordered', True):
1260
                if record.storage_kind == 'absent':
3062.1.9 by Aaron Bentley
Move PlanMerge into merge and _PlanMergeVersionedFile into versionedfile
1261
                    continue
3350.6.4 by Robert Collins
First cut at pluralised VersionedFiles. Some rather massive API incompatabilities, primarily because of the difficulty of coherence among competing stores.
1262
                else:
1263
                    pending.remove(record.key)
1264
                    yield record
3287.5.2 by Robert Collins
Deprecate VersionedFile.get_parents, breaking pulling from a ghost containing knit or pack repository to weaves, which improves correctness and allows simplification of core code.
1265
            if not pending:
3350.6.4 by Robert Collins
First cut at pluralised VersionedFiles. Some rather massive API incompatabilities, primarily because of the difficulty of coherence among competing stores.
1266
                return
1267
        # report absent entries
1268
        for key in pending:
1269
            yield AbsentContentFactory(key)
3062.1.9 by Aaron Bentley
Move PlanMerge into merge and _PlanMergeVersionedFile into versionedfile
1270
3350.6.4 by Robert Collins
First cut at pluralised VersionedFiles. Some rather massive API incompatabilities, primarily because of the difficulty of coherence among competing stores.
1271
    def get_parent_map(self, keys):
1272
        """See VersionedFiles.get_parent_map"""
1273
        # We create a new provider because a fallback may have been added.
1274
        # If we make fallbacks private we can update a stack list and avoid
1275
        # object creation thrashing.
3350.6.6 by Robert Collins
Fix test_plan_file_merge
1276
        keys = set(keys)
1277
        result = {}
1278
        if revision.NULL_REVISION in keys:
1279
            keys.remove(revision.NULL_REVISION)
1280
            result[revision.NULL_REVISION] = ()
3350.6.4 by Robert Collins
First cut at pluralised VersionedFiles. Some rather massive API incompatabilities, primarily because of the difficulty of coherence among competing stores.
1281
        self._providers = self._providers[:1] + self.fallback_versionedfiles
3350.6.6 by Robert Collins
Fix test_plan_file_merge
1282
        result.update(
1283
            _StackedParentsProvider(self._providers).get_parent_map(keys))
3350.6.5 by Robert Collins
Update to bzr.dev.
1284
        for key, parents in result.iteritems():
1285
            if parents == ():
1286
                result[key] = (revision.NULL_REVISION,)
3287.5.2 by Robert Collins
Deprecate VersionedFile.get_parents, breaking pulling from a ghost containing knit or pack repository to weaves, which improves correctness and allows simplification of core code.
1287
        return result
3144.3.1 by Aaron Bentley
Implement LCA merge, with problematic conflict markers
1288
3062.1.9 by Aaron Bentley
Move PlanMerge into merge and _PlanMergeVersionedFile into versionedfile
1289
1551.6.10 by Aaron Bentley
Renamed WeaveMerge to PlanMerge, added plan method, created planless WeaveMerge
1290
class PlanWeaveMerge(TextMerge):
1551.6.13 by Aaron Bentley
Cleanup
1291
    """Weave merge that takes a plan as its input.
1292
    
1551.6.14 by Aaron Bentley
Tweaks from merge review
1293
    This exists so that VersionedFile.plan_merge is implementable.
1294
    Most callers will want to use WeaveMerge instead.
1551.6.13 by Aaron Bentley
Cleanup
1295
    """
1296
1551.6.14 by Aaron Bentley
Tweaks from merge review
1297
    def __init__(self, plan, a_marker=TextMerge.A_MARKER,
1298
                 b_marker=TextMerge.B_MARKER):
1551.6.10 by Aaron Bentley
Renamed WeaveMerge to PlanMerge, added plan method, created planless WeaveMerge
1299
        TextMerge.__init__(self, a_marker, b_marker)
1300
        self.plan = plan
1301
1551.6.7 by Aaron Bentley
Implemented two-way merge, refactored weave merge
1302
    def _merge_struct(self):
1563.2.1 by Robert Collins
Merge in a variation of the versionedfile api from versioned-file.
1303
        lines_a = []
1304
        lines_b = []
1305
        ch_a = ch_b = False
1664.2.8 by Aaron Bentley
Fix WeaveMerge when plan doesn't end with unchanged lines
1306
1307
        def outstanding_struct():
1308
            if not lines_a and not lines_b:
1309
                return
1310
            elif ch_a and not ch_b:
1311
                # one-sided change:
1312
                yield(lines_a,)
1313
            elif ch_b and not ch_a:
1314
                yield (lines_b,)
1315
            elif lines_a == lines_b:
1316
                yield(lines_a,)
1317
            else:
1318
                yield (lines_a, lines_b)
1551.6.13 by Aaron Bentley
Cleanup
1319
       
1616.1.18 by Martin Pool
(weave-merge) don't treat killed-both lines as points of agreement;
1320
        # We previously considered either 'unchanged' or 'killed-both' lines
1321
        # to be possible places to resynchronize.  However, assuming agreement
1759.2.1 by Jelmer Vernooij
Fix some types (found using aspell).
1322
        # on killed-both lines may be too aggressive. -- mbp 20060324
1551.6.7 by Aaron Bentley
Implemented two-way merge, refactored weave merge
1323
        for state, line in self.plan:
1616.1.18 by Martin Pool
(weave-merge) don't treat killed-both lines as points of agreement;
1324
            if state == 'unchanged':
1563.2.1 by Robert Collins
Merge in a variation of the versionedfile api from versioned-file.
1325
                # resync and flush queued conflicts changes if any
1664.2.8 by Aaron Bentley
Fix WeaveMerge when plan doesn't end with unchanged lines
1326
                for struct in outstanding_struct():
1327
                    yield struct
1551.6.11 by Aaron Bentley
Switched TextMerge_lines to work on a list
1328
                lines_a = []
1329
                lines_b = []
1563.2.1 by Robert Collins
Merge in a variation of the versionedfile api from versioned-file.
1330
                ch_a = ch_b = False
1331
                
1332
            if state == 'unchanged':
1333
                if line:
1551.6.5 by Aaron Bentley
Got weave merge producing structural output
1334
                    yield ([line],)
1563.2.1 by Robert Collins
Merge in a variation of the versionedfile api from versioned-file.
1335
            elif state == 'killed-a':
1336
                ch_a = True
1337
                lines_b.append(line)
1338
            elif state == 'killed-b':
1339
                ch_b = True
1340
                lines_a.append(line)
1341
            elif state == 'new-a':
1342
                ch_a = True
1343
                lines_a.append(line)
1344
            elif state == 'new-b':
1345
                ch_b = True
1346
                lines_b.append(line)
3144.3.2 by Aaron Bentley
Get conflict handling working
1347
            elif state == 'conflicted-a':
1348
                ch_b = ch_a = True
1349
                lines_a.append(line)
1350
            elif state == 'conflicted-b':
1351
                ch_b = ch_a = True
1352
                lines_b.append(line)
1563.2.1 by Robert Collins
Merge in a variation of the versionedfile api from versioned-file.
1353
            else:
3376.2.4 by Martin Pool
Remove every assert statement from bzrlib!
1354
                if state not in ('irrelevant', 'ghost-a', 'ghost-b',
1355
                        'killed-base', 'killed-both'):
1356
                    raise AssertionError(state)
1664.2.8 by Aaron Bentley
Fix WeaveMerge when plan doesn't end with unchanged lines
1357
        for struct in outstanding_struct():
1358
            yield struct
1563.2.12 by Robert Collins
Checkpointing: created InterObject to factor out common inter object worker code, added InterVersionedFile and tests to allow making join work between any versionedfile.
1359
1664.2.14 by Aaron Bentley
spacing fix
1360
1551.6.10 by Aaron Bentley
Renamed WeaveMerge to PlanMerge, added plan method, created planless WeaveMerge
1361
class WeaveMerge(PlanWeaveMerge):
2831.7.1 by Ian Clatworthy
versionedfile.py code cleanups
1362
    """Weave merge that takes a VersionedFile and two versions as its input."""
1551.6.13 by Aaron Bentley
Cleanup
1363
1551.6.10 by Aaron Bentley
Renamed WeaveMerge to PlanMerge, added plan method, created planless WeaveMerge
1364
    def __init__(self, versionedfile, ver_a, ver_b, 
1551.6.14 by Aaron Bentley
Tweaks from merge review
1365
        a_marker=PlanWeaveMerge.A_MARKER, b_marker=PlanWeaveMerge.B_MARKER):
1551.6.15 by Aaron Bentley
Moved plan_merge into Weave
1366
        plan = versionedfile.plan_merge(ver_a, ver_b)
1551.6.10 by Aaron Bentley
Renamed WeaveMerge to PlanMerge, added plan method, created planless WeaveMerge
1367
        PlanWeaveMerge.__init__(self, plan, a_marker, b_marker)
1368
1369
3518.1.1 by Jelmer Vernooij
Add VirtualVersionedFiles class.
1370
class VirtualVersionedFiles(VersionedFiles):
1371
    """Dummy implementation for VersionedFiles that uses other functions for 
1372
    obtaining fulltexts and parent maps.
1373
1374
    This is always on the bottom of the stack and uses string keys 
1375
    (rather than tuples) internally.
1376
    """
1377
1378
    def __init__(self, get_parent_map, get_lines):
1379
        """Create a VirtualVersionedFiles.
1380
1381
        :param get_parent_map: Same signature as Repository.get_parent_map.
1382
        :param get_lines: Should return lines for specified key or None if 
1383
                          not available.
1384
        """
1385
        super(VirtualVersionedFiles, self).__init__()
1386
        self._get_parent_map = get_parent_map
1387
        self._get_lines = get_lines
1388
        
1389
    def check(self, progressbar=None):
1390
        """See VersionedFiles.check.
1391
1392
        :note: Always returns True for VirtualVersionedFiles.
1393
        """
1394
        return True
1395
1396
    def add_mpdiffs(self, records):
1397
        """See VersionedFiles.mpdiffs.
1398
1399
        :note: Not implemented for VirtualVersionedFiles.
1400
        """
1401
        raise NotImplementedError(self.add_mpdiffs)
1402
1403
    def get_parent_map(self, keys):
1404
        """See VersionedFiles.get_parent_map."""
3518.1.2 by Jelmer Vernooij
Fix some stylistic issues pointed out by Ian.
1405
        return dict([((k,), tuple([(p,) for p in v]))
1406
            for k,v in self._get_parent_map([k for (k,) in keys]).iteritems()])
3518.1.1 by Jelmer Vernooij
Add VirtualVersionedFiles class.
1407
1408
    def get_sha1s(self, keys):
1409
        """See VersionedFiles.get_sha1s."""
1410
        ret = {}
1411
        for (k,) in keys:
1412
            lines = self._get_lines(k)
1413
            if lines is not None:
3518.1.2 by Jelmer Vernooij
Fix some stylistic issues pointed out by Ian.
1414
                if not isinstance(lines, list):
1415
                    raise AssertionError
3518.1.1 by Jelmer Vernooij
Add VirtualVersionedFiles class.
1416
                ret[(k,)] = osutils.sha_strings(lines)
1417
        return ret
1418
1419
    def get_record_stream(self, keys, ordering, include_delta_closure):
1420
        """See VersionedFiles.get_record_stream."""
1421
        for (k,) in list(keys):
1422
            lines = self._get_lines(k)
1423
            if lines is not None:
3518.1.2 by Jelmer Vernooij
Fix some stylistic issues pointed out by Ian.
1424
                if not isinstance(lines, list):
1425
                    raise AssertionError
3518.1.1 by Jelmer Vernooij
Add VirtualVersionedFiles class.
1426
                yield FulltextContentFactory((k,), None, 
1427
                        sha1=osutils.sha_strings(lines),
1428
                        text=''.join(lines))
1429
            else:
1430
                yield AbsentContentFactory((k,))
1431
1432
1433