/brz/remove-bazaar

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