/brz/remove-bazaar

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