~bzr-pqm/bzr/bzr.dev

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
4183.7.1 by Sabin Iacob
update FSF mailing address
18
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
1563.2.1 by Robert Collins
Merge in a variation of the versionedfile api from versioned-file.
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
4022.1.6 by Robert Collins
Cherrypick and polish the RemoteSink for streaming push.
25
import struct
3350.6.1 by Robert Collins
* New ``versionedfile.KeyMapper`` interface to abstract out the access to
26
from zlib import adler32
27
1996.3.7 by John Arbash Meinel
lazy import versionedfile, late-load bzrlib.merge
28
from bzrlib.lazy_import import lazy_import
29
lazy_import(globals(), """
3224.5.20 by Andrew Bennetts
Remove or lazyify a couple more imports.
30
import urllib
1996.3.7 by John Arbash Meinel
lazy import versionedfile, late-load bzrlib.merge
31
32
from bzrlib import (
4454.3.65 by John Arbash Meinel
Tests that VF implementations support .get_annotator()
33
    annotate,
1996.3.7 by John Arbash Meinel
lazy import versionedfile, late-load bzrlib.merge
34
    errors,
4593.5.36 by John Arbash Meinel
a few more implementations of the interface.
35
    graph as _mod_graph,
3735.32.18 by John Arbash Meinel
We now support generating a network stream.
36
    groupcompress,
3830.3.12 by Martin Pool
Review cleanups: unify has_key impls, add missing_keys(), clean up exception blocks
37
    index,
4005.3.2 by Robert Collins
First passing NetworkRecordStream test - a fulltext from any record type which isn't a chunked or fulltext can be serialised and deserialised successfully.
38
    knit,
2249.5.12 by John Arbash Meinel
Change the APIs for VersionedFile, Store, and some of Repository into utf-8
39
    osutils,
2520.4.3 by Aaron Bentley
Implement plain strategy for extracting and installing multiparent diffs
40
    multiparent,
1996.3.7 by John Arbash Meinel
lazy import versionedfile, late-load bzrlib.merge
41
    tsort,
2229.2.1 by Aaron Bentley
Reject reserved ids in versiondfile, tree, branch and repository
42
    revision,
1996.3.7 by John Arbash Meinel
lazy import versionedfile, late-load bzrlib.merge
43
    ui,
44
    )
4379.3.3 by Gary van der Merwe
Rename and add doc string for StackedParentsProvider.
45
from bzrlib.graph import DictParentsProvider, Graph, StackedParentsProvider
1996.3.7 by John Arbash Meinel
lazy import versionedfile, late-load bzrlib.merge
46
from bzrlib.transport.memory import MemoryTransport
47
""")
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.
48
from bzrlib.inter import InterObject
3350.3.7 by Robert Collins
Create a registry of versioned file record adapters.
49
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.
50
from bzrlib.symbol_versioning import *
1551.6.7 by Aaron Bentley
Implemented two-way merge, refactored weave merge
51
from bzrlib.textmerge import TextMerge
2694.5.4 by Jelmer Vernooij
Move bzrlib.util.bencode to bzrlib._bencode_py.
52
from bzrlib import bencode
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.
53
54
3350.3.7 by Robert Collins
Create a registry of versioned file record adapters.
55
adapter_registry = Registry()
56
adapter_registry.register_lazy(('knit-delta-gz', 'fulltext'), 'bzrlib.knit',
57
    'DeltaPlainToFullText')
58
adapter_registry.register_lazy(('knit-ft-gz', 'fulltext'), 'bzrlib.knit',
59
    'FTPlainToFullText')
60
adapter_registry.register_lazy(('knit-annotated-delta-gz', 'knit-delta-gz'),
61
    'bzrlib.knit', 'DeltaAnnotatedToUnannotated')
62
adapter_registry.register_lazy(('knit-annotated-delta-gz', 'fulltext'),
63
    'bzrlib.knit', 'DeltaAnnotatedToFullText')
64
adapter_registry.register_lazy(('knit-annotated-ft-gz', 'knit-ft-gz'),
65
    'bzrlib.knit', 'FTAnnotatedToUnannotated')
66
adapter_registry.register_lazy(('knit-annotated-ft-gz', 'fulltext'),
67
    'bzrlib.knit', 'FTAnnotatedToFullText')
3890.2.1 by John Arbash Meinel
Start working on a ChunkedContentFactory.
68
# adapter_registry.register_lazy(('knit-annotated-ft-gz', 'chunked'),
69
#     'bzrlib.knit', 'FTAnnotatedToChunked')
3350.3.7 by Robert Collins
Create a registry of versioned file record adapters.
70
71
3350.3.3 by Robert Collins
Functional get_record_stream interface tests covering full interface.
72
class ContentFactory(object):
73
    """Abstract interface for insertion and retrieval from a VersionedFile.
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
74
3350.3.3 by Robert Collins
Functional get_record_stream interface tests covering full interface.
75
    :ivar sha1: None, or the sha1 of the content fulltext.
76
    :ivar storage_kind: The native storage kind of this factory. One of
77
        'mpdiff', 'knit-annotated-ft', 'knit-annotated-delta', 'knit-ft',
78
        'knit-delta', 'fulltext', 'knit-annotated-ft-gz',
79
        'knit-annotated-delta-gz', 'knit-ft-gz', 'knit-delta-gz'.
80
    :ivar key: The key of this content. Each key is a tuple with a single
81
        string in it.
82
    :ivar parents: A tuple of parent keys for self.key. If the object has
83
        no parent information, None (as opposed to () for an empty list of
84
        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.
85
    """
3350.3.3 by Robert Collins
Functional get_record_stream interface tests covering full interface.
86
87
    def __init__(self):
88
        """Create a ContentFactory."""
89
        self.sha1 = None
90
        self.storage_kind = None
91
        self.key = None
92
        self.parents = None
93
94
3890.2.1 by John Arbash Meinel
Start working on a ChunkedContentFactory.
95
class ChunkedContentFactory(ContentFactory):
96
    """Static data content factory.
97
98
    This takes a 'chunked' list of strings. The only requirement on 'chunked' is
99
    that ''.join(lines) becomes a valid fulltext. A tuple of a single string
100
    satisfies this, as does a list of lines.
101
102
    :ivar sha1: None, or the sha1 of the content fulltext.
103
    :ivar storage_kind: The native storage kind of this factory. Always
3890.2.2 by John Arbash Meinel
Change the signature to report the storage kind as 'chunked'
104
        'chunked'
3890.2.1 by John Arbash Meinel
Start working on a ChunkedContentFactory.
105
    :ivar key: The key of this content. Each key is a tuple with a single
106
        string in it.
107
    :ivar parents: A tuple of parent keys for self.key. If the object has
108
        no parent information, None (as opposed to () for an empty list of
109
        parents).
110
     """
111
112
    def __init__(self, key, parents, sha1, chunks):
113
        """Create a ContentFactory."""
114
        self.sha1 = sha1
3890.2.2 by John Arbash Meinel
Change the signature to report the storage kind as 'chunked'
115
        self.storage_kind = 'chunked'
3890.2.1 by John Arbash Meinel
Start working on a ChunkedContentFactory.
116
        self.key = key
117
        self.parents = parents
118
        self._chunks = chunks
119
120
    def get_bytes_as(self, storage_kind):
121
        if storage_kind == 'chunked':
122
            return self._chunks
123
        elif storage_kind == 'fulltext':
124
            return ''.join(self._chunks)
125
        raise errors.UnavailableRepresentation(self.key, storage_kind,
126
            self.storage_kind)
127
128
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.
129
class FulltextContentFactory(ContentFactory):
130
    """Static data content factory.
131
132
    This takes a fulltext when created and just returns that during
133
    get_bytes_as('fulltext').
3890.2.1 by John Arbash Meinel
Start working on a ChunkedContentFactory.
134
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.
135
    :ivar sha1: None, or the sha1 of the content fulltext.
136
    :ivar storage_kind: The native storage kind of this factory. Always
137
        'fulltext'.
138
    :ivar key: The key of this content. Each key is a tuple with a single
139
        string in it.
140
    :ivar parents: A tuple of parent keys for self.key. If the object has
141
        no parent information, None (as opposed to () for an empty list of
142
        parents).
143
     """
144
145
    def __init__(self, key, parents, sha1, text):
146
        """Create a ContentFactory."""
147
        self.sha1 = sha1
148
        self.storage_kind = 'fulltext'
149
        self.key = key
150
        self.parents = parents
151
        self._text = text
152
153
    def get_bytes_as(self, storage_kind):
154
        if storage_kind == self.storage_kind:
155
            return self._text
3890.2.1 by John Arbash Meinel
Start working on a ChunkedContentFactory.
156
        elif storage_kind == 'chunked':
3976.2.1 by Robert Collins
Use a list not a tuple for chunks returned from FullTextContentFactory objects, because otherwise code tries to assign to tuples.
157
            return [self._text]
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.
158
        raise errors.UnavailableRepresentation(self.key, storage_kind,
159
            self.storage_kind)
160
161
162
class AbsentContentFactory(ContentFactory):
3350.3.12 by Robert Collins
Generate streams with absent records.
163
    """A placeholder content factory for unavailable texts.
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
164
3350.3.12 by Robert Collins
Generate streams with absent records.
165
    :ivar sha1: None.
166
    :ivar storage_kind: 'absent'.
167
    :ivar key: The key of this content. Each key is a tuple with a single
168
        string in it.
169
    :ivar parents: None.
170
    """
171
172
    def __init__(self, key):
173
        """Create a ContentFactory."""
174
        self.sha1 = None
175
        self.storage_kind = 'absent'
176
        self.key = key
177
        self.parents = None
178
4537.2.1 by John Arbash Meinel
Add AbsentContentFactory.get_bytes_as()
179
    def get_bytes_as(self, storage_kind):
180
        raise ValueError('A request was made for key: %s, but that'
181
                         ' content is not available, and the calling'
182
                         ' code does not handle if it is missing.'
183
                         % (self.key,))
184
3350.3.12 by Robert Collins
Generate streams with absent records.
185
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.
186
class AdapterFactory(ContentFactory):
187
    """A content factory to adapt between key prefix's."""
188
189
    def __init__(self, key, parents, adapted):
190
        """Create an adapter factory instance."""
191
        self.key = key
192
        self.parents = parents
193
        self._adapted = adapted
194
195
    def __getattr__(self, attr):
196
        """Return a member from the adapted object."""
197
        if attr in ('key', 'parents'):
198
            return self.__dict__[attr]
199
        else:
200
            return getattr(self._adapted, attr)
201
202
3350.3.14 by Robert Collins
Deprecate VersionedFile.join.
203
def filter_absent(record_stream):
204
    """Adapt a record stream to remove absent records."""
205
    for record in record_stream:
206
        if record.storage_kind != 'absent':
207
            yield record
