/brz/remove-bazaar

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