208
209
1563.2.1 by Robert Collins
Merge in a variation of the versionedfile api from versioned-file.
210
class VersionedFile(object):
211
    """Versioned text file storage.
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
212
1563.2.1 by Robert Collins
Merge in a variation of the versionedfile api from versioned-file.
213
    A versioned file manages versions of line-based text files,
214
    keeping track of the originating version for each line.
215
216
    To clients the "lines" of the file are represented as a list of
217
    strings. These strings will typically have terminal newline
218
    characters, but this is not required.  In particular files commonly
219
    do not have a newline at the end of the file.
220
221
    Texts are identified by a version-id string.
222
    """
223
2229.2.1 by Aaron Bentley
Reject reserved ids in versiondfile, tree, branch and repository
224
    @staticmethod
2229.2.3 by Aaron Bentley
change reserved_id to is_reserved_id, add check_not_reserved for DRY
225
    def check_not_reserved_id(version_id):
226
        revision.check_not_reserved_id(version_id)
2229.2.1 by Aaron Bentley
Reject reserved ids in versiondfile, tree, branch and repository
227
1563.2.15 by Robert Collins
remove the weavestore assumptions about the number and nature of files it manages.
228
    def copy_to(self, name, transport):
229
        """Copy this versioned file to name on transport."""
230
        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
231
3350.3.3 by Robert Collins
Functional get_record_stream interface tests covering full interface.
232
    def get_record_stream(self, versions, ordering, include_delta_closure):
233
        """Get a stream of records for versions.
234
235
        :param versions: The versions to include. Each version is a tuple
236
            (version,).
237
        :param ordering: Either 'unordered' or 'topological'. A topologically
238
            sorted stream has compression parents strictly before their
239
            children.
240
        :param include_delta_closure: If True then the closure across any
3350.3.22 by Robert Collins
Review feedback.
241
            compression parents will be included (in the data content of the
242
            stream, not in the emitted records). This guarantees that
243
            'fulltext' can be used successfully on every record.
3350.3.3 by Robert Collins
Functional get_record_stream interface tests covering full interface.
244
        :return: An iterator of ContentFactory objects, each of which is only
245
            valid until the iterator is advanced.
246
        """
247
        raise NotImplementedError(self.get_record_stream)
1563.2.1 by Robert Collins
Merge in a variation of the versionedfile api from versioned-file.
248
249
    def has_version(self, version_id):
250
        """Returns whether version is present."""
251
        raise NotImplementedError(self.has_version)
252
3350.3.8 by Robert Collins
Basic stream insertion, no fast path yet for knit to knit.
253
    def insert_record_stream(self, stream):
254
        """Insert a record stream into this versioned file.
255
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
256
        :param stream: A stream of records to insert.
3350.3.8 by Robert Collins
Basic stream insertion, no fast path yet for knit to knit.
257
        :return: None
258
        :seealso VersionedFile.get_record_stream:
259
        """
260
        raise NotImplementedError
261
2520.4.140 by Aaron Bentley
Use matching blocks from mpdiff for knit delta creation
262
    def add_lines(self, version_id, parents, lines, parent_texts=None,
2805.6.7 by Robert Collins
Review feedback.
263
        left_matching_blocks=None, nostore_sha=None, random_id=False,
264
        check_content=True):
1563.2.1 by Robert Collins
Merge in a variation of the versionedfile api from versioned-file.
265
        """Add a single text on top of the versioned file.
266
267
        Must raise RevisionAlreadyPresent if the new version is
268
        already present in file history.
269
270
        Must raise RevisionNotPresent if any of the given parents are
1594.2.21 by Robert Collins
Teach versioned files to prevent mutation after finishing.
271
        not present in file history.
2805.6.3 by Robert Collins
* The ``VersionedFile`` interface no longer protects against misuse when
272
273
        :param lines: A list of lines. Each line must be a bytestring. And all
274
            of them except the last must be terminated with \n and contain no
275
            other \n's. The last line may either contain no \n's or a single
276
            terminated \n. If the lines list does meet this constraint the add
277
            routine may error or may succeed - but you will be unable to read
278
            the data back accurately. (Checking the lines have been split
2805.6.7 by Robert Collins
Review feedback.
279
            correctly is expensive and extremely unlikely to catch bugs so it
280
            is not done at runtime unless check_content is True.)
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
281
        :param parent_texts: An optional dictionary containing the opaque
2805.6.3 by Robert Collins
* The ``VersionedFile`` interface no longer protects against misuse when
282
            representations of some or all of the parents of version_id to
283
            allow delta optimisations.  VERY IMPORTANT: the texts must be those
284
            returned by add_lines or data corruption can be caused.
2520.4.148 by Aaron Bentley
Updates from review
285
        :param left_matching_blocks: a hint about which areas are common
286
            between the text and its left-hand-parent.  The format is
287
            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.
288
        :param nostore_sha: Raise ExistingContent and do not add the lines to
289
            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.
290
        :param random_id: If True a random id has been selected rather than
291
            an id determined by some deterministic process such as a converter
292
            from a foreign VCS. When True the backend may choose not to check
293
            for uniqueness of the resulting key within the versioned file, so
294
            this should only be done when the result is expected to be unique
295
            anyway.
2805.6.7 by Robert Collins
Review feedback.
296
        :param check_content: If True, the lines supplied are verified to be
297
            bytestrings that are correctly formed lines.
2776.1.1 by Robert Collins
* The ``add_lines`` methods on ``VersionedFile`` implementations has changed
298
        :return: The text sha1, the number of bytes in the text, and an opaque
299
                 representation of the inserted version which can be provided
300
                 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.
301
        """
1594.2.23 by Robert Collins
Test versioned file storage handling of clean/dirty status for accessed versioned files.
302
        self._check_write_ok()
2520.4.140 by Aaron Bentley
Use matching blocks from mpdiff for knit delta creation
303
        return self._add_lines(version_id, parents, lines, parent_texts,
2805.6.7 by Robert Collins
Review feedback.
304
            left_matching_blocks, nostore_sha, random_id, check_content)
1594.2.21 by Robert Collins
Teach versioned files to prevent mutation after finishing.
305
2520.4.140 by Aaron Bentley
Use matching blocks from mpdiff for knit delta creation
306
    def _add_lines(self, version_id, parents, lines, parent_texts,
2805.6.7 by Robert Collins
Review feedback.
307
        left_matching_blocks, nostore_sha, random_id, check_content):
1594.2.21 by Robert Collins
Teach versioned files to prevent mutation after finishing.
308
        """Helper to do the class specific add_lines."""
1563.2.4 by Robert Collins
First cut at including the knit implementation of versioned_file.
309
        raise NotImplementedError(self.add_lines)
1563.2.1 by Robert Collins
Merge in a variation of the versionedfile api from versioned-file.
310
1596.2.32 by Robert Collins
Reduce re-extraction of texts during weave to knit joins by providing a memoisation facility.
311
    def add_lines_with_ghosts(self, version_id, parents, lines,
2805.6.7 by Robert Collins
Review feedback.
312
        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.
313
        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.
314
        """Add lines to the versioned file, allowing ghosts to be present.
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
315
2794.1.1 by Robert Collins
Allow knits to be instructed not to add a text based on a sha, for commit.
316
        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.
317
        """
1594.2.23 by Robert Collins
Test versioned file storage handling of clean/dirty status for accessed versioned files.
318
        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.
319
        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.
320
            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.
321
2794.1.1 by Robert Collins
Allow knits to be instructed not to add a text based on a sha, for commit.
322
    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.
323
        nostore_sha, random_id, check_content, left_matching_blocks):
1594.2.21 by Robert Collins
Teach versioned files to prevent mutation after finishing.
324
        """Helper to do class specific add_lines_with_ghosts."""
1594.2.8 by Robert Collins
add ghost aware apis to knits.
325
        raise NotImplementedError(self.add_lines_with_ghosts)
326
1563.2.19 by Robert Collins
stub out a check for knits.
327
    def check(self, progress_bar=None):
328
        """Check the versioned file for integrity."""
329
        raise NotImplementedError(self.check)
330
1666.1.6 by Robert Collins
Make knit the default format.
331
    def _check_lines_not_unicode(self, lines):
332
        """Check that lines being added to a versioned file are not unicode."""
333
        for line in lines:
334
            if line.__class__ is not str:
335
                raise errors.BzrBadParameterUnicode("lines")
336
337
    def _check_lines_are_lines(self, lines):
338
        """Check that the lines really are full lines without inline EOL."""
339
        for line in lines:
340
            if '\n' in line[:-1]:
341
                raise errors.BzrBadParameterContainsNewline("lines")
342
2535.3.1 by Andrew Bennetts
Add get_format_signature to VersionedFile
343
    def get_format_signature(self):
344
        """Get a text description of the data encoding in this file.
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
345
2831.7.1 by Ian Clatworthy
versionedfile.py code cleanups
346
        :since: 0.90
2535.3.1 by Andrew Bennetts
Add get_format_signature to VersionedFile
347
        """
348
        raise NotImplementedError(self.get_format_signature)
349
2520.4.41 by Aaron Bentley
Accelerate mpdiff generation
350
    def make_mpdiffs(self, version_ids):
2831.7.1 by Ian Clatworthy
versionedfile.py code cleanups
351
        """Create multiparent diffs for specified versions."""
2520.4.41 by Aaron Bentley
Accelerate mpdiff generation
352
        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.
353
        knit_versions.update(version_ids)
354
        parent_map = self.get_parent_map(version_ids)
2520.4.41 by Aaron Bentley
Accelerate mpdiff generation
355
        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.
356
            try:
357
                knit_versions.update(parent_map[version_id])
358
            except KeyError:
3453.3.1 by Daniel Fischer
Raise the right exception in make_mpdiffs (bug #235687)
359
                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.
360
        # We need to filter out ghosts, because we can't diff against them.
361
        knit_versions = set(self.get_parent_map(knit_versions).keys())
2520.4.90 by Aaron Bentley
Handle \r terminated lines in Weaves properly
362
        lines = dict(zip(knit_versions,
363
            self._get_lf_split_line_list(knit_versions)))
2520.4.41 by Aaron Bentley
Accelerate mpdiff generation
364
        diffs = []
365
        for version_id in version_ids:
366
            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.
367
            try:
368
                parents = [lines[p] for p in parent_map[version_id] if p in
369
                    knit_versions]
370
            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
371
                # I don't know how this could ever trigger.
372
                # parent_map[version_id] was already triggered in the previous
373
                # for loop, and lines[p] has the 'if p in knit_versions' check,
374
                # so we again won't have a KeyError.
3453.3.1 by Daniel Fischer
Raise the right exception in make_mpdiffs (bug #235687)
375
                raise errors.RevisionNotPresent(version_id, self)
2520.4.48 by Aaron Bentley
Support getting blocks from knit deltas with no final EOL
376
            if len(parents) > 0:
377
                left_parent_blocks = self._extract_blocks(version_id,
378
                                                          parents[0], target)
379
            else:
380
                left_parent_blocks = None
2520.4.41 by Aaron Bentley
Accelerate mpdiff generation
381
            diffs.append(multiparent.MultiParent.from_lines(target, parents,
382
                         left_parent_blocks))
383
        return diffs
384
2520.4.48 by Aaron Bentley
Support getting blocks from knit deltas with no final EOL
385
    def _extract_blocks(self, version_id, source, target):
2520.4.41 by Aaron Bentley
Accelerate mpdiff generation
386
        return None
2520.4.3 by Aaron Bentley
Implement plain strategy for extracting and installing multiparent diffs
387
2520.4.61 by Aaron Bentley
Do bulk insertion of records
388
    def add_mpdiffs(self, records):
2831.7.1 by Ian Clatworthy
versionedfile.py code cleanups
389
        """Add mpdiffs to this VersionedFile.
2520.4.126 by Aaron Bentley
Add more docs
390
391
        Records should be iterables of version, parents, expected_sha1,
2831.7.1 by Ian Clatworthy
versionedfile.py code cleanups
392
        mpdiff. mpdiff should be a MultiParent instance.
2520.4.126 by Aaron Bentley
Add more docs
393
        """
2831.7.1 by Ian Clatworthy
versionedfile.py code cleanups
394
        # Does this need to call self._check_write_ok()? (IanC 20070919)
2520.4.61 by Aaron Bentley
Do bulk insertion of records
395
        vf_parents = {}
2520.4.141 by Aaron Bentley
More batch operations adding mpdiffs
396
        mpvf = multiparent.MultiMemoryVersionedFile()
397
        versions = []
398
        for version, parent_ids, expected_sha1, mpdiff in records:
399
            versions.append(version)
400
            mpvf.add_diff(mpdiff, version, parent_ids)
401
        needed_parents = set()
2520.4.142 by Aaron Bentley
Clean up installation of inventory records
402
        for version, parent_ids, expected_sha1, mpdiff in records:
2520.4.141 by Aaron Bentley
More batch operations adding mpdiffs
403
            needed_parents.update(p for p in parent_ids
404
                                  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.
405
        present_parents = set(self.get_parent_map(needed_parents).keys())
406
        for parent_id, lines in zip(present_parents,
407
                                 self._get_lf_split_line_list(present_parents)):
2520.4.141 by Aaron Bentley
More batch operations adding mpdiffs
408
            mpvf.add_version(lines, parent_id, [])
409
        for (version, parent_ids, expected_sha1, mpdiff), lines in\
410
            zip(records, mpvf.get_line_list(versions)):
411
            if len(parent_ids) == 1:
2520.4.140 by Aaron Bentley
Use matching blocks from mpdiff for knit delta creation
412
                left_matching_blocks = list(mpdiff.get_matching_blocks(0,
2520.4.141 by Aaron Bentley
More batch operations adding mpdiffs
413
                    mpvf.get_diff(parent_ids[0]).num_lines()))
2520.4.140 by Aaron Bentley
Use matching blocks from mpdiff for knit delta creation
414
            else:
415
                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.
416
            try:
417
                _, _, version_text = self.add_lines_with_ghosts(version,
418
                    parent_ids, lines, vf_parents,
419
                    left_matching_blocks=left_matching_blocks)
420
            except NotImplementedError:
421
                # The vf can't handle ghosts, so add lines normally, which will
422
                # (reasonably) fail if there are ghosts in the data.
423
                _, _, version_text = self.add_lines(version,
424
                    parent_ids, lines, vf_parents,
425
                    left_matching_blocks=left_matching_blocks)
2520.4.61 by Aaron Bentley
Do bulk insertion of records
426
            vf_parents[version] = version_text
3350.8.3 by Robert Collins
VF.get_sha1s needed changing to be stackable.
427
        sha1s = self.get_sha1s(versions)
428
        for version, parent_ids, expected_sha1, mpdiff in records:
429
            if expected_sha1 != sha1s[version]:
2520.4.71 by Aaron Bentley
Update test to accept VersionedFileInvalidChecksum instead of TestamentMismatch
430
                raise errors.VersionedFileInvalidChecksum(version)
2520.4.3 by Aaron Bentley
Implement plain strategy for extracting and installing multiparent diffs
431
1563.2.1 by Robert Collins
Merge in a variation of the versionedfile api from versioned-file.
432
    def get_text(self, version_id):
433
        """Return version contents as a text string.
434
435
        Raises RevisionNotPresent if version is not present in
436
        file history.
437
        """
438
        return ''.join(self.get_lines(version_id))
439
    get_string = get_text
440
1756.2.1 by Aaron Bentley
Implement get_texts
441
    def get_texts(self, version_ids):
442
        """Return the texts of listed versions as a list of strings.
443
444
        Raises RevisionNotPresent if version is not present in
445
        file history.
446
        """
447
        return [''.join(self.get_lines(v)) for v in version_ids]
448
1563.2.1 by Robert Collins
Merge in a variation of the versionedfile api from versioned-file.
449
    def get_lines(self, version_id):
450
        """Return version contents as a sequence of lines.
451
452
        Raises RevisionNotPresent if version is not present in
453
        file history.
454
        """
455
        raise NotImplementedError(self.get_lines)
456
2520.4.90 by Aaron Bentley
Handle \r terminated lines in Weaves properly
457
    def _get_lf_split_line_list(self, version_ids):
458
        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
459
2530.1.1 by Aaron Bentley
Make topological sorting optional for get_ancestry
460
    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.
461
        """Return a list of all ancestors of given version(s). This
462
        will not include the null revision.
463
2490.2.32 by Aaron Bentley
Merge of not-sorting-ancestry branch
464
        This list will not be topologically sorted if topo_sorted=False is
465
        passed.
2530.1.1 by Aaron Bentley
Make topological sorting optional for get_ancestry
466
1563.2.1 by Robert Collins
Merge in a variation of the versionedfile api from versioned-file.
467
        Must raise RevisionNotPresent if any of the given versions are
468
        not present in file history."""
469
        if isinstance(version_ids, basestring):
470
            version_ids = [version_ids]
471
        raise NotImplementedError(self.get_ancestry)
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
472
1594.2.8 by Robert Collins
add ghost aware apis to knits.
473
    def get_ancestry_with_ghosts(self, version_ids):
474
        """Return a list of all ancestors of given version(s). This
475
        will not include the null revision.
476
477
        Must raise RevisionNotPresent if any of the given versions are
478
        not present in file history.
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
479
1594.2.8 by Robert Collins
add ghost aware apis to knits.
480
        Ghosts that are known about will be included in ancestry list,
481
        but are not explicitly marked.
482
        """
483
        raise NotImplementedError(self.get_ancestry_with_ghosts)
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
484
3287.5.1 by Robert Collins
Add VersionedFile.get_parent_map.
485
    def get_parent_map(self, version_ids):
486
        """Get a map of the parents of version_ids.
487
488
        :param version_ids: The version ids to look up parents for.
489
        :return: A mapping from version id to parents.
490
        """
491
        raise NotImplementedError(self.get_parent_map)
492
1594.2.8 by Robert Collins
add ghost aware apis to knits.
493
    def get_parents_with_ghosts(self, version_id):
494
        """Return version names for parents of version_id.
495
496
        Will raise RevisionNotPresent if version_id is not present
497
        in the history.
498
499
        Ghosts that are known about will be included in the parent list,
500
        but are not explicitly marked.
501
        """
3287.5.1 by Robert Collins
Add VersionedFile.get_parent_map.
502
        try:
503
            return list(self.get_parent_map([version_id])[version_id])
504
        except KeyError:
505
            raise errors.RevisionNotPresent(version_id, self)
1594.2.8 by Robert Collins
add ghost aware apis to knits.
506
1563.2.1 by Robert Collins
Merge in a variation of the versionedfile api from versioned-file.
507
    def annotate(self, version_id):
3316.2.13 by Robert Collins
* ``VersionedFile.annotate_iter`` is deprecated. While in principal this
508
        """Return a list of (version-id, line) tuples for version_id.
509
510
        :raise RevisionNotPresent: If the given version is
511
        not present in file history.
512
        """
513
        raise NotImplementedError(self.annotate)
1563.2.1 by Robert Collins
Merge in a variation of the versionedfile api from versioned-file.
514
2975.3.2 by Robert Collins
Review feedback - document the API change and improve readability in pack's _do_copy_nodes.
515
    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)
516
                                                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.
517
        """Iterate over the lines in the versioned file from version_ids.
518
2975.3.2 by Robert Collins
Review feedback - document the API change and improve readability in pack's _do_copy_nodes.
519
        This may return lines from other versions. Each item the returned
520
        iterator yields is a tuple of a line and a text version that that line
521
        is present in (not introduced in).
522
523
        Ordering of results is in whatever order is most suitable for the
524
        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.
525
2039.1.1 by Aaron Bentley
Clean up progress properly when interrupted during fetch (#54000)
526
        If a progress bar is supplied, it may be used to indicate progress.
527
        The caller is responsible for cleaning up progress bars (because this
528
        is an iterator).
529
1594.2.6 by Robert Collins
Introduce a api specifically for looking at lines in some versions of the inventory, for fileid_involved.
530
        NOTES: Lines are normalised: they will all have \n terminators.
531
               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.
532
533
        :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.
534
        """
535
        raise NotImplementedError(self.iter_lines_added_or_present_in_versions)
536
1551.6.15 by Aaron Bentley
Moved plan_merge into Weave
537
    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.
538
        """Return pseudo-annotation indicating how the two versions merge.
539
540
        This is computed between versions a and b and their common
541
        base.
542
543
        Weave lines present in none of them are skipped entirely.
1664.2.2 by Aaron Bentley
Added legend for plan-merge output
544
545
        Legend:
546
        killed-base Dead in base revision
547
        killed-both Killed in each revision
548
        killed-a    Killed in a
549
        killed-b    Killed in b
550
        unchanged   Alive in both a and b (possibly created in both)
551
        new-a       Created in a
552
        new-b       Created in b
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
553
        ghost-a     Killed in a, unborn in b
1664.2.5 by Aaron Bentley
Update plan-merge legend
554
        ghost-b     Killed in b, unborn in a
1664.2.2 by Aaron Bentley
Added legend for plan-merge output
555
        irrelevant  Not in either revision
1563.2.1 by Robert Collins
Merge in a variation of the versionedfile api from versioned-file.
556
        """
1551.6.15 by Aaron Bentley
Moved plan_merge into Weave
557
        raise NotImplementedError(VersionedFile.plan_merge)
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
558
1996.3.7 by John Arbash Meinel
lazy import versionedfile, late-load bzrlib.merge
559
    def weave_merge(self, plan, a_marker=TextMerge.A_MARKER,
1551.6.14 by Aaron Bentley
Tweaks from merge review
560
                    b_marker=TextMerge.B_MARKER):
1551.6.12 by Aaron Bentley
Indicate conflicts from merge_lines, insead of guessing
561
        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
562
1664.2.7 by Aaron Bentley
Merge bzr.dev
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
class RecordingVersionedFilesDecorator(object):
565
    """A minimal versioned files that records calls made on it.
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
566
3350.3.4 by Robert Collins
Finish adapters for annotated knits to unannotated knits and full texts.
567
    Only enough methods have been added to support tests using it to date.
568
569
    :ivar calls: A list of the calls made; can be reset at any time by
570
        assigning [] to it.
571
    """
572
573
    def __init__(self, backing_vf):
3871.4.1 by John Arbash Meinel
Add a VFDecorator that can yield records in a specified order
574
        """Create a RecordingVersionedFilesDecorator decorating backing_vf.
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
575
3350.3.4 by Robert Collins
Finish adapters for annotated knits to unannotated knits and full texts.
576
        :param backing_vf: The versioned file to answer all methods.
577
        """
578
        self._backing_vf = backing_vf
579
        self.calls = []
580
3350.8.2 by Robert Collins
stacked get_parent_map.
581
    def add_lines(self, key, parents, lines, parent_texts=None,
582
        left_matching_blocks=None, nostore_sha=None, random_id=False,
583
        check_content=True):
584
        self.calls.append(("add_lines", key, parents, lines, parent_texts,
585
            left_matching_blocks, nostore_sha, random_id, check_content))
586
        return self._backing_vf.add_lines(key, parents, lines, parent_texts,
587
            left_matching_blocks, nostore_sha, random_id, check_content)
588
3517.4.19 by Martin Pool
Update test for knit.check() to expect it to recurse into fallback vfs
589
    def check(self):
590
        self._backing_vf.check()
591
3350.8.2 by Robert Collins
stacked get_parent_map.
592
    def get_parent_map(self, keys):
593
        self.calls.append(("get_parent_map", copy(keys)))
594
        return self._backing_vf.get_parent_map(keys)
595
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.
596
    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!).
597
        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.
598
            include_delta_closure))
599
        return self._backing_vf.get_record_stream(keys, sort_order,
600
            include_delta_closure)
601
3350.8.3 by Robert Collins
VF.get_sha1s needed changing to be stackable.
602
    def get_sha1s(self, keys):
603
        self.calls.append(("get_sha1s", copy(keys)))
604
        return self._backing_vf.get_sha1s(keys)
605
3350.8.5 by Robert Collins
Iter_lines_added_or_present_in_keys stacks.
606
    def iter_lines_added_or_present_in_keys(self, keys, pb=None):
607
        self.calls.append(("iter_lines_added_or_present_in_keys", copy(keys)))
3350.8.14 by Robert Collins
Review feedback.
608
        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.
609
3350.8.4 by Robert Collins
Vf.keys() stacking support.
610
    def keys(self):
611
        self.calls.append(("keys",))
612
        return self._backing_vf.keys()
613
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.
614
3871.4.1 by John Arbash Meinel
Add a VFDecorator that can yield records in a specified order
615
class OrderingVersionedFilesDecorator(RecordingVersionedFilesDecorator):
616
    """A VF that records calls, and returns keys in specific order.
617
618
    :ivar calls: A list of the calls made; can be reset at any time by
619
        assigning [] to it.
620
    """
621
622
    def __init__(self, backing_vf, key_priority):
623
        """Create a RecordingVersionedFilesDecorator decorating backing_vf.
624
625
        :param backing_vf: The versioned file to answer all methods.
626
        :param key_priority: A dictionary defining what order keys should be
627
            returned from an 'unordered' get_record_stream request.
628
            Keys with lower priority are returned first, keys not present in
629
            the map get an implicit priority of 0, and are returned in
630
            lexicographical order.
631
        """
632
        RecordingVersionedFilesDecorator.__init__(self, backing_vf)
633
        self._key_priority = key_priority
634
635
    def get_record_stream(self, keys, sort_order, include_delta_closure):
636
        self.calls.append(("get_record_stream", list(keys), sort_order,
637
            include_delta_closure))
638
        if sort_order == 'unordered':
639
            def sort_key(key):
640
                return (self._key_priority.get(key, 0), key)
641
            # Use a defined order by asking for the keys one-by-one from the
642
            # backing_vf
643
            for key in sorted(keys, key=sort_key):
644
                for record in self._backing_vf.get_record_stream([key],
645
                                'unordered', include_delta_closure):
646
                    yield record
647
        else:
648
            for record in self._backing_vf.get_record_stream(keys, sort_order,
649
                            include_delta_closure):
650
                yield record
651
652
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.
653
class KeyMapper(object):
3350.6.10 by Martin Pool
VersionedFiles review cleanups
654
    """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.
655
656
    def map(self, key):
657
        """Map key to an underlying storage identifier.
658
659
        :param key: A key tuple e.g. ('file-id', 'revision-id').
660
        :return: An underlying storage identifier, specific to the partitioning
661
            mechanism.
662
        """
663
        raise NotImplementedError(self.map)
664
665
    def unmap(self, partition_id):
666
        """Map a partitioned storage id back to a key prefix.
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
667
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.
668
        :param partition_id: The underlying partition id.
3350.6.10 by Martin Pool
VersionedFiles review cleanups
669
        :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.
670
            id.
671
        """
672
        raise NotImplementedError(self.unmap)
673
674
675
class ConstantMapper(KeyMapper):
676
    """A key mapper that maps to a constant result."""
677
678
    def __init__(self, result):
679
        """Create a ConstantMapper which will return result for all maps."""
680
        self._result = result
681
682
    def map(self, key):
683
        """See KeyMapper.map()."""
684
        return self._result
685
686
687
class URLEscapeMapper(KeyMapper):
688
    """Base class for use with transport backed storage.
689
690
    This provides a map and unmap wrapper that respectively url escape and
691
    unescape their outputs and inputs.
692
    """
693
694
    def map(self, key):
695
        """See KeyMapper.map()."""
696
        return urllib.quote(self._map(key))
697
698
    def unmap(self, partition_id):
699
        """See KeyMapper.unmap()."""
700
        return self._unmap(urllib.unquote(partition_id))
701
702
703
class PrefixMapper(URLEscapeMapper):
704
    """A key mapper that extracts the first component of a key.
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
705
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.
706
    This mapper is for use with a transport based backend.
707
    """
708
709
    def _map(self, key):
710
        """See KeyMapper.map()."""
711
        return key[0]
712
713
    def _unmap(self, partition_id):
714
        """See KeyMapper.unmap()."""
715
        return (partition_id,)
716
717
718
class HashPrefixMapper(URLEscapeMapper):
719
    """A key mapper that combines the first component of a key with a hash.
720
721
    This mapper is for use with a transport based backend.
722
    """
723
724
    def _map(self, key):
725
        """See KeyMapper.map()."""
726
        prefix = self._escape(key[0])
727
        return "%02x/%s" % (adler32(prefix) & 0xff, prefix)
728
729
    def _escape(self, prefix):
730
        """No escaping needed here."""
731
        return prefix
732
733
    def _unmap(self, partition_id):
734
        """See KeyMapper.unmap()."""
735
        return (self._unescape(osutils.basename(partition_id)),)
736
737
    def _unescape(self, basename):
738
        """No unescaping needed for HashPrefixMapper."""
739
        return basename
740
741
742
class HashEscapedPrefixMapper(HashPrefixMapper):
743
    """Combines the escaped first component of a key with a hash.
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
744
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.
745
    This mapper is for use with a transport based backend.
746
    """
747
748
    _safe = "abcdefghijklmnopqrstuvwxyz0123456789-_@,."
749
750
    def _escape(self, prefix):
751
        """Turn a key element into a filesystem safe string.
752
753
        This is similar to a plain urllib.quote, except
754
        it uses specific safe characters, so that it doesn't
755
        have to translate a lot of valid file ids.
756
        """
757
        # @ does not get escaped. This is because it is a valid
758
        # filesystem character we use all the time, and it looks
759
        # a lot better than seeing %40 all the time.
760
        r = [((c in self._safe) and c or ('%%%02x' % ord(c)))
761
             for c in prefix]
762
        return ''.join(r)
763
764
    def _unescape(self, basename):
765
        """Escaped names are easily unescaped by urlutils."""
766
        return urllib.unquote(basename)
767
768
769
def make_versioned_files_factory(versioned_file_factory, mapper):
770
    """Create a ThunkedVersionedFiles factory.
771
772
    This will create a callable which when called creates a
773
    ThunkedVersionedFiles on a transport, using mapper to access individual
774
    versioned files, and versioned_file_factory to create each individual file.
775
    """
776
    def factory(transport):
777
        return ThunkedVersionedFiles(transport, versioned_file_factory, mapper,
778
            lambda:True)
779
    return factory
780
781
782
class VersionedFiles(object):
783
    """Storage for many versioned files.
784
785
    This object allows a single keyspace for accessing the history graph and
786
    contents of named bytestrings.
787
788
    Currently no implementation allows the graph of different key prefixes to
789
    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.
790
791
    The keyspace is expressed via simple tuples. Any instance of VersionedFiles
792
    may have a different length key-size, but that size will be constant for
793
    all texts added to or retrieved from it. For instance, bzrlib uses
794
    instances with a key-size of 2 for storing user files in a repository, with
795
    the first element the fileid, and the second the version of that file.
796
797
    The use of tuples allows a single code base to support several different
798
    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.
799
    """
800
801
    def add_lines(self, key, parents, lines, parent_texts=None,
802
        left_matching_blocks=None, nostore_sha=None, random_id=False,
803
        check_content=True):
804
        """Add a text to the store.
805
4241.4.1 by Ian Clatworthy
add sha generation support to versionedfiles
806
        :param key: The key tuple of the text to add. If the last element is
807
            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.
808
        :param parents: The parents key tuples of the text to add.
809
        :param lines: A list of lines. Each line must be a bytestring. And all
810
            of them except the last must be terminated with \n and contain no
811
            other \n's. The last line may either contain no \n's or a single
812
            terminating \n. If the lines list does meet this constraint the add
813
            routine may error or may succeed - but you will be unable to read
814
            the data back accurately. (Checking the lines have been split
815
            correctly is expensive and extremely unlikely to catch bugs so it
816
            is not done at runtime unless check_content is True.)
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
817
        :param parent_texts: An optional dictionary containing the opaque
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.
818
            representations of some or all of the parents of version_id to
819
            allow delta optimisations.  VERY IMPORTANT: the texts must be those
820
            returned by add_lines or data corruption can be caused.
821
        :param left_matching_blocks: a hint about which areas are common
822
            between the text and its left-hand-parent.  The format is
823
            the SequenceMatcher.get_matching_blocks format.
824
        :param nostore_sha: Raise ExistingContent and do not add the lines to
825
            the versioned file if the digest of the lines matches this.
826
        :param random_id: If True a random id has been selected rather than
827
            an id determined by some deterministic process such as a converter
828
            from a foreign VCS. When True the backend may choose not to check
829
            for uniqueness of the resulting key within the versioned file, so
830
            this should only be done when the result is expected to be unique
831
            anyway.
832
        :param check_content: If True, the lines supplied are verified to be
833
            bytestrings that are correctly formed lines.
834
        :return: The text sha1, the number of bytes in the text, and an opaque
835
                 representation of the inserted version which can be provided
836
                 back to future add_lines calls in the parent_texts dictionary.
837
        """
838
        raise NotImplementedError(self.add_lines)
839
4398.8.6 by John Arbash Meinel
Switch the api from VF.add_text to VF._add_text and trim some extra 'features'.
840
    def _add_text(self, key, parents, text, nostore_sha=None, random_id=False):
841
        """Add a text to the store.
842
843
        This is a private function for use by CommitBuilder.
844
845
        :param key: The key tuple of the text to add. If the last element is
846
            None, a CHK string will be generated during the addition.
847
        :param parents: The parents key tuples of the text to add.
848
        :param text: A string containing the text to be committed.
849
        :param nostore_sha: Raise ExistingContent and do not add the lines to
850
            the versioned file if the digest of the lines matches this.
851
        :param random_id: If True a random id has been selected rather than
852
            an id determined by some deterministic process such as a converter
853
            from a foreign VCS. When True the backend may choose not to check
854
            for uniqueness of the resulting key within the versioned file, so
855
            this should only be done when the result is expected to be unique
856
            anyway.
857
        :param check_content: If True, the lines supplied are verified to be
858
            bytestrings that are correctly formed lines.
859
        :return: The text sha1, the number of bytes in the text, and an opaque
860
                 representation of the inserted version which can be provided
861
                 back to future _add_text calls in the parent_texts dictionary.
862
        """
863
        # The default implementation just thunks over to .add_lines(),
864
        # inefficient, but it works.
4398.8.1 by John Arbash Meinel
Add a VersionedFile.add_text() api.
865
        return self.add_lines(key, parents, osutils.split_lines(text),
866
                              nostore_sha=nostore_sha,
867
                              random_id=random_id,
4398.8.6 by John Arbash Meinel
Switch the api from VF.add_text to VF._add_text and trim some extra 'features'.
868
                              check_content=True)
4398.8.1 by John Arbash Meinel
Add a VersionedFile.add_text() api.
869
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.
870
    def add_mpdiffs(self, records):
871
        """Add mpdiffs to this VersionedFile.
872
873
        Records should be iterables of version, parents, expected_sha1,
874
        mpdiff. mpdiff should be a MultiParent instance.
875
        """
876
        vf_parents = {}
877
        mpvf = multiparent.MultiMemoryVersionedFile()
878
        versions = []
879
        for version, parent_ids, expected_sha1, mpdiff in records:
880
            versions.append(version)
881
            mpvf.add_diff(mpdiff, version, parent_ids)
882
        needed_parents = set()
883
        for version, parent_ids, expected_sha1, mpdiff in records:
884
            needed_parents.update(p for p in parent_ids
885
                                  if not mpvf.has_version(p))
886
        # It seems likely that adding all the present parents as fulltexts can
887
        # easily exhaust memory.
3890.2.9 by John Arbash Meinel
Start using osutils.chunks_as_lines rather than osutils.split_lines.
888
        chunks_to_lines = osutils.chunks_to_lines
3350.8.11 by Robert Collins
Stacked add_mpdiffs.
889
        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.
890
            True):
3350.8.11 by Robert Collins
Stacked add_mpdiffs.
891
            if record.storage_kind == 'absent':
892
                continue
3890.2.9 by John Arbash Meinel
Start using osutils.chunks_as_lines rather than osutils.split_lines.
893
            mpvf.add_version(chunks_to_lines(record.get_bytes_as('chunked')),
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.
894
                record.key, [])
895
        for (key, parent_keys, expected_sha1, mpdiff), lines in\
896
            zip(records, mpvf.get_line_list(versions)):
897
            if len(parent_keys) == 1:
898
                left_matching_blocks = list(mpdiff.get_matching_blocks(0,
899
                    mpvf.get_diff(parent_keys[0]).num_lines()))
900
            else:
901
                left_matching_blocks = None
902
            version_sha1, _, version_text = self.add_lines(key,
903
                parent_keys, lines, vf_parents,
904
                left_matching_blocks=left_matching_blocks)
905
            if version_sha1 != expected_sha1:
906
                raise errors.VersionedFileInvalidChecksum(version)
907
            vf_parents[key] = version_text
908
909
    def annotate(self, key):
910
        """Return a list of (version-key, line) tuples for the text of key.
911
912
        :raise RevisionNotPresent: If the key is not present.
913
        """
914
        raise NotImplementedError(self.annotate)
915
916
    def check(self, progress_bar=None):
4332.3.26 by Robert Collins
Allow passing keys to check to VersionedFile.check().
917
        """Check this object for integrity.
918
        
919
        :param progress_bar: A progress bar to output as the check progresses.
920
        :param keys: Specific keys within the VersionedFiles to check. When
921
            this parameter is not None, check() becomes a generator as per
922
            get_record_stream. The difference to get_record_stream is that
923
            more or deeper checks will be performed.
924
        :return: None, or if keys was supplied a generator as per
925
            get_record_stream.
926
        """
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.
927
        raise NotImplementedError(self.check)
928
929
    @staticmethod
930
    def check_not_reserved_id(version_id):
931
        revision.check_not_reserved_id(version_id)
932
4744.2.5 by John Arbash Meinel
Change to a generic 'VersionedFiles.clear_cache()' api.
933
    def clear_cache(self):
934
        """Clear whatever caches this VersionedFile holds.
935
936
        This is generally called after an operation has been performed, when we
937
        don't expect to be using this versioned file again soon.
938
        """
939
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.
940
    def _check_lines_not_unicode(self, lines):
941
        """Check that lines being added to a versioned file are not unicode."""
942
        for line in lines:
943
            if line.__class__ is not str:
944
                raise errors.BzrBadParameterUnicode("lines")
945
946
    def _check_lines_are_lines(self, lines):
947
        """Check that the lines really are full lines without inline EOL."""
948
        for line in lines:
949
            if '\n' in line[:-1]:
950
                raise errors.BzrBadParameterContainsNewline("lines")
951
4593.5.36 by John Arbash Meinel
a few more implementations of the interface.
952
    def get_known_graph_ancestry(self, keys):
953
        """Get a KnownGraph instance with the ancestry of keys."""
954
        # most basic implementation is a loop around get_parent_map
955
        pending = set(keys)
956
        parent_map = {}
957
        while pending:
958
            this_parent_map = self.get_parent_map(pending)
959
            parent_map.update(this_parent_map)
960
            pending = set()
961
            map(pending.update, this_parent_map.itervalues())
962
            pending = pending.difference(parent_map)
963
        kg = _mod_graph.KnownGraph(parent_map)
964
        return kg
965
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.
966
    def get_parent_map(self, keys):
967
        """Get a map of the parents of keys.
968
969
        :param keys: The keys to look up parents for.
970
        :return: A mapping from keys to parents. Absent keys are absent from
971
            the mapping.
972
        """
973
        raise NotImplementedError(self.get_parent_map)
974
975
    def get_record_stream(self, keys, ordering, include_delta_closure):
976
        """Get a stream of records for keys.
977
978
        :param keys: The keys to include.
979
        :param ordering: Either 'unordered' or 'topological'. A topologically
980
            sorted stream has compression parents strictly before their
981
            children.
982
        :param include_delta_closure: If True then the closure across any
983
            compression parents will be included (in the opaque data).
984
        :return: An iterator of ContentFactory objects, each of which is only
985
            valid until the iterator is advanced.
986
        """
987
        raise NotImplementedError(self.get_record_stream)
988
989
    def get_sha1s(self, keys):
990
        """Get the sha1's of the texts for the given keys.
991
992
        :param keys: The names of the keys to lookup
3350.8.3 by Robert Collins
VF.get_sha1s needed changing to be stackable.
993
        :return: a dict from key to sha1 digest. Keys of texts which are not
3350.8.14 by Robert Collins
Review feedback.
994
            present in the store are not present in the returned
3350.8.3 by Robert Collins
VF.get_sha1s needed changing to be stackable.
995
            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.
996
        """
997
        raise NotImplementedError(self.get_sha1s)
998
3830.3.12 by Martin Pool
Review cleanups: unify has_key impls, add missing_keys(), clean up exception blocks
999
    has_key = index._has_key_from_parent_map
1000
4009.3.3 by Andrew Bennetts
Add docstrings.
1001
    def get_missing_compression_parent_keys(self):
1002
        """Return an iterable of keys of missing compression parents.
1003
1004
        Check this after calling insert_record_stream to find out if there are
1005
        any missing compression parents.  If there are, the records that
4009.3.12 by Robert Collins
Polish on inserting record streams with missing compression parents.
1006
        depend on them are not able to be inserted safely. The precise
1007
        behaviour depends on the concrete VersionedFiles class in use.
1008
1009
        Classes that do not support this will raise NotImplementedError.
4009.3.3 by Andrew Bennetts
Add docstrings.
1010
        """
1011
        raise NotImplementedError(self.get_missing_compression_parent_keys)
1012
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.
1013
    def insert_record_stream(self, stream):
1014
        """Insert a record stream into this container.
1015
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
1016
        :param stream: A stream of records to insert.
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.
1017
        :return: None
1018
        :seealso VersionedFile.get_record_stream:
1019
        """
1020
        raise NotImplementedError
1021
1022
    def iter_lines_added_or_present_in_keys(self, keys, pb=None):
1023
        """Iterate over the lines in the versioned files from keys.
1024
1025
        This may return lines from other keys. Each item the returned
1026
        iterator yields is a tuple of a line and a text version that that line
1027
        is present in (not introduced in).
1028
1029
        Ordering of results is in whatever order is most suitable for the
1030
        underlying storage format.
1031
1032
        If a progress bar is supplied, it may be used to indicate progress.
1033
        The caller is responsible for cleaning up progress bars (because this
1034
        is an iterator).
1035
1036
        NOTES:
1037
         * Lines are normalised by the underlying store: they will all have \n
1038
           terminators.
1039
         * Lines are returned in arbitrary order.
1040
1041
        :return: An iterator over (line, key).
1042
        """
1043
        raise NotImplementedError(self.iter_lines_added_or_present_in_keys)
1044
1045
    def keys(self):
1046
        """Return a iterable of the keys for all the contained texts."""
1047
        raise NotImplementedError(self.keys)
1048
1049
    def make_mpdiffs(self, keys):
1050
        """Create multiparent diffs for specified keys."""
1051
        keys_order = tuple(keys)
1052
        keys = frozenset(keys)
1053
        knit_keys = set(keys)
1054
        parent_map = self.get_parent_map(keys)
1055
        for parent_keys in parent_map.itervalues():
1056
            if parent_keys:
1057
                knit_keys.update(parent_keys)
1058
        missing_keys = keys - set(parent_map)
1059
        if missing_keys:
3530.3.2 by Robert Collins
Handling frozen set inputs in mpdiff generation when a key is missing
1060
            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.
1061
        # We need to filter out ghosts, because we can't diff against them.
1062
        maybe_ghosts = knit_keys - keys
1063
        ghosts = maybe_ghosts - set(self.get_parent_map(maybe_ghosts))
1064
        knit_keys.difference_update(ghosts)
1065
        lines = {}
3890.2.9 by John Arbash Meinel
Start using osutils.chunks_as_lines rather than osutils.split_lines.
1066
        chunks_to_lines = osutils.chunks_to_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.
1067
        for record in self.get_record_stream(knit_keys, 'topological', True):
3890.2.9 by John Arbash Meinel
Start using osutils.chunks_as_lines rather than osutils.split_lines.
1068
            lines[record.key] = chunks_to_lines(record.get_bytes_as('chunked'))
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.
1069
            # line_block_dict = {}
1070
            # for parent, blocks in record.extract_line_blocks():
1071
            #   line_blocks[parent] = blocks
1072
            # line_blocks[record.key] = line_block_dict
1073
        diffs = []
1074
        for key in keys_order:
1075
            target = lines[key]
1076
            parents = parent_map[key] or []
1077
            # Note that filtering knit_keys can lead to a parent difference
1078
            # between the creation and the application of the mpdiff.
1079
            parent_lines = [lines[p] for p in parents if p in knit_keys]
1080
            if len(parent_lines) > 0:
1081
                left_parent_blocks = self._extract_blocks(key, parent_lines[0],
1082
                    target)
1083
            else:
1084
                left_parent_blocks = None
1085
            diffs.append(multiparent.MultiParent.from_lines(target,
1086
                parent_lines, left_parent_blocks))
1087
        return diffs
1088
3830.3.12 by Martin Pool
Review cleanups: unify has_key impls, add missing_keys(), clean up exception blocks
1089
    missing_keys = index._missing_keys_from_parent_map
1090
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.
1091
    def _extract_blocks(self, version_id, source, target):
1092
        return None
1093
1094
1095
class ThunkedVersionedFiles(VersionedFiles):
1096
    """Storage for many versioned files thunked onto a 'VersionedFile' class.
1097
1098
    This object allows a single keyspace for accessing the history graph and
1099
    contents of named bytestrings.
1100
1101
    Currently no implementation allows the graph of different key prefixes to
1102
    intersect, but the API does allow such implementations in the future.
1103
    """
1104
1105
    def __init__(self, transport, file_factory, mapper, is_locked):
1106
        """Create a ThunkedVersionedFiles."""
1107
        self._transport = transport
1108
        self._file_factory = file_factory
1109
        self._mapper = mapper
1110
        self._is_locked = is_locked
1111
1112
    def add_lines(self, key, parents, lines, parent_texts=None,
1113
        left_matching_blocks=None, nostore_sha=None, random_id=False,
1114
        check_content=True):
1115
        """See VersionedFiles.add_lines()."""
1116
        path = self._mapper.map(key)
1117
        version_id = key[-1]
1118
        parents = [parent[-1] for parent in parents]
1119
        vf = self._get_vf(path)
1120
        try:
1121
            try:
1122
                return vf.add_lines_with_ghosts(version_id, parents, lines,
1123
                    parent_texts=parent_texts,
1124
                    left_matching_blocks=left_matching_blocks,
1125
                    nostore_sha=nostore_sha, random_id=random_id,
1126
                    check_content=check_content)
1127
            except NotImplementedError:
1128
                return vf.add_lines(version_id, parents, lines,
1129
                    parent_texts=parent_texts,
1130
                    left_matching_blocks=left_matching_blocks,
1131
                    nostore_sha=nostore_sha, random_id=random_id,
1132
                    check_content=check_content)
1133
        except errors.NoSuchFile:
1134
            # parent directory may be missing, try again.
1135
            self._transport.mkdir(osutils.dirname(path))
1136
            try:
1137
                return vf.add_lines_with_ghosts(version_id, parents, lines,
1138
                    parent_texts=parent_texts,
1139
                    left_matching_blocks=left_matching_blocks,
1140
                    nostore_sha=nostore_sha, random_id=random_id,
1141
                    check_content=check_content)
1142
            except NotImplementedError:
1143
                return vf.add_lines(version_id, parents, lines,
1144
                    parent_texts=parent_texts,
1145
                    left_matching_blocks=left_matching_blocks,
1146
                    nostore_sha=nostore_sha, random_id=random_id,
1147
                    check_content=check_content)
1148
1149
    def annotate(self, key):
1150
        """Return a list of (version-key, line) tuples for the text of key.
1151
1152
        :raise RevisionNotPresent: If the key is not present.
1153
        """
1154
        prefix = key[:-1]
1155
        path = self._mapper.map(prefix)
1156
        vf = self._get_vf(path)
1157
        origins = vf.annotate(key[-1])
1158
        result = []
1159
        for origin, line in origins:
1160
            result.append((prefix + (origin,), line))
1161
        return result
1162
4454.3.65 by John Arbash Meinel
Tests that VF implementations support .get_annotator()
1163
    def get_annotator(self):
1164
        return annotate.Annotator(self)
1165
4332.3.26 by Robert Collins
Allow passing keys to check to VersionedFile.check().
1166
    def check(self, progress_bar=None, keys=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.
1167
        """See VersionedFiles.check()."""
4332.3.26 by Robert Collins
Allow passing keys to check to VersionedFile.check().
1168
        # XXX: This is over-enthusiastic but as we only thunk for Weaves today
1169
        # this is tolerable. Ideally we'd pass keys down to check() and 
1170
        # have the older VersiondFile interface updated too.
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.
1171
        for prefix, vf in self._iter_all_components():
1172
            vf.check()
4332.3.26 by Robert Collins
Allow passing keys to check to VersionedFile.check().
1173
        if keys is not None:
1174
            return self.get_record_stream(keys, 'unordered', True)
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.
1175
1176
    def get_parent_map(self, keys):
1177
        """Get a map of the parents of keys.
1178
1179
        :param keys: The keys to look up parents for.
1180
        :return: A mapping from keys to parents. Absent keys are absent from
1181
            the mapping.
1182
        """
1183
        prefixes = self._partition_keys(keys)
1184
        result = {}
1185
        for prefix, suffixes in prefixes.items():
1186
            path = self._mapper.map(prefix)
1187
            vf = self._get_vf(path)
1188
            parent_map = vf.get_parent_map(suffixes)
1189
            for key, parents in parent_map.items():
1190
                result[prefix + (key,)] = tuple(
1191
                    prefix + (parent,) for parent in parents)
1192
        return result
1193
1194
    def _get_vf(self, path):
1195
        if not self._is_locked():
1196
            raise errors.ObjectNotLocked(self)
1197
        return self._file_factory(path, self._transport, create=True,
1198
            get_scope=lambda:None)
1199
1200
    def _partition_keys(self, keys):
1201
        """Turn keys into a dict of prefix:suffix_list."""
1202
        result = {}
1203
        for key in keys:
1204
            prefix_keys = result.setdefault(key[:-1], [])
1205
            prefix_keys.append(key[-1])
1206
        return result
1207
1208
    def _get_all_prefixes(self):
1209
        # Identify all key prefixes.
1210
        # XXX: A bit hacky, needs polish.
1211
        if type(self._mapper) == ConstantMapper:
1212
            paths = [self._mapper.map(())]
1213
            prefixes = [()]
1214
        else:
1215
            relpaths = set()
1216
            for quoted_relpath in self._transport.iter_files_recursive():
1217
                path, ext = os.path.splitext(quoted_relpath)
1218
                relpaths.add(path)
1219
            paths = list(relpaths)
1220
            prefixes = [self._mapper.unmap(path) for path in paths]
1221
        return zip(paths, prefixes)
1222
1223
    def get_record_stream(self, keys, ordering, include_delta_closure):
1224
        """See VersionedFiles.get_record_stream()."""
1225
        # Ordering will be taken care of by each partitioned store; group keys
1226
        # by partition.
1227
        keys = sorted(keys)
1228
        for prefix, suffixes, vf in self._iter_keys_vf(keys):
1229
            suffixes = [(suffix,) for suffix in suffixes]
1230
            for record in vf.get_record_stream(suffixes, ordering,
1231
                include_delta_closure):
1232
                if record.parents is not None:
1233
                    record.parents = tuple(
1234
                        prefix + parent for parent in record.parents)
1235
                record.key = prefix + record.key
1236
                yield record
1237
1238
    def _iter_keys_vf(self, keys):
1239
        prefixes = self._partition_keys(keys)
1240
        sha1s = {}
1241
        for prefix, suffixes in prefixes.items():
1242
            path = self._mapper.map(prefix)
1243
            vf = self._get_vf(path)
1244
            yield prefix, suffixes, vf
1245
1246
    def get_sha1s(self, keys):
1247
        """See VersionedFiles.get_sha1s()."""
1248
        sha1s = {}
1249
        for prefix,suffixes, vf in self._iter_keys_vf(keys):
1250
            vf_sha1s = vf.get_sha1s(suffixes)
3350.8.3 by Robert Collins
VF.get_sha1s needed changing to be stackable.
1251
            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.
1252
                sha1s[prefix + (suffix,)] = sha1
3350.8.3 by Robert Collins
VF.get_sha1s needed changing to be stackable.
1253
        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.
1254
1255
    def insert_record_stream(self, stream):
1256
        """Insert a record stream into this container.
1257
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
1258
        :param stream: A stream of records to insert.
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.
1259
        :return: None
1260
        :seealso VersionedFile.get_record_stream:
1261
        """
1262
        for record in stream:
1263
            prefix = record.key[:-1]
1264
            key = record.key[-1:]
1265
            if record.parents is not None:
1266
                parents = [parent[-1:] for parent in record.parents]
1267
            else:
1268
                parents = None
1269
            thunk_record = AdapterFactory(key, parents, record)
1270
            path = self._mapper.map(prefix)
1271
            # Note that this parses the file many times; we can do better but
1272
            # as this only impacts weaves in terms of performance, it is
1273
            # tolerable.
1274
            vf = self._get_vf(path)
1275
            vf.insert_record_stream([thunk_record])
1276
1277
    def iter_lines_added_or_present_in_keys(self, keys, pb=None):
1278
        """Iterate over the lines in the versioned files from keys.
1279
1280
        This may return lines from other keys. Each item the returned
1281
        iterator yields is a tuple of a line and a text version that that line
1282
        is present in (not introduced in).
1283
1284
        Ordering of results is in whatever order is most suitable for the
1285
        underlying storage format.
1286
1287
        If a progress bar is supplied, it may be used to indicate progress.
1288
        The caller is responsible for cleaning up progress bars (because this
1289
        is an iterator).
1290
1291
        NOTES:
1292
         * Lines are normalised by the underlying store: they will all have \n
1293
           terminators.
1294
         * Lines are returned in arbitrary order.
1295
1296
        :return: An iterator over (line, key).
1297
        """
1298
        for prefix, suffixes, vf in self._iter_keys_vf(keys):
1299
            for line, version in vf.iter_lines_added_or_present_in_versions(suffixes):
1300
                yield line, prefix + (version,)
1301
1302
    def _iter_all_components(self):
1303
        for path, prefix in self._get_all_prefixes():
1304
            yield prefix, self._get_vf(path)
1305
1306
    def keys(self):
1307
        """See VersionedFiles.keys()."""
1308
        result = set()
1309
        for prefix, vf in self._iter_all_components():
1310
            for suffix in vf.versions():
1311
                result.add(prefix + (suffix,))
1312
        return result
1313
1314
1315
class _PlanMergeVersionedFile(VersionedFiles):
3062.1.9 by Aaron Bentley
Move PlanMerge into merge and _PlanMergeVersionedFile into versionedfile
1316
    """A VersionedFile for uncommitted and committed texts.
1317
1318
    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.
1319
    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
1320
    PlanMerge.  It falls back to multiple versionedfiles for data not stored in
1321
    _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.
1322
1323
    :ivar: fallback_versionedfiles a list of VersionedFiles objects that can be
1324
        queried for missing texts.
3062.1.9 by Aaron Bentley
Move PlanMerge into merge and _PlanMergeVersionedFile into versionedfile
1325
    """
1326
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.
1327
    def __init__(self, file_id):
1328
        """Create a _PlanMergeVersionedFile.
3062.1.9 by Aaron Bentley
Move PlanMerge into merge and _PlanMergeVersionedFile into versionedfile
1329
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.
1330
        :param file_id: Used with _PlanMerge code which is not yet fully
1331
            tuple-keyspace aware.
3062.1.9 by Aaron Bentley
Move PlanMerge into merge and _PlanMergeVersionedFile into versionedfile
1332
        """
1333
        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.
1334
        # fallback locations
1335
        self.fallback_versionedfiles = []
1336
        # Parents for locally held keys.
3062.1.9 by Aaron Bentley
Move PlanMerge into merge and _PlanMergeVersionedFile into versionedfile
1337
        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.
1338
        # line data for locally held keys.
3062.1.9 by Aaron Bentley
Move PlanMerge into merge and _PlanMergeVersionedFile into versionedfile
1339
        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.
1340
        # key lookup providers
1341
        self._providers = [DictParentsProvider(self._parents)]
3062.1.9 by Aaron Bentley
Move PlanMerge into merge and _PlanMergeVersionedFile into versionedfile
1342
3062.2.3 by Aaron Bentley
Sync up with bzr.dev API changes
1343
    def plan_merge(self, ver_a, ver_b, base=None):
3062.1.13 by Aaron Bentley
Make _PlanMerge an implementation detail of _PlanMergeVersionedFile
1344
        """See VersionedFile.plan_merge"""
3144.3.7 by Aaron Bentley
Update from review
1345
        from bzrlib.merge import _PlanMerge
3062.2.3 by Aaron Bentley
Sync up with bzr.dev API changes
1346
        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.
1347
            return _PlanMerge(ver_a, ver_b, self, (self._file_id,)).plan_merge()
1348
        old_plan = list(_PlanMerge(ver_a, base, self, (self._file_id,)).plan_merge())
1349
        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
1350
        return _PlanMerge._subtract_plans(old_plan, new_plan)
1351
3144.3.1 by Aaron Bentley
Implement LCA merge, with problematic conflict markers
1352
    def plan_lca_merge(self, ver_a, ver_b, base=None):
3144.3.7 by Aaron Bentley
Update from review
1353
        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.
1354
        graph = Graph(self)
1355
        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
1356
        if base is None:
1357
            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.
1358
        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
1359
        return _PlanLCAMerge._subtract_plans(list(old_plan), list(new_plan))
3062.1.13 by Aaron Bentley
Make _PlanMerge an implementation detail of _PlanMergeVersionedFile
1360
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.
1361
    def add_lines(self, key, parents, lines):
1362
        """See VersionedFiles.add_lines
3062.1.9 by Aaron Bentley
Move PlanMerge into merge and _PlanMergeVersionedFile into versionedfile
1363
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.
1364
        Lines are added locally, not to fallback versionedfiles.  Also, ghosts
1365
        are permitted.  Only reserved ids are permitted.
3062.1.9 by Aaron Bentley
Move PlanMerge into merge and _PlanMergeVersionedFile into versionedfile
1366
        """
3350.6.8 by Martin Pool
Change stray pdb calls to exceptions
1367
        if type(key) is not tuple:
1368
            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.
1369
        if not revision.is_reserved_id(key[-1]):
3062.1.9 by Aaron Bentley
Move PlanMerge into merge and _PlanMergeVersionedFile into versionedfile
1370
            raise ValueError('Only reserved ids may be used')
1371
        if parents is None:
1372
            raise ValueError('Parents may not be None')
1373
        if lines is None:
1374
            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.
1375
        self._parents[key] = tuple(parents)
1376
        self._lines[key] = lines
3062.1.9 by Aaron Bentley
Move PlanMerge into merge and _PlanMergeVersionedFile into versionedfile
1377
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.
1378
    def get_record_stream(self, keys, ordering, include_delta_closure):
1379
        pending = set(keys)
1380
        for key in keys:
1381
            if key in self._lines:
1382
                lines = self._lines[key]
1383
                parents = self._parents[key]
1384
                pending.remove(key)
3890.2.1 by John Arbash Meinel
Start working on a ChunkedContentFactory.
1385
                yield ChunkedContentFactory(key, parents, None, lines)
3062.1.9 by Aaron Bentley
Move PlanMerge into merge and _PlanMergeVersionedFile into versionedfile
1386
        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.
1387
            for record in versionedfile.get_record_stream(
1388
                pending, 'unordered', True):
1389
                if record.storage_kind == 'absent':
3062.1.9 by Aaron Bentley
Move PlanMerge into merge and _PlanMergeVersionedFile into versionedfile
1390
                    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.
1391
                else:
1392
                    pending.remove(record.key)
1393
                    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.
1394
            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.
1395
                return
1396
        # report absent entries
1397
        for key in pending:
1398
            yield AbsentContentFactory(key)
3062.1.9 by Aaron Bentley
Move PlanMerge into merge and _PlanMergeVersionedFile into versionedfile
1399
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.
1400
    def get_parent_map(self, keys):
1401
        """See VersionedFiles.get_parent_map"""
1402
        # We create a new provider because a fallback may have been added.
1403
        # If we make fallbacks private we can update a stack list and avoid
1404
        # object creation thrashing.
3350.6.6 by Robert Collins
Fix test_plan_file_merge
1405
        keys = set(keys)
1406
        result = {}
1407
        if revision.NULL_REVISION in keys:
1408
            keys.remove(revision.NULL_REVISION)
1409
            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.
1410
        self._providers = self._providers[:1] + self.fallback_versionedfiles
3350.6.6 by Robert Collins
Fix test_plan_file_merge
1411
        result.update(
4379.3.3 by Gary van der Merwe
Rename and add doc string for StackedParentsProvider.
1412
            StackedParentsProvider(self._providers).get_parent_map(keys))
3350.6.5 by Robert Collins
Update to bzr.dev.
1413
        for key, parents in result.iteritems():
1414
            if parents == ():
1415
                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.
1416
        return result
3144.3.1 by Aaron Bentley
Implement LCA merge, with problematic conflict markers
1417
3062.1.9 by Aaron Bentley
Move PlanMerge into merge and _PlanMergeVersionedFile into versionedfile
1418
1551.6.10 by Aaron Bentley
Renamed WeaveMerge to PlanMerge, added plan method, created planless WeaveMerge
1419
class PlanWeaveMerge(TextMerge):
1551.6.13 by Aaron Bentley
Cleanup
1420
    """Weave merge that takes a plan as its input.
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
1421
1551.6.14 by Aaron Bentley
Tweaks from merge review
1422
    This exists so that VersionedFile.plan_merge is implementable.
1423
    Most callers will want to use WeaveMerge instead.
1551.6.13 by Aaron Bentley
Cleanup
1424
    """
1425
1551.6.14 by Aaron Bentley
Tweaks from merge review
1426
    def __init__(self, plan, a_marker=TextMerge.A_MARKER,
1427
                 b_marker=TextMerge.B_MARKER):
1551.6.10 by Aaron Bentley
Renamed WeaveMerge to PlanMerge, added plan method, created planless WeaveMerge
1428
        TextMerge.__init__(self, a_marker, b_marker)
1429
        self.plan = plan
1430
1551.6.7 by Aaron Bentley
Implemented two-way merge, refactored weave merge
1431
    def _merge_struct(self):
1563.2.1 by Robert Collins
Merge in a variation of the versionedfile api from versioned-file.
1432
        lines_a = []
1433
        lines_b = []
1434
        ch_a = ch_b = False
1664.2.8 by Aaron Bentley
Fix WeaveMerge when plan doesn't end with unchanged lines
1435
1436
        def outstanding_struct():
1437
            if not lines_a and not lines_b:
1438
                return
1439
            elif ch_a and not ch_b:
1440
                # one-sided change:
1441
                yield(lines_a,)
1442
            elif ch_b and not ch_a:
1443
                yield (lines_b,)
1444
            elif lines_a == lines_b:
1445
                yield(lines_a,)
1446
            else:
1447
                yield (lines_a, lines_b)
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
1448
1616.1.18 by Martin Pool
(weave-merge) don't treat killed-both lines as points of agreement;
1449
        # We previously considered either 'unchanged' or 'killed-both' lines
1450
        # to be possible places to resynchronize.  However, assuming agreement
1759.2.1 by Jelmer Vernooij
Fix some types (found using aspell).
1451
        # on killed-both lines may be too aggressive. -- mbp 20060324
1551.6.7 by Aaron Bentley
Implemented two-way merge, refactored weave merge
1452
        for state, line in self.plan:
1616.1.18 by Martin Pool
(weave-merge) don't treat killed-both lines as points of agreement;
1453
            if state == 'unchanged':
1563.2.1 by Robert Collins
Merge in a variation of the versionedfile api from versioned-file.
1454
                # resync and flush queued conflicts changes if any
1664.2.8 by Aaron Bentley
Fix WeaveMerge when plan doesn't end with unchanged lines
1455
                for struct in outstanding_struct():
1456
                    yield struct
1551.6.11 by Aaron Bentley
Switched TextMerge_lines to work on a list
1457
                lines_a = []
1458
                lines_b = []
1563.2.1 by Robert Collins
Merge in a variation of the versionedfile api from versioned-file.
1459
                ch_a = ch_b = False
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
1460
1563.2.1 by Robert Collins
Merge in a variation of the versionedfile api from versioned-file.
1461
            if state == 'unchanged':
1462
                if line:
1551.6.5 by Aaron Bentley
Got weave merge producing structural output
1463
                    yield ([line],)
1563.2.1 by Robert Collins
Merge in a variation of the versionedfile api from versioned-file.
1464
            elif state == 'killed-a':
1465
                ch_a = True
1466
                lines_b.append(line)
1467
            elif state == 'killed-b':
1468
                ch_b = True
1469
                lines_a.append(line)
1470
            elif state == 'new-a':
1471
                ch_a = True
1472
                lines_a.append(line)
1473
            elif state == 'new-b':
1474
                ch_b = True
1475
                lines_b.append(line)
3144.3.2 by Aaron Bentley
Get conflict handling working
1476
            elif state == 'conflicted-a':
1477
                ch_b = ch_a = True
1478
                lines_a.append(line)
1479
            elif state == 'conflicted-b':
1480
                ch_b = ch_a = True
1481
                lines_b.append(line)
4312.1.1 by John Arbash Meinel
Add a per-implementation test that deleting lines conflicts with modifying lines.
1482
            elif state == 'killed-both':
1483
                # This counts as a change, even though there is no associated
1484
                # line
1485
                ch_b = ch_a = True
1563.2.1 by Robert Collins
Merge in a variation of the versionedfile api from versioned-file.
1486
            else:
3376.2.4 by Martin Pool
Remove every assert statement from bzrlib!
1487
                if state not in ('irrelevant', 'ghost-a', 'ghost-b',
4312.1.1 by John Arbash Meinel
Add a per-implementation test that deleting lines conflicts with modifying lines.
1488
                        'killed-base'):
3376.2.4 by Martin Pool
Remove every assert statement from bzrlib!
1489
                    raise AssertionError(state)
1664.2.8 by Aaron Bentley
Fix WeaveMerge when plan doesn't end with unchanged lines
1490
        for struct in outstanding_struct():
1491
            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.
1492
1664.2.14 by Aaron Bentley
spacing fix
1493
1551.6.10 by Aaron Bentley
Renamed WeaveMerge to PlanMerge, added plan method, created planless WeaveMerge
1494
class WeaveMerge(PlanWeaveMerge):
2831.7.1 by Ian Clatworthy
versionedfile.py code cleanups
1495
    """Weave merge that takes a VersionedFile and two versions as its input."""
1551.6.13 by Aaron Bentley
Cleanup
1496
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
1497
    def __init__(self, versionedfile, ver_a, ver_b,
1551.6.14 by Aaron Bentley
Tweaks from merge review
1498
        a_marker=PlanWeaveMerge.A_MARKER, b_marker=PlanWeaveMerge.B_MARKER):
1551.6.15 by Aaron Bentley
Moved plan_merge into Weave
1499
        plan = versionedfile.plan_merge(ver_a, ver_b)
1551.6.10 by Aaron Bentley
Renamed WeaveMerge to PlanMerge, added plan method, created planless WeaveMerge
1500
        PlanWeaveMerge.__init__(self, plan, a_marker, b_marker)
1501
1502
3518.1.1 by Jelmer Vernooij
Add VirtualVersionedFiles class.
1503
class VirtualVersionedFiles(VersionedFiles):
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
1504
    """Dummy implementation for VersionedFiles that uses other functions for
3518.1.1 by Jelmer Vernooij
Add VirtualVersionedFiles class.
1505
    obtaining fulltexts and parent maps.
1506
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
1507
    This is always on the bottom of the stack and uses string keys
3518.1.1 by Jelmer Vernooij
Add VirtualVersionedFiles class.
1508
    (rather than tuples) internally.
1509
    """
1510
1511
    def __init__(self, get_parent_map, get_lines):
1512
        """Create a VirtualVersionedFiles.
1513
1514
        :param get_parent_map: Same signature as Repository.get_parent_map.
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
1515
        :param get_lines: Should return lines for specified key or None if
3518.1.1 by Jelmer Vernooij
Add VirtualVersionedFiles class.
1516
                          not available.
1517
        """
1518
        super(VirtualVersionedFiles, self).__init__()
1519
        self._get_parent_map = get_parent_map
1520
        self._get_lines = get_lines
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
1521
3518.1.1 by Jelmer Vernooij
Add VirtualVersionedFiles class.
1522
    def check(self, progressbar=None):
1523
        """See VersionedFiles.check.
1524
1525
        :note: Always returns True for VirtualVersionedFiles.
1526
        """
1527
        return True
1528
1529
    def add_mpdiffs(self, records):
1530
        """See VersionedFiles.mpdiffs.
1531
1532
        :note: Not implemented for VirtualVersionedFiles.
1533
        """
1534
        raise NotImplementedError(self.add_mpdiffs)
1535
1536
    def get_parent_map(self, keys):
1537
        """See VersionedFiles.get_parent_map."""
3518.1.2 by Jelmer Vernooij
Fix some stylistic issues pointed out by Ian.
1538
        return dict([((k,), tuple([(p,) for p in v]))
1539
            for k,v in self._get_parent_map([k for (k,) in keys]).iteritems()])
3518.1.1 by Jelmer Vernooij
Add VirtualVersionedFiles class.
1540
1541
    def get_sha1s(self, keys):
1542
        """See VersionedFiles.get_sha1s."""
1543
        ret = {}
1544
        for (k,) in keys:
1545
            lines = self._get_lines(k)
1546
            if lines is not None:
3518.1.2 by Jelmer Vernooij
Fix some stylistic issues pointed out by Ian.
1547
                if not isinstance(lines, list):
1548
                    raise AssertionError
3518.1.1 by Jelmer Vernooij
Add VirtualVersionedFiles class.
1549
                ret[(k,)] = osutils.sha_strings(lines)
1550
        return ret
1551
1552
    def get_record_stream(self, keys, ordering, include_delta_closure):
1553
        """See VersionedFiles.get_record_stream."""
1554
        for (k,) in list(keys):
1555
            lines = self._get_lines(k)
1556
            if lines is not None:
3518.1.2 by Jelmer Vernooij
Fix some stylistic issues pointed out by Ian.
1557
                if not isinstance(lines, list):
1558
                    raise AssertionError
3890.2.1 by John Arbash Meinel
Start working on a ChunkedContentFactory.
1559
                yield ChunkedContentFactory((k,), None,
3518.1.1 by Jelmer Vernooij
Add VirtualVersionedFiles class.
1560
                        sha1=osutils.sha_strings(lines),
3890.2.1 by John Arbash Meinel
Start working on a ChunkedContentFactory.
1561
                        chunks=lines)
3518.1.1 by Jelmer Vernooij
Add VirtualVersionedFiles class.
1562
            else:
1563
                yield AbsentContentFactory((k,))
1564
3949.4.1 by Jelmer Vernooij
Implement VirtualVersionedFiles.iter_lines_added_or_present_in_keys.
1565
    def iter_lines_added_or_present_in_keys(self, keys, pb=None):
1566
        """See VersionedFile.iter_lines_added_or_present_in_versions()."""
1567
        for i, (key,) in enumerate(keys):
1568
            if pb is not None:
4110.2.10 by Martin Pool
Tweak iter_lines progress messages
1569
                pb.update("Finding changed lines", i, len(keys))
3949.4.1 by Jelmer Vernooij
Implement VirtualVersionedFiles.iter_lines_added_or_present_in_keys.
1570
            for l in self._get_lines(key):
1571
                yield (l, key)
4005.3.2 by Robert Collins
First passing NetworkRecordStream test - a fulltext from any record type which isn't a chunked or fulltext can be serialised and deserialised successfully.
1572
1573
1574
def network_bytes_to_kind_and_offset(network_bytes):
1575
    """Strip of a record kind from the front of network_bytes.
1576
1577
    :param network_bytes: The bytes of a record.
1578
    :return: A tuple (storage_kind, offset_of_remaining_bytes)
1579
    """
1580
    line_end = network_bytes.find('\n')
1581
    storage_kind = network_bytes[:line_end]
1582
    return storage_kind, line_end + 1
1583
1584
1585
class NetworkRecordStream(object):
1586
    """A record_stream which reconstitures a serialised stream."""
1587
1588
    def __init__(self, bytes_iterator):
1589
        """Create a NetworkRecordStream.
1590
1591
        :param bytes_iterator: An iterator of bytes. Each item in this
1592
            iterator should have been obtained from a record_streams'
1593
            record.get_bytes_as(record.storage_kind) call.
1594
        """
1595
        self._bytes_iterator = bytes_iterator
4476.3.4 by Andrew Bennetts
Network serialisation, and most tests passing with InterDifferingSerializer commented out.
1596
        self._kind_factory = {
1597
            'fulltext': fulltext_network_to_record,
1598
            'groupcompress-block': groupcompress.network_block_to_records,
1599
            'knit-ft-gz': knit.knit_network_to_record,
1600
            'knit-delta-gz': knit.knit_network_to_record,
1601
            'knit-annotated-ft-gz': knit.knit_network_to_record,
1602
            'knit-annotated-delta-gz': knit.knit_network_to_record,
1603
            'knit-delta-closure': knit.knit_delta_closure_to_records,
4005.3.2 by Robert Collins
First passing NetworkRecordStream test - a fulltext from any record type which isn't a chunked or fulltext can be serialised and deserialised successfully.
1604
            }
1605
1606
    def read(self):
1607
        """Read the stream.
1608
1609
        :return: An iterator as per VersionedFiles.get_record_stream().
1610
        """
1611
        for bytes in self._bytes_iterator:
1612
            storage_kind, line_end = network_bytes_to_kind_and_offset(bytes)
4005.3.6 by Robert Collins
Support delta_closure=True with NetworkRecordStream to transmit deltas over the wire when full text extraction is required on the far end.
1613
            for record in self._kind_factory[storage_kind](
1614
                storage_kind, bytes, line_end):
1615
                yield record
4022.1.6 by Robert Collins
Cherrypick and polish the RemoteSink for streaming push.
1616
1617
1618
def fulltext_network_to_record(kind, bytes, line_end):
1619
    """Convert a network fulltext record to record."""
1620
    meta_len, = struct.unpack('!L', bytes[line_end:line_end+4])
4060.1.4 by Robert Collins
Streaming fetch from remote servers.
1621
    record_meta = bytes[line_end+4:line_end+4+meta_len]
4022.1.6 by Robert Collins
Cherrypick and polish the RemoteSink for streaming push.
1622
    key, parents = bencode.bdecode_as_tuple(record_meta)
1623
    if parents == 'nil':
1624
        parents = None
4060.1.4 by Robert Collins
Streaming fetch from remote servers.
1625
    fulltext = bytes[line_end+4+meta_len:]
1626
    return [FulltextContentFactory(key, parents, None, fulltext)]
4022.1.6 by Robert Collins
Cherrypick and polish the RemoteSink for streaming push.
1627
1628
1629
def _length_prefix(bytes):
1630
    return struct.pack('!L', len(bytes))
1631
1632
4060.1.4 by Robert Collins
Streaming fetch from remote servers.
1633
def record_to_fulltext_bytes(record):
4022.1.6 by Robert Collins
Cherrypick and polish the RemoteSink for streaming push.
1634
    if record.parents is None:
1635
        parents = 'nil'
1636
    else:
1637
        parents = record.parents
1638
    record_meta = bencode.bencode((record.key, parents))
1639
    record_content = record.get_bytes_as('fulltext')
1640
    return "fulltext\n%s%s%s" % (
1641
        _length_prefix(record_meta), record_meta, record_content)
4111.1.1 by Robert Collins
Add a groupcompress sort order.
1642
1643
1644
def sort_groupcompress(parent_map):
1645
    """Sort and group the keys in parent_map into groupcompress order.
1646
1647
    groupcompress is defined (currently) as reverse-topological order, grouped
1648
    by the key prefix.
1649
1650
    :return: A sorted-list of keys
1651
    """
1652
    # gc-optimal ordering is approximately reverse topological,
1653
    # properly grouped by file-id.
1654
    per_prefix_map = {}
1655
    for item in parent_map.iteritems():
1656
        key = item[0]
1657
        if isinstance(key, str) or len(key) == 1:
1658
            prefix = ''
1659
        else:
1660
            prefix = key[0]
1661
        try:
1662
            per_prefix_map[prefix].append(item)
1663
        except KeyError:
1664
            per_prefix_map[prefix] = [item]
1665
1666
    present_keys = []
1667
    for prefix in sorted(per_prefix_map):
1668
        present_keys.extend(reversed(tsort.topo_sort(per_prefix_map[prefix])))
1669
    return present_keys