~bzr-pqm/bzr/bzr.dev

« back to all changes in this revision

Viewing changes to bzrlib/versionedfile.py

  • Committer: Aaron Bentley
  • Date: 2006-06-21 14:30:57 UTC
  • mfrom: (1801.1.1 bzr.dev)
  • mto: This revision was merged to the branch mainline in revision 1803.
  • Revision ID: abentley@panoramicfeedback.com-20060621143057-776e4b8d707e430e
Install benchmarks. (Jelmer Vernooij)

Show diffs side-by-side

added added

removed removed

Lines of Context:
1
 
# Copyright (C) 2005, 2006, 2007, 2008 Canonical Ltd
 
1
# Copyright (C) 2005, 2006 by Canonical Ltd
2
2
#
3
3
# Authors:
4
4
#   Johan Rydberg <jrydberg@gnu.org>
7
7
# it under the terms of the GNU General Public License as published by
8
8
# the Free Software Foundation; either version 2 of the License, or
9
9
# (at your option) any later version.
10
 
#
 
10
 
11
11
# This program is distributed in the hope that it will be useful,
12
12
# but WITHOUT ANY WARRANTY; without even the implied warranty of
13
13
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14
14
# GNU General Public License for more details.
15
 
#
 
15
 
16
16
# You should have received a copy of the GNU General Public License
17
17
# along with this program; if not, write to the Free Software
18
 
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
 
18
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
19
19
 
20
20
"""Versioned text file storage api."""
21
21
 
22
 
from copy import copy
23
 
from cStringIO import StringIO
24
 
import os
25
 
import struct
26
 
from zlib import adler32
27
 
 
28
 
from bzrlib.lazy_import import lazy_import
29
 
lazy_import(globals(), """
30
 
import urllib
31
 
 
32
 
from bzrlib import (
33
 
    annotate,
34
 
    errors,
35
 
    graph as _mod_graph,
36
 
    groupcompress,
37
 
    index,
38
 
    knit,
39
 
    osutils,
40
 
    multiparent,
41
 
    tsort,
42
 
    revision,
43
 
    ui,
44
 
    )
45
 
from bzrlib.graph import DictParentsProvider, Graph, StackedParentsProvider
46
 
from bzrlib.transport.memory import MemoryTransport
47
 
""")
 
22
 
 
23
from copy import deepcopy
 
24
from unittest import TestSuite
 
25
 
 
26
 
 
27
import bzrlib.errors as errors
48
28
from bzrlib.inter import InterObject
49
 
from bzrlib.registry import Registry
50
 
from bzrlib.symbol_versioning import *
51
29
from bzrlib.textmerge import TextMerge
52
 
from bzrlib import bencode
53
 
 
54
 
 
55
 
adapter_registry = Registry()
56
 
adapter_registry.register_lazy(('knit-delta-gz', 'fulltext'), 'bzrlib.knit',
57
 
    'DeltaPlainToFullText')
58
 
adapter_registry.register_lazy(('knit-ft-gz', 'fulltext'), 'bzrlib.knit',
59
 
    'FTPlainToFullText')
60
 
adapter_registry.register_lazy(('knit-annotated-delta-gz', 'knit-delta-gz'),
61
 
    'bzrlib.knit', 'DeltaAnnotatedToUnannotated')
62
 
adapter_registry.register_lazy(('knit-annotated-delta-gz', 'fulltext'),
63
 
    'bzrlib.knit', 'DeltaAnnotatedToFullText')
64
 
adapter_registry.register_lazy(('knit-annotated-ft-gz', 'knit-ft-gz'),
65
 
    'bzrlib.knit', 'FTAnnotatedToUnannotated')
66
 
adapter_registry.register_lazy(('knit-annotated-ft-gz', 'fulltext'),
67
 
    'bzrlib.knit', 'FTAnnotatedToFullText')
68
 
# adapter_registry.register_lazy(('knit-annotated-ft-gz', 'chunked'),
69
 
#     'bzrlib.knit', 'FTAnnotatedToChunked')
70
 
 
71
 
 
72
 
class ContentFactory(object):
73
 
    """Abstract interface for insertion and retrieval from a VersionedFile.
74
 
 
75
 
    :ivar sha1: None, or the sha1 of the content fulltext.
76
 
    :ivar storage_kind: The native storage kind of this factory. One of
77
 
        'mpdiff', 'knit-annotated-ft', 'knit-annotated-delta', 'knit-ft',
78
 
        'knit-delta', 'fulltext', 'knit-annotated-ft-gz',
79
 
        'knit-annotated-delta-gz', 'knit-ft-gz', 'knit-delta-gz'.
80
 
    :ivar key: The key of this content. Each key is a tuple with a single
81
 
        string in it.
82
 
    :ivar parents: A tuple of parent keys for self.key. If the object has
83
 
        no parent information, None (as opposed to () for an empty list of
84
 
        parents).
85
 
    """
86
 
 
87
 
    def __init__(self):
88
 
        """Create a ContentFactory."""
89
 
        self.sha1 = None
90
 
        self.storage_kind = None
91
 
        self.key = None
92
 
        self.parents = None
93
 
 
94
 
 
95
 
class ChunkedContentFactory(ContentFactory):
96
 
    """Static data content factory.
97
 
 
98
 
    This takes a 'chunked' list of strings. The only requirement on 'chunked' is
99
 
    that ''.join(lines) becomes a valid fulltext. A tuple of a single string
100
 
    satisfies this, as does a list of lines.
101
 
 
102
 
    :ivar sha1: None, or the sha1 of the content fulltext.
103
 
    :ivar storage_kind: The native storage kind of this factory. Always
104
 
        'chunked'
105
 
    :ivar key: The key of this content. Each key is a tuple with a single
106
 
        string in it.
107
 
    :ivar parents: A tuple of parent keys for self.key. If the object has
108
 
        no parent information, None (as opposed to () for an empty list of
109
 
        parents).
110
 
     """
111
 
 
112
 
    def __init__(self, key, parents, sha1, chunks):
113
 
        """Create a ContentFactory."""
114
 
        self.sha1 = sha1
115
 
        self.storage_kind = 'chunked'
116
 
        self.key = key
117
 
        self.parents = parents
118
 
        self._chunks = chunks
119
 
 
120
 
    def get_bytes_as(self, storage_kind):
121
 
        if storage_kind == 'chunked':
122
 
            return self._chunks
123
 
        elif storage_kind == 'fulltext':
124
 
            return ''.join(self._chunks)
125
 
        raise errors.UnavailableRepresentation(self.key, storage_kind,
126
 
            self.storage_kind)
127
 
 
128
 
 
129
 
class FulltextContentFactory(ContentFactory):
130
 
    """Static data content factory.
131
 
 
132
 
    This takes a fulltext when created and just returns that during
133
 
    get_bytes_as('fulltext').
134
 
 
135
 
    :ivar sha1: None, or the sha1 of the content fulltext.
136
 
    :ivar storage_kind: The native storage kind of this factory. Always
137
 
        'fulltext'.
138
 
    :ivar key: The key of this content. Each key is a tuple with a single
139
 
        string in it.
140
 
    :ivar parents: A tuple of parent keys for self.key. If the object has
141
 
        no parent information, None (as opposed to () for an empty list of
142
 
        parents).
143
 
     """
144
 
 
145
 
    def __init__(self, key, parents, sha1, text):
146
 
        """Create a ContentFactory."""
147
 
        self.sha1 = sha1
148
 
        self.storage_kind = 'fulltext'
149
 
        self.key = key
150
 
        self.parents = parents
151
 
        self._text = text
152
 
 
153
 
    def get_bytes_as(self, storage_kind):
154
 
        if storage_kind == self.storage_kind:
155
 
            return self._text
156
 
        elif storage_kind == 'chunked':
157
 
            return [self._text]
158
 
        raise errors.UnavailableRepresentation(self.key, storage_kind,
159
 
            self.storage_kind)
160
 
 
161
 
 
162
 
class AbsentContentFactory(ContentFactory):
163
 
    """A placeholder content factory for unavailable texts.
164
 
 
165
 
    :ivar sha1: None.
166
 
    :ivar storage_kind: 'absent'.
167
 
    :ivar key: The key of this content. Each key is a tuple with a single
168
 
        string in it.
169
 
    :ivar parents: None.
170
 
    """
171
 
 
172
 
    def __init__(self, key):
173
 
        """Create a ContentFactory."""
174
 
        self.sha1 = None
175
 
        self.storage_kind = 'absent'
176
 
        self.key = key
177
 
        self.parents = None
178
 
 
179
 
    def get_bytes_as(self, storage_kind):
180
 
        raise ValueError('A request was made for key: %s, but that'
181
 
                         ' content is not available, and the calling'
182
 
                         ' code does not handle if it is missing.'
183
 
                         % (self.key,))
184
 
 
185
 
 
186
 
class AdapterFactory(ContentFactory):
187
 
    """A content factory to adapt between key prefix's."""
188
 
 
189
 
    def __init__(self, key, parents, adapted):
190
 
        """Create an adapter factory instance."""
191
 
        self.key = key
192
 
        self.parents = parents
193
 
        self._adapted = adapted
194
 
 
195
 
    def __getattr__(self, attr):
196
 
        """Return a member from the adapted object."""
197
 
        if attr in ('key', 'parents'):
198
 
            return self.__dict__[attr]
199
 
        else:
200
 
            return getattr(self._adapted, attr)
201
 
 
202
 
 
203
 
def filter_absent(record_stream):
204
 
    """Adapt a record stream to remove absent records."""
205
 
    for record in record_stream:
206
 
        if record.storage_kind != 'absent':
207
 
            yield record
 
30
from bzrlib.transport.memory import MemoryTransport
 
31
from bzrlib.tsort import topo_sort
 
32
from bzrlib import ui
 
33
from bzrlib.symbol_versioning import (deprecated_function,
 
34
        deprecated_method,
 
35
        zero_eight,
 
36
        )
208
37
 
209
38
 
210
39
class VersionedFile(object):
211
40
    """Versioned text file storage.
212
 
 
 
41
    
213
42
    A versioned file manages versions of line-based text files,
214
43
    keeping track of the originating version for each line.
215
44
 
221
50
    Texts are identified by a version-id string.
222
51
    """
223
52
 
224
 
    @staticmethod
225
 
    def check_not_reserved_id(version_id):
226
 
        revision.check_not_reserved_id(version_id)
 
53
    def __init__(self, access_mode):
 
54
        self.finished = False
 
55
        self._access_mode = access_mode
227
56
 
228
57
    def copy_to(self, name, transport):
229
58
        """Copy this versioned file to name on transport."""
230
59
        raise NotImplementedError(self.copy_to)
231
 
 
232
 
    def get_record_stream(self, versions, ordering, include_delta_closure):
233
 
        """Get a stream of records for versions.
234
 
 
235
 
        :param versions: The versions to include. Each version is a tuple
236
 
            (version,).
237
 
        :param ordering: Either 'unordered' or 'topological'. A topologically
238
 
            sorted stream has compression parents strictly before their
239
 
            children.
240
 
        :param include_delta_closure: If True then the closure across any
241
 
            compression parents will be included (in the data content of the
242
 
            stream, not in the emitted records). This guarantees that
243
 
            'fulltext' can be used successfully on every record.
244
 
        :return: An iterator of ContentFactory objects, each of which is only
245
 
            valid until the iterator is advanced.
 
60
    
 
61
    @deprecated_method(zero_eight)
 
62
    def names(self):
 
63
        """Return a list of all the versions in this versioned file.
 
64
 
 
65
        Please use versionedfile.versions() now.
246
66
        """
247
 
        raise NotImplementedError(self.get_record_stream)
 
67
        return self.versions()
 
68
 
 
69
    def versions(self):
 
70
        """Return a unsorted list of versions."""
 
71
        raise NotImplementedError(self.versions)
 
72
 
 
73
    def has_ghost(self, version_id):
 
74
        """Returns whether version is present as a ghost."""
 
75
        raise NotImplementedError(self.has_ghost)
248
76
 
249
77
    def has_version(self, version_id):
250
78
        """Returns whether version is present."""
251
79
        raise NotImplementedError(self.has_version)
252
80
 
253
 
    def insert_record_stream(self, stream):
254
 
        """Insert a record stream into this versioned file.
255
 
 
256
 
        :param stream: A stream of records to insert.
257
 
        :return: None
258
 
        :seealso VersionedFile.get_record_stream:
259
 
        """
260
 
        raise NotImplementedError
261
 
 
262
 
    def add_lines(self, version_id, parents, lines, parent_texts=None,
263
 
        left_matching_blocks=None, nostore_sha=None, random_id=False,
264
 
        check_content=True):
 
81
    def add_delta(self, version_id, parents, delta_parent, sha1, noeol, delta):
 
82
        """Add a text to the versioned file via a pregenerated delta.
 
83
 
 
84
        :param version_id: The version id being added.
 
85
        :param parents: The parents of the version_id.
 
86
        :param delta_parent: The parent this delta was created against.
 
87
        :param sha1: The sha1 of the full text.
 
88
        :param delta: The delta instructions. See get_delta for details.
 
89
        """
 
90
        self._check_write_ok()
 
91
        if self.has_version(version_id):
 
92
            raise errors.RevisionAlreadyPresent(version_id, self)
 
93
        return self._add_delta(version_id, parents, delta_parent, sha1, noeol, delta)
 
94
 
 
95
    def _add_delta(self, version_id, parents, delta_parent, sha1, noeol, delta):
 
96
        """Class specific routine to add a delta.
 
97
 
 
98
        This generic version simply applies the delta to the delta_parent and
 
99
        then inserts it.
 
100
        """
 
101
        # strip annotation from delta
 
102
        new_delta = []
 
103
        for start, stop, delta_len, delta_lines in delta:
 
104
            new_delta.append((start, stop, delta_len, [text for origin, text in delta_lines]))
 
105
        if delta_parent is not None:
 
106
            parent_full = self.get_lines(delta_parent)
 
107
        else:
 
108
            parent_full = []
 
109
        new_full = self._apply_delta(parent_full, new_delta)
 
110
        # its impossible to have noeol on an empty file
 
111
        if noeol and new_full[-1][-1] == '\n':
 
112
            new_full[-1] = new_full[-1][:-1]
 
113
        self.add_lines(version_id, parents, new_full)
 
114
 
 
115
    def add_lines(self, version_id, parents, lines, parent_texts=None):
265
116
        """Add a single text on top of the versioned file.
266
117
 
267
118
        Must raise RevisionAlreadyPresent if the new version is
269
120
 
270
121
        Must raise RevisionNotPresent if any of the given parents are
271
122
        not present in file history.
272
 
 
273
 
        :param lines: A list of lines. Each line must be a bytestring. And all
274
 
            of them except the last must be terminated with \n and contain no
275
 
            other \n's. The last line may either contain no \n's or a single
276
 
            terminated \n. If the lines list does meet this constraint the add
277
 
            routine may error or may succeed - but you will be unable to read
278
 
            the data back accurately. (Checking the lines have been split
279
 
            correctly is expensive and extremely unlikely to catch bugs so it
280
 
            is not done at runtime unless check_content is True.)
281
 
        :param parent_texts: An optional dictionary containing the opaque
282
 
            representations of some or all of the parents of version_id to
283
 
            allow delta optimisations.  VERY IMPORTANT: the texts must be those
284
 
            returned by add_lines or data corruption can be caused.
285
 
        :param left_matching_blocks: a hint about which areas are common
286
 
            between the text and its left-hand-parent.  The format is
287
 
            the SequenceMatcher.get_matching_blocks format.
288
 
        :param nostore_sha: Raise ExistingContent and do not add the lines to
289
 
            the versioned file if the digest of the lines matches this.
290
 
        :param random_id: If True a random id has been selected rather than
291
 
            an id determined by some deterministic process such as a converter
292
 
            from a foreign VCS. When True the backend may choose not to check
293
 
            for uniqueness of the resulting key within the versioned file, so
294
 
            this should only be done when the result is expected to be unique
295
 
            anyway.
296
 
        :param check_content: If True, the lines supplied are verified to be
297
 
            bytestrings that are correctly formed lines.
298
 
        :return: The text sha1, the number of bytes in the text, and an opaque
299
 
                 representation of the inserted version which can be provided
300
 
                 back to future add_lines calls in the parent_texts dictionary.
 
123
        :param parent_texts: An optional dictionary containing the opaque 
 
124
             representations of some or all of the parents of 
 
125
             version_id to allow delta optimisations. 
 
126
             VERY IMPORTANT: the texts must be those returned
 
127
             by add_lines or data corruption can be caused.
 
128
        :return: An opaque representation of the inserted version which can be
 
129
                 provided back to future add_lines calls in the parent_texts
 
130
                 dictionary.
301
131
        """
302
132
        self._check_write_ok()
303
 
        return self._add_lines(version_id, parents, lines, parent_texts,
304
 
            left_matching_blocks, nostore_sha, random_id, check_content)
 
133
        return self._add_lines(version_id, parents, lines, parent_texts)
305
134
 
306
 
    def _add_lines(self, version_id, parents, lines, parent_texts,
307
 
        left_matching_blocks, nostore_sha, random_id, check_content):
 
135
    def _add_lines(self, version_id, parents, lines, parent_texts):
308
136
        """Helper to do the class specific add_lines."""
309
137
        raise NotImplementedError(self.add_lines)
310
138
 
311
139
    def add_lines_with_ghosts(self, version_id, parents, lines,
312
 
        parent_texts=None, nostore_sha=None, random_id=False,
313
 
        check_content=True, left_matching_blocks=None):
 
140
                              parent_texts=None):
314
141
        """Add lines to the versioned file, allowing ghosts to be present.
315
 
 
316
 
        This takes the same parameters as add_lines and returns the same.
 
142
        
 
143
        This takes the same parameters as add_lines.
317
144
        """
318
145
        self._check_write_ok()
319
146
        return self._add_lines_with_ghosts(version_id, parents, lines,
320
 
            parent_texts, nostore_sha, random_id, check_content, left_matching_blocks)
 
147
                                           parent_texts)
321
148
 
322
 
    def _add_lines_with_ghosts(self, version_id, parents, lines, parent_texts,
323
 
        nostore_sha, random_id, check_content, left_matching_blocks):
 
149
    def _add_lines_with_ghosts(self, version_id, parents, lines, parent_texts):
324
150
        """Helper to do class specific add_lines_with_ghosts."""
325
151
        raise NotImplementedError(self.add_lines_with_ghosts)
326
152
 
340
166
            if '\n' in line[:-1]:
341
167
                raise errors.BzrBadParameterContainsNewline("lines")
342
168
 
343
 
    def get_format_signature(self):
344
 
        """Get a text description of the data encoding in this file.
345
 
 
346
 
        :since: 0.90
347
 
        """
348
 
        raise NotImplementedError(self.get_format_signature)
349
 
 
350
 
    def make_mpdiffs(self, version_ids):
351
 
        """Create multiparent diffs for specified versions."""
352
 
        knit_versions = set()
353
 
        knit_versions.update(version_ids)
354
 
        parent_map = self.get_parent_map(version_ids)
355
 
        for version_id in version_ids:
356
 
            try:
357
 
                knit_versions.update(parent_map[version_id])
358
 
            except KeyError:
359
 
                raise errors.RevisionNotPresent(version_id, self)
360
 
        # We need to filter out ghosts, because we can't diff against them.
361
 
        knit_versions = set(self.get_parent_map(knit_versions).keys())
362
 
        lines = dict(zip(knit_versions,
363
 
            self._get_lf_split_line_list(knit_versions)))
364
 
        diffs = []
365
 
        for version_id in version_ids:
366
 
            target = lines[version_id]
367
 
            try:
368
 
                parents = [lines[p] for p in parent_map[version_id] if p in
369
 
                    knit_versions]
370
 
            except KeyError:
371
 
                # I don't know how this could ever trigger.
372
 
                # parent_map[version_id] was already triggered in the previous
373
 
                # for loop, and lines[p] has the 'if p in knit_versions' check,
374
 
                # so we again won't have a KeyError.
375
 
                raise errors.RevisionNotPresent(version_id, self)
376
 
            if len(parents) > 0:
377
 
                left_parent_blocks = self._extract_blocks(version_id,
378
 
                                                          parents[0], target)
379
 
            else:
380
 
                left_parent_blocks = None
381
 
            diffs.append(multiparent.MultiParent.from_lines(target, parents,
382
 
                         left_parent_blocks))
383
 
        return diffs
384
 
 
385
 
    def _extract_blocks(self, version_id, source, target):
386
 
        return None
387
 
 
388
 
    def add_mpdiffs(self, records):
389
 
        """Add mpdiffs to this VersionedFile.
390
 
 
391
 
        Records should be iterables of version, parents, expected_sha1,
392
 
        mpdiff. mpdiff should be a MultiParent instance.
393
 
        """
394
 
        # Does this need to call self._check_write_ok()? (IanC 20070919)
395
 
        vf_parents = {}
396
 
        mpvf = multiparent.MultiMemoryVersionedFile()
397
 
        versions = []
398
 
        for version, parent_ids, expected_sha1, mpdiff in records:
399
 
            versions.append(version)
400
 
            mpvf.add_diff(mpdiff, version, parent_ids)
401
 
        needed_parents = set()
402
 
        for version, parent_ids, expected_sha1, mpdiff in records:
403
 
            needed_parents.update(p for p in parent_ids
404
 
                                  if not mpvf.has_version(p))
405
 
        present_parents = set(self.get_parent_map(needed_parents).keys())
406
 
        for parent_id, lines in zip(present_parents,
407
 
                                 self._get_lf_split_line_list(present_parents)):
408
 
            mpvf.add_version(lines, parent_id, [])
409
 
        for (version, parent_ids, expected_sha1, mpdiff), lines in\
410
 
            zip(records, mpvf.get_line_list(versions)):
411
 
            if len(parent_ids) == 1:
412
 
                left_matching_blocks = list(mpdiff.get_matching_blocks(0,
413
 
                    mpvf.get_diff(parent_ids[0]).num_lines()))
414
 
            else:
415
 
                left_matching_blocks = None
416
 
            try:
417
 
                _, _, version_text = self.add_lines_with_ghosts(version,
418
 
                    parent_ids, lines, vf_parents,
419
 
                    left_matching_blocks=left_matching_blocks)
420
 
            except NotImplementedError:
421
 
                # The vf can't handle ghosts, so add lines normally, which will
422
 
                # (reasonably) fail if there are ghosts in the data.
423
 
                _, _, version_text = self.add_lines(version,
424
 
                    parent_ids, lines, vf_parents,
425
 
                    left_matching_blocks=left_matching_blocks)
426
 
            vf_parents[version] = version_text
427
 
        sha1s = self.get_sha1s(versions)
428
 
        for version, parent_ids, expected_sha1, mpdiff in records:
429
 
            if expected_sha1 != sha1s[version]:
430
 
                raise errors.VersionedFileInvalidChecksum(version)
431
 
 
 
169
    def _check_write_ok(self):
 
170
        """Is the versioned file marked as 'finished' ? Raise if it is."""
 
171
        if self.finished:
 
172
            raise errors.OutSideTransaction()
 
173
        if self._access_mode != 'w':
 
174
            raise errors.ReadOnlyObjectDirtiedError(self)
 
175
 
 
176
    def clear_cache(self):
 
177
        """Remove any data cached in the versioned file object."""
 
178
 
 
179
    def clone_text(self, new_version_id, old_version_id, parents):
 
180
        """Add an identical text to old_version_id as new_version_id.
 
181
 
 
182
        Must raise RevisionNotPresent if the old version or any of the
 
183
        parents are not present in file history.
 
184
 
 
185
        Must raise RevisionAlreadyPresent if the new version is
 
186
        already present in file history."""
 
187
        self._check_write_ok()
 
188
        return self._clone_text(new_version_id, old_version_id, parents)
 
189
 
 
190
    def _clone_text(self, new_version_id, old_version_id, parents):
 
191
        """Helper function to do the _clone_text work."""
 
192
        raise NotImplementedError(self.clone_text)
 
193
 
 
194
    def create_empty(self, name, transport, mode=None):
 
195
        """Create a new versioned file of this exact type.
 
196
 
 
197
        :param name: the file name
 
198
        :param transport: the transport
 
199
        :param mode: optional file mode.
 
200
        """
 
201
        raise NotImplementedError(self.create_empty)
 
202
 
 
203
    def fix_parents(self, version, new_parents):
 
204
        """Fix the parents list for version.
 
205
        
 
206
        This is done by appending a new version to the index
 
207
        with identical data except for the parents list.
 
208
        the parents list must be a superset of the current
 
209
        list.
 
210
        """
 
211
        self._check_write_ok()
 
212
        return self._fix_parents(version, new_parents)
 
213
 
 
214
    def _fix_parents(self, version, new_parents):
 
215
        """Helper for fix_parents."""
 
216
        raise NotImplementedError(self.fix_parents)
 
217
 
 
218
    def get_delta(self, version):
 
219
        """Get a delta for constructing version from some other version.
 
220
        
 
221
        :return: (delta_parent, sha1, noeol, delta)
 
222
        Where delta_parent is a version id or None to indicate no parent.
 
223
        """
 
224
        raise NotImplementedError(self.get_delta)
 
225
 
 
226
    def get_deltas(self, versions):
 
227
        """Get multiple deltas at once for constructing versions.
 
228
        
 
229
        :return: dict(version_id:(delta_parent, sha1, noeol, delta))
 
230
        Where delta_parent is a version id or None to indicate no parent, and
 
231
        version_id is the version_id created by that delta.
 
232
        """
 
233
        result = {}
 
234
        for version in versions:
 
235
            result[version] = self.get_delta(version)
 
236
        return result
 
237
 
 
238
    def get_sha1(self, version_id):
 
239
        """Get the stored sha1 sum for the given revision.
 
240
        
 
241
        :param name: The name of the version to lookup
 
242
        """
 
243
        raise NotImplementedError(self.get_sha1)
 
244
 
 
245
    def get_suffixes(self):
 
246
        """Return the file suffixes associated with this versioned file."""
 
247
        raise NotImplementedError(self.get_suffixes)
 
248
    
432
249
    def get_text(self, version_id):
433
250
        """Return version contents as a text string.
434
251
 
454
271
        """
455
272
        raise NotImplementedError(self.get_lines)
456
273
 
457
 
    def _get_lf_split_line_list(self, version_ids):
458
 
        return [StringIO(t).readlines() for t in self.get_texts(version_ids)]
459
 
 
460
 
    def get_ancestry(self, version_ids, topo_sorted=True):
 
274
    def get_ancestry(self, version_ids):
461
275
        """Return a list of all ancestors of given version(s). This
462
276
        will not include the null revision.
463
277
 
464
 
        This list will not be topologically sorted if topo_sorted=False is
465
 
        passed.
466
 
 
467
278
        Must raise RevisionNotPresent if any of the given versions are
468
279
        not present in file history."""
469
280
        if isinstance(version_ids, basestring):
470
281
            version_ids = [version_ids]
471
282
        raise NotImplementedError(self.get_ancestry)
472
 
 
 
283
        
473
284
    def get_ancestry_with_ghosts(self, version_ids):
474
285
        """Return a list of all ancestors of given version(s). This
475
286
        will not include the null revision.
476
287
 
477
288
        Must raise RevisionNotPresent if any of the given versions are
478
289
        not present in file history.
479
 
 
 
290
        
480
291
        Ghosts that are known about will be included in ancestry list,
481
292
        but are not explicitly marked.
482
293
        """
483
294
        raise NotImplementedError(self.get_ancestry_with_ghosts)
484
 
 
485
 
    def get_parent_map(self, version_ids):
486
 
        """Get a map of the parents of version_ids.
487
 
 
488
 
        :param version_ids: The version ids to look up parents for.
489
 
        :return: A mapping from version id to parents.
490
 
        """
491
 
        raise NotImplementedError(self.get_parent_map)
 
295
        
 
296
    def get_graph(self, version_ids=None):
 
297
        """Return a graph from the versioned file. 
 
298
        
 
299
        Ghosts are not listed or referenced in the graph.
 
300
        :param version_ids: Versions to select.
 
301
                            None means retrieve all versions.
 
302
        """
 
303
        result = {}
 
304
        if version_ids is None:
 
305
            for version in self.versions():
 
306
                result[version] = self.get_parents(version)
 
307
        else:
 
308
            pending = set(version_ids)
 
309
            while pending:
 
310
                version = pending.pop()
 
311
                if version in result:
 
312
                    continue
 
313
                parents = self.get_parents(version)
 
314
                for parent in parents:
 
315
                    if parent in result:
 
316
                        continue
 
317
                    pending.add(parent)
 
318
                result[version] = parents
 
319
        return result
 
320
 
 
321
    def get_graph_with_ghosts(self):
 
322
        """Return a graph for the entire versioned file.
 
323
        
 
324
        Ghosts are referenced in parents list but are not
 
325
        explicitly listed.
 
326
        """
 
327
        raise NotImplementedError(self.get_graph_with_ghosts)
 
328
 
 
329
    @deprecated_method(zero_eight)
 
330
    def parent_names(self, version):
 
331
        """Return version names for parents of a version.
 
332
        
 
333
        See get_parents for the current api.
 
334
        """
 
335
        return self.get_parents(version)
 
336
 
 
337
    def get_parents(self, version_id):
 
338
        """Return version names for parents of a version.
 
339
 
 
340
        Must raise RevisionNotPresent if version is not present in
 
341
        file history.
 
342
        """
 
343
        raise NotImplementedError(self.get_parents)
492
344
 
493
345
    def get_parents_with_ghosts(self, version_id):
494
346
        """Return version names for parents of version_id.
499
351
        Ghosts that are known about will be included in the parent list,
500
352
        but are not explicitly marked.
501
353
        """
502
 
        try:
503
 
            return list(self.get_parent_map([version_id])[version_id])
504
 
        except KeyError:
505
 
            raise errors.RevisionNotPresent(version_id, self)
 
354
        raise NotImplementedError(self.get_parents_with_ghosts)
 
355
 
 
356
    def annotate_iter(self, version_id):
 
357
        """Yield list of (version-id, line) pairs for the specified
 
358
        version.
 
359
 
 
360
        Must raise RevisionNotPresent if any of the given versions are
 
361
        not present in file history.
 
362
        """
 
363
        raise NotImplementedError(self.annotate_iter)
506
364
 
507
365
    def annotate(self, version_id):
508
 
        """Return a list of (version-id, line) tuples for version_id.
509
 
 
510
 
        :raise RevisionNotPresent: If the given version is
511
 
        not present in file history.
 
366
        return list(self.annotate_iter(version_id))
 
367
 
 
368
    def _apply_delta(self, lines, delta):
 
369
        """Apply delta to lines."""
 
370
        lines = list(lines)
 
371
        offset = 0
 
372
        for start, end, count, delta_lines in delta:
 
373
            lines[offset+start:offset+end] = delta_lines
 
374
            offset = offset + (start - end) + count
 
375
        return lines
 
376
 
 
377
    def join(self, other, pb=None, msg=None, version_ids=None,
 
378
             ignore_missing=False):
 
379
        """Integrate versions from other into this versioned file.
 
380
 
 
381
        If version_ids is None all versions from other should be
 
382
        incorporated into this versioned file.
 
383
 
 
384
        Must raise RevisionNotPresent if any of the specified versions
 
385
        are not present in the other files history unless ignore_missing
 
386
        is supplied when they are silently skipped.
512
387
        """
513
 
        raise NotImplementedError(self.annotate)
 
388
        self._check_write_ok()
 
389
        return InterVersionedFile.get(other, self).join(
 
390
            pb,
 
391
            msg,
 
392
            version_ids,
 
393
            ignore_missing)
514
394
 
515
 
    def iter_lines_added_or_present_in_versions(self, version_ids=None,
516
 
                                                pb=None):
 
395
    def iter_lines_added_or_present_in_versions(self, version_ids=None):
517
396
        """Iterate over the lines in the versioned file from version_ids.
518
397
 
519
 
        This may return lines from other versions. Each item the returned
520
 
        iterator yields is a tuple of a line and a text version that that line
521
 
        is present in (not introduced in).
522
 
 
523
 
        Ordering of results is in whatever order is most suitable for the
524
 
        underlying storage format.
525
 
 
526
 
        If a progress bar is supplied, it may be used to indicate progress.
527
 
        The caller is responsible for cleaning up progress bars (because this
528
 
        is an iterator).
 
398
        This may return lines from other versions, and does not return the
 
399
        specific version marker at this point. The api may be changed
 
400
        during development to include the version that the versioned file
 
401
        thinks is relevant, but given that such hints are just guesses,
 
402
        its better not to have it if we don't need it.
529
403
 
530
404
        NOTES: Lines are normalised: they will all have \n terminators.
531
405
               Lines are returned in arbitrary order.
532
 
 
533
 
        :return: An iterator over (line, version_id).
534
406
        """
535
407
        raise NotImplementedError(self.iter_lines_added_or_present_in_versions)
536
408
 
 
409
    def transaction_finished(self):
 
410
        """The transaction that this file was opened in has finished.
 
411
 
 
412
        This records self.finished = True and should cause all mutating
 
413
        operations to error.
 
414
        """
 
415
        self.finished = True
 
416
 
 
417
    @deprecated_method(zero_eight)
 
418
    def walk(self, version_ids=None):
 
419
        """Walk the versioned file as a weave-like structure, for
 
420
        versions relative to version_ids.  Yields sequence of (lineno,
 
421
        insert, deletes, text) for each relevant line.
 
422
 
 
423
        Must raise RevisionNotPresent if any of the specified versions
 
424
        are not present in the file history.
 
425
 
 
426
        :param version_ids: the version_ids to walk with respect to. If not
 
427
                            supplied the entire weave-like structure is walked.
 
428
 
 
429
        walk is deprecated in favour of iter_lines_added_or_present_in_versions
 
430
        """
 
431
        raise NotImplementedError(self.walk)
 
432
 
 
433
    @deprecated_method(zero_eight)
 
434
    def iter_names(self):
 
435
        """Walk the names list."""
 
436
        return iter(self.versions())
 
437
 
537
438
    def plan_merge(self, ver_a, ver_b):
538
439
        """Return pseudo-annotation indicating how the two versions merge.
539
440
 
550
451
        unchanged   Alive in both a and b (possibly created in both)
551
452
        new-a       Created in a
552
453
        new-b       Created in b
553
 
        ghost-a     Killed in a, unborn in b
 
454
        ghost-a     Killed in a, unborn in b    
554
455
        ghost-b     Killed in b, unborn in a
555
456
        irrelevant  Not in either revision
556
457
        """
557
458
        raise NotImplementedError(VersionedFile.plan_merge)
558
 
 
559
 
    def weave_merge(self, plan, a_marker=TextMerge.A_MARKER,
 
459
        
 
460
    def weave_merge(self, plan, a_marker=TextMerge.A_MARKER, 
560
461
                    b_marker=TextMerge.B_MARKER):
561
462
        return PlanWeaveMerge(plan, a_marker, b_marker).merge_lines()[0]
562
463
 
563
464
 
564
 
class RecordingVersionedFilesDecorator(object):
565
 
    """A minimal versioned files that records calls made on it.
566
 
 
567
 
    Only enough methods have been added to support tests using it to date.
568
 
 
569
 
    :ivar calls: A list of the calls made; can be reset at any time by
570
 
        assigning [] to it.
571
 
    """
572
 
 
573
 
    def __init__(self, backing_vf):
574
 
        """Create a RecordingVersionedFilesDecorator decorating backing_vf.
575
 
 
576
 
        :param backing_vf: The versioned file to answer all methods.
577
 
        """
578
 
        self._backing_vf = backing_vf
579
 
        self.calls = []
580
 
 
581
 
    def add_lines(self, key, parents, lines, parent_texts=None,
582
 
        left_matching_blocks=None, nostore_sha=None, random_id=False,
583
 
        check_content=True):
584
 
        self.calls.append(("add_lines", key, parents, lines, parent_texts,
585
 
            left_matching_blocks, nostore_sha, random_id, check_content))
586
 
        return self._backing_vf.add_lines(key, parents, lines, parent_texts,
587
 
            left_matching_blocks, nostore_sha, random_id, check_content)
588
 
 
589
 
    def check(self):
590
 
        self._backing_vf.check()
591
 
 
592
 
    def get_parent_map(self, keys):
593
 
        self.calls.append(("get_parent_map", copy(keys)))
594
 
        return self._backing_vf.get_parent_map(keys)
595
 
 
596
 
    def get_record_stream(self, keys, sort_order, include_delta_closure):
597
 
        self.calls.append(("get_record_stream", list(keys), sort_order,
598
 
            include_delta_closure))
599
 
        return self._backing_vf.get_record_stream(keys, sort_order,
600
 
            include_delta_closure)
601
 
 
602
 
    def get_sha1s(self, keys):
603
 
        self.calls.append(("get_sha1s", copy(keys)))
604
 
        return self._backing_vf.get_sha1s(keys)
605
 
 
606
 
    def iter_lines_added_or_present_in_keys(self, keys, pb=None):
607
 
        self.calls.append(("iter_lines_added_or_present_in_keys", copy(keys)))
608
 
        return self._backing_vf.iter_lines_added_or_present_in_keys(keys, pb=pb)
609
 
 
610
 
    def keys(self):
611
 
        self.calls.append(("keys",))
612
 
        return self._backing_vf.keys()
613
 
 
614
 
 
615
 
class OrderingVersionedFilesDecorator(RecordingVersionedFilesDecorator):
616
 
    """A VF that records calls, and returns keys in specific order.
617
 
 
618
 
    :ivar calls: A list of the calls made; can be reset at any time by
619
 
        assigning [] to it.
620
 
    """
621
 
 
622
 
    def __init__(self, backing_vf, key_priority):
623
 
        """Create a RecordingVersionedFilesDecorator decorating backing_vf.
624
 
 
625
 
        :param backing_vf: The versioned file to answer all methods.
626
 
        :param key_priority: A dictionary defining what order keys should be
627
 
            returned from an 'unordered' get_record_stream request.
628
 
            Keys with lower priority are returned first, keys not present in
629
 
            the map get an implicit priority of 0, and are returned in
630
 
            lexicographical order.
631
 
        """
632
 
        RecordingVersionedFilesDecorator.__init__(self, backing_vf)
633
 
        self._key_priority = key_priority
634
 
 
635
 
    def get_record_stream(self, keys, sort_order, include_delta_closure):
636
 
        self.calls.append(("get_record_stream", list(keys), sort_order,
637
 
            include_delta_closure))
638
 
        if sort_order == 'unordered':
639
 
            def sort_key(key):
640
 
                return (self._key_priority.get(key, 0), key)
641
 
            # Use a defined order by asking for the keys one-by-one from the
642
 
            # backing_vf
643
 
            for key in sorted(keys, key=sort_key):
644
 
                for record in self._backing_vf.get_record_stream([key],
645
 
                                'unordered', include_delta_closure):
646
 
                    yield record
647
 
        else:
648
 
            for record in self._backing_vf.get_record_stream(keys, sort_order,
649
 
                            include_delta_closure):
650
 
                yield record
651
 
 
652
 
 
653
 
class KeyMapper(object):
654
 
    """KeyMappers map between keys and underlying partitioned storage."""
655
 
 
656
 
    def map(self, key):
657
 
        """Map key to an underlying storage identifier.
658
 
 
659
 
        :param key: A key tuple e.g. ('file-id', 'revision-id').
660
 
        :return: An underlying storage identifier, specific to the partitioning
661
 
            mechanism.
662
 
        """
663
 
        raise NotImplementedError(self.map)
664
 
 
665
 
    def unmap(self, partition_id):
666
 
        """Map a partitioned storage id back to a key prefix.
667
 
 
668
 
        :param partition_id: The underlying partition id.
669
 
        :return: As much of a key (or prefix) as is derivable from the partition
670
 
            id.
671
 
        """
672
 
        raise NotImplementedError(self.unmap)
673
 
 
674
 
 
675
 
class ConstantMapper(KeyMapper):
676
 
    """A key mapper that maps to a constant result."""
677
 
 
678
 
    def __init__(self, result):
679
 
        """Create a ConstantMapper which will return result for all maps."""
680
 
        self._result = result
681
 
 
682
 
    def map(self, key):
683
 
        """See KeyMapper.map()."""
684
 
        return self._result
685
 
 
686
 
 
687
 
class URLEscapeMapper(KeyMapper):
688
 
    """Base class for use with transport backed storage.
689
 
 
690
 
    This provides a map and unmap wrapper that respectively url escape and
691
 
    unescape their outputs and inputs.
692
 
    """
693
 
 
694
 
    def map(self, key):
695
 
        """See KeyMapper.map()."""
696
 
        return urllib.quote(self._map(key))
697
 
 
698
 
    def unmap(self, partition_id):
699
 
        """See KeyMapper.unmap()."""
700
 
        return self._unmap(urllib.unquote(partition_id))
701
 
 
702
 
 
703
 
class PrefixMapper(URLEscapeMapper):
704
 
    """A key mapper that extracts the first component of a key.
705
 
 
706
 
    This mapper is for use with a transport based backend.
707
 
    """
708
 
 
709
 
    def _map(self, key):
710
 
        """See KeyMapper.map()."""
711
 
        return key[0]
712
 
 
713
 
    def _unmap(self, partition_id):
714
 
        """See KeyMapper.unmap()."""
715
 
        return (partition_id,)
716
 
 
717
 
 
718
 
class HashPrefixMapper(URLEscapeMapper):
719
 
    """A key mapper that combines the first component of a key with a hash.
720
 
 
721
 
    This mapper is for use with a transport based backend.
722
 
    """
723
 
 
724
 
    def _map(self, key):
725
 
        """See KeyMapper.map()."""
726
 
        prefix = self._escape(key[0])
727
 
        return "%02x/%s" % (adler32(prefix) & 0xff, prefix)
728
 
 
729
 
    def _escape(self, prefix):
730
 
        """No escaping needed here."""
731
 
        return prefix
732
 
 
733
 
    def _unmap(self, partition_id):
734
 
        """See KeyMapper.unmap()."""
735
 
        return (self._unescape(osutils.basename(partition_id)),)
736
 
 
737
 
    def _unescape(self, basename):
738
 
        """No unescaping needed for HashPrefixMapper."""
739
 
        return basename
740
 
 
741
 
 
742
 
class HashEscapedPrefixMapper(HashPrefixMapper):
743
 
    """Combines the escaped first component of a key with a hash.
744
 
 
745
 
    This mapper is for use with a transport based backend.
746
 
    """
747
 
 
748
 
    _safe = "abcdefghijklmnopqrstuvwxyz0123456789-_@,."
749
 
 
750
 
    def _escape(self, prefix):
751
 
        """Turn a key element into a filesystem safe string.
752
 
 
753
 
        This is similar to a plain urllib.quote, except
754
 
        it uses specific safe characters, so that it doesn't
755
 
        have to translate a lot of valid file ids.
756
 
        """
757
 
        # @ does not get escaped. This is because it is a valid
758
 
        # filesystem character we use all the time, and it looks
759
 
        # a lot better than seeing %40 all the time.
760
 
        r = [((c in self._safe) and c or ('%%%02x' % ord(c)))
761
 
             for c in prefix]
762
 
        return ''.join(r)
763
 
 
764
 
    def _unescape(self, basename):
765
 
        """Escaped names are easily unescaped by urlutils."""
766
 
        return urllib.unquote(basename)
767
 
 
768
 
 
769
 
def make_versioned_files_factory(versioned_file_factory, mapper):
770
 
    """Create a ThunkedVersionedFiles factory.
771
 
 
772
 
    This will create a callable which when called creates a
773
 
    ThunkedVersionedFiles on a transport, using mapper to access individual
774
 
    versioned files, and versioned_file_factory to create each individual file.
775
 
    """
776
 
    def factory(transport):
777
 
        return ThunkedVersionedFiles(transport, versioned_file_factory, mapper,
778
 
            lambda:True)
779
 
    return factory
780
 
 
781
 
 
782
 
class VersionedFiles(object):
783
 
    """Storage for many versioned files.
784
 
 
785
 
    This object allows a single keyspace for accessing the history graph and
786
 
    contents of named bytestrings.
787
 
 
788
 
    Currently no implementation allows the graph of different key prefixes to
789
 
    intersect, but the API does allow such implementations in the future.
790
 
 
791
 
    The keyspace is expressed via simple tuples. Any instance of VersionedFiles
792
 
    may have a different length key-size, but that size will be constant for
793
 
    all texts added to or retrieved from it. For instance, bzrlib uses
794
 
    instances with a key-size of 2 for storing user files in a repository, with
795
 
    the first element the fileid, and the second the version of that file.
796
 
 
797
 
    The use of tuples allows a single code base to support several different
798
 
    uses with only the mapping logic changing from instance to instance.
799
 
    """
800
 
 
801
 
    def add_lines(self, key, parents, lines, parent_texts=None,
802
 
        left_matching_blocks=None, nostore_sha=None, random_id=False,
803
 
        check_content=True):
804
 
        """Add a text to the store.
805
 
 
806
 
        :param key: The key tuple of the text to add. If the last element is
807
 
            None, a CHK string will be generated during the addition.
808
 
        :param parents: The parents key tuples of the text to add.
809
 
        :param lines: A list of lines. Each line must be a bytestring. And all
810
 
            of them except the last must be terminated with \n and contain no
811
 
            other \n's. The last line may either contain no \n's or a single
812
 
            terminating \n. If the lines list does meet this constraint the add
813
 
            routine may error or may succeed - but you will be unable to read
814
 
            the data back accurately. (Checking the lines have been split
815
 
            correctly is expensive and extremely unlikely to catch bugs so it
816
 
            is not done at runtime unless check_content is True.)
817
 
        :param parent_texts: An optional dictionary containing the opaque
818
 
            representations of some or all of the parents of version_id to
819
 
            allow delta optimisations.  VERY IMPORTANT: the texts must be those
820
 
            returned by add_lines or data corruption can be caused.
821
 
        :param left_matching_blocks: a hint about which areas are common
822
 
            between the text and its left-hand-parent.  The format is
823
 
            the SequenceMatcher.get_matching_blocks format.
824
 
        :param nostore_sha: Raise ExistingContent and do not add the lines to
825
 
            the versioned file if the digest of the lines matches this.
826
 
        :param random_id: If True a random id has been selected rather than
827
 
            an id determined by some deterministic process such as a converter
828
 
            from a foreign VCS. When True the backend may choose not to check
829
 
            for uniqueness of the resulting key within the versioned file, so
830
 
            this should only be done when the result is expected to be unique
831
 
            anyway.
832
 
        :param check_content: If True, the lines supplied are verified to be
833
 
            bytestrings that are correctly formed lines.
834
 
        :return: The text sha1, the number of bytes in the text, and an opaque
835
 
                 representation of the inserted version which can be provided
836
 
                 back to future add_lines calls in the parent_texts dictionary.
837
 
        """
838
 
        raise NotImplementedError(self.add_lines)
839
 
 
840
 
    def _add_text(self, key, parents, text, nostore_sha=None, random_id=False):
841
 
        """Add a text to the store.
842
 
 
843
 
        This is a private function for use by CommitBuilder.
844
 
 
845
 
        :param key: The key tuple of the text to add. If the last element is
846
 
            None, a CHK string will be generated during the addition.
847
 
        :param parents: The parents key tuples of the text to add.
848
 
        :param text: A string containing the text to be committed.
849
 
        :param nostore_sha: Raise ExistingContent and do not add the lines to
850
 
            the versioned file if the digest of the lines matches this.
851
 
        :param random_id: If True a random id has been selected rather than
852
 
            an id determined by some deterministic process such as a converter
853
 
            from a foreign VCS. When True the backend may choose not to check
854
 
            for uniqueness of the resulting key within the versioned file, so
855
 
            this should only be done when the result is expected to be unique
856
 
            anyway.
857
 
        :param check_content: If True, the lines supplied are verified to be
858
 
            bytestrings that are correctly formed lines.
859
 
        :return: The text sha1, the number of bytes in the text, and an opaque
860
 
                 representation of the inserted version which can be provided
861
 
                 back to future _add_text calls in the parent_texts dictionary.
862
 
        """
863
 
        # The default implementation just thunks over to .add_lines(),
864
 
        # inefficient, but it works.
865
 
        return self.add_lines(key, parents, osutils.split_lines(text),
866
 
                              nostore_sha=nostore_sha,
867
 
                              random_id=random_id,
868
 
                              check_content=True)
869
 
 
870
 
    def add_mpdiffs(self, records):
871
 
        """Add mpdiffs to this VersionedFile.
872
 
 
873
 
        Records should be iterables of version, parents, expected_sha1,
874
 
        mpdiff. mpdiff should be a MultiParent instance.
875
 
        """
876
 
        vf_parents = {}
877
 
        mpvf = multiparent.MultiMemoryVersionedFile()
878
 
        versions = []
879
 
        for version, parent_ids, expected_sha1, mpdiff in records:
880
 
            versions.append(version)
881
 
            mpvf.add_diff(mpdiff, version, parent_ids)
882
 
        needed_parents = set()
883
 
        for version, parent_ids, expected_sha1, mpdiff in records:
884
 
            needed_parents.update(p for p in parent_ids
885
 
                                  if not mpvf.has_version(p))
886
 
        # It seems likely that adding all the present parents as fulltexts can
887
 
        # easily exhaust memory.
888
 
        chunks_to_lines = osutils.chunks_to_lines
889
 
        for record in self.get_record_stream(needed_parents, 'unordered',
890
 
            True):
891
 
            if record.storage_kind == 'absent':
892
 
                continue
893
 
            mpvf.add_version(chunks_to_lines(record.get_bytes_as('chunked')),
894
 
                record.key, [])
895
 
        for (key, parent_keys, expected_sha1, mpdiff), lines in\
896
 
            zip(records, mpvf.get_line_list(versions)):
897
 
            if len(parent_keys) == 1:
898
 
                left_matching_blocks = list(mpdiff.get_matching_blocks(0,
899
 
                    mpvf.get_diff(parent_keys[0]).num_lines()))
900
 
            else:
901
 
                left_matching_blocks = None
902
 
            version_sha1, _, version_text = self.add_lines(key,
903
 
                parent_keys, lines, vf_parents,
904
 
                left_matching_blocks=left_matching_blocks)
905
 
            if version_sha1 != expected_sha1:
906
 
                raise errors.VersionedFileInvalidChecksum(version)
907
 
            vf_parents[key] = version_text
908
 
 
909
 
    def annotate(self, key):
910
 
        """Return a list of (version-key, line) tuples for the text of key.
911
 
 
912
 
        :raise RevisionNotPresent: If the key is not present.
913
 
        """
914
 
        raise NotImplementedError(self.annotate)
915
 
 
916
 
    def check(self, progress_bar=None):
917
 
        """Check this object for integrity.
918
 
        
919
 
        :param progress_bar: A progress bar to output as the check progresses.
920
 
        :param keys: Specific keys within the VersionedFiles to check. When
921
 
            this parameter is not None, check() becomes a generator as per
922
 
            get_record_stream. The difference to get_record_stream is that
923
 
            more or deeper checks will be performed.
924
 
        :return: None, or if keys was supplied a generator as per
925
 
            get_record_stream.
926
 
        """
927
 
        raise NotImplementedError(self.check)
928
 
 
929
 
    @staticmethod
930
 
    def check_not_reserved_id(version_id):
931
 
        revision.check_not_reserved_id(version_id)
932
 
 
933
 
    def _check_lines_not_unicode(self, lines):
934
 
        """Check that lines being added to a versioned file are not unicode."""
935
 
        for line in lines:
936
 
            if line.__class__ is not str:
937
 
                raise errors.BzrBadParameterUnicode("lines")
938
 
 
939
 
    def _check_lines_are_lines(self, lines):
940
 
        """Check that the lines really are full lines without inline EOL."""
941
 
        for line in lines:
942
 
            if '\n' in line[:-1]:
943
 
                raise errors.BzrBadParameterContainsNewline("lines")
944
 
 
945
 
    def get_known_graph_ancestry(self, keys):
946
 
        """Get a KnownGraph instance with the ancestry of keys."""
947
 
        # most basic implementation is a loop around get_parent_map
948
 
        pending = set(keys)
949
 
        parent_map = {}
950
 
        while pending:
951
 
            this_parent_map = self.get_parent_map(pending)
952
 
            parent_map.update(this_parent_map)
953
 
            pending = set()
954
 
            map(pending.update, this_parent_map.itervalues())
955
 
            pending = pending.difference(parent_map)
956
 
        kg = _mod_graph.KnownGraph(parent_map)
957
 
        return kg
958
 
 
959
 
    def get_parent_map(self, keys):
960
 
        """Get a map of the parents of keys.
961
 
 
962
 
        :param keys: The keys to look up parents for.
963
 
        :return: A mapping from keys to parents. Absent keys are absent from
964
 
            the mapping.
965
 
        """
966
 
        raise NotImplementedError(self.get_parent_map)
967
 
 
968
 
    def get_record_stream(self, keys, ordering, include_delta_closure):
969
 
        """Get a stream of records for keys.
970
 
 
971
 
        :param keys: The keys to include.
972
 
        :param ordering: Either 'unordered' or 'topological'. A topologically
973
 
            sorted stream has compression parents strictly before their
974
 
            children.
975
 
        :param include_delta_closure: If True then the closure across any
976
 
            compression parents will be included (in the opaque data).
977
 
        :return: An iterator of ContentFactory objects, each of which is only
978
 
            valid until the iterator is advanced.
979
 
        """
980
 
        raise NotImplementedError(self.get_record_stream)
981
 
 
982
 
    def get_sha1s(self, keys):
983
 
        """Get the sha1's of the texts for the given keys.
984
 
 
985
 
        :param keys: The names of the keys to lookup
986
 
        :return: a dict from key to sha1 digest. Keys of texts which are not
987
 
            present in the store are not present in the returned
988
 
            dictionary.
989
 
        """
990
 
        raise NotImplementedError(self.get_sha1s)
991
 
 
992
 
    has_key = index._has_key_from_parent_map
993
 
 
994
 
    def get_missing_compression_parent_keys(self):
995
 
        """Return an iterable of keys of missing compression parents.
996
 
 
997
 
        Check this after calling insert_record_stream to find out if there are
998
 
        any missing compression parents.  If there are, the records that
999
 
        depend on them are not able to be inserted safely. The precise
1000
 
        behaviour depends on the concrete VersionedFiles class in use.
1001
 
 
1002
 
        Classes that do not support this will raise NotImplementedError.
1003
 
        """
1004
 
        raise NotImplementedError(self.get_missing_compression_parent_keys)
1005
 
 
1006
 
    def insert_record_stream(self, stream):
1007
 
        """Insert a record stream into this container.
1008
 
 
1009
 
        :param stream: A stream of records to insert.
1010
 
        :return: None
1011
 
        :seealso VersionedFile.get_record_stream:
1012
 
        """
1013
 
        raise NotImplementedError
1014
 
 
1015
 
    def iter_lines_added_or_present_in_keys(self, keys, pb=None):
1016
 
        """Iterate over the lines in the versioned files from keys.
1017
 
 
1018
 
        This may return lines from other keys. Each item the returned
1019
 
        iterator yields is a tuple of a line and a text version that that line
1020
 
        is present in (not introduced in).
1021
 
 
1022
 
        Ordering of results is in whatever order is most suitable for the
1023
 
        underlying storage format.
1024
 
 
1025
 
        If a progress bar is supplied, it may be used to indicate progress.
1026
 
        The caller is responsible for cleaning up progress bars (because this
1027
 
        is an iterator).
1028
 
 
1029
 
        NOTES:
1030
 
         * Lines are normalised by the underlying store: they will all have \n
1031
 
           terminators.
1032
 
         * Lines are returned in arbitrary order.
1033
 
 
1034
 
        :return: An iterator over (line, key).
1035
 
        """
1036
 
        raise NotImplementedError(self.iter_lines_added_or_present_in_keys)
1037
 
 
1038
 
    def keys(self):
1039
 
        """Return a iterable of the keys for all the contained texts."""
1040
 
        raise NotImplementedError(self.keys)
1041
 
 
1042
 
    def make_mpdiffs(self, keys):
1043
 
        """Create multiparent diffs for specified keys."""
1044
 
        keys_order = tuple(keys)
1045
 
        keys = frozenset(keys)
1046
 
        knit_keys = set(keys)
1047
 
        parent_map = self.get_parent_map(keys)
1048
 
        for parent_keys in parent_map.itervalues():
1049
 
            if parent_keys:
1050
 
                knit_keys.update(parent_keys)
1051
 
        missing_keys = keys - set(parent_map)
1052
 
        if missing_keys:
1053
 
            raise errors.RevisionNotPresent(list(missing_keys)[0], self)
1054
 
        # We need to filter out ghosts, because we can't diff against them.
1055
 
        maybe_ghosts = knit_keys - keys
1056
 
        ghosts = maybe_ghosts - set(self.get_parent_map(maybe_ghosts))
1057
 
        knit_keys.difference_update(ghosts)
1058
 
        lines = {}
1059
 
        chunks_to_lines = osutils.chunks_to_lines
1060
 
        for record in self.get_record_stream(knit_keys, 'topological', True):
1061
 
            lines[record.key] = chunks_to_lines(record.get_bytes_as('chunked'))
1062
 
            # line_block_dict = {}
1063
 
            # for parent, blocks in record.extract_line_blocks():
1064
 
            #   line_blocks[parent] = blocks
1065
 
            # line_blocks[record.key] = line_block_dict
1066
 
        diffs = []
1067
 
        for key in keys_order:
1068
 
            target = lines[key]
1069
 
            parents = parent_map[key] or []
1070
 
            # Note that filtering knit_keys can lead to a parent difference
1071
 
            # between the creation and the application of the mpdiff.
1072
 
            parent_lines = [lines[p] for p in parents if p in knit_keys]
1073
 
            if len(parent_lines) > 0:
1074
 
                left_parent_blocks = self._extract_blocks(key, parent_lines[0],
1075
 
                    target)
1076
 
            else:
1077
 
                left_parent_blocks = None
1078
 
            diffs.append(multiparent.MultiParent.from_lines(target,
1079
 
                parent_lines, left_parent_blocks))
1080
 
        return diffs
1081
 
 
1082
 
    missing_keys = index._missing_keys_from_parent_map
1083
 
 
1084
 
    def _extract_blocks(self, version_id, source, target):
1085
 
        return None
1086
 
 
1087
 
 
1088
 
class ThunkedVersionedFiles(VersionedFiles):
1089
 
    """Storage for many versioned files thunked onto a 'VersionedFile' class.
1090
 
 
1091
 
    This object allows a single keyspace for accessing the history graph and
1092
 
    contents of named bytestrings.
1093
 
 
1094
 
    Currently no implementation allows the graph of different key prefixes to
1095
 
    intersect, but the API does allow such implementations in the future.
1096
 
    """
1097
 
 
1098
 
    def __init__(self, transport, file_factory, mapper, is_locked):
1099
 
        """Create a ThunkedVersionedFiles."""
1100
 
        self._transport = transport
1101
 
        self._file_factory = file_factory
1102
 
        self._mapper = mapper
1103
 
        self._is_locked = is_locked
1104
 
 
1105
 
    def add_lines(self, key, parents, lines, parent_texts=None,
1106
 
        left_matching_blocks=None, nostore_sha=None, random_id=False,
1107
 
        check_content=True):
1108
 
        """See VersionedFiles.add_lines()."""
1109
 
        path = self._mapper.map(key)
1110
 
        version_id = key[-1]
1111
 
        parents = [parent[-1] for parent in parents]
1112
 
        vf = self._get_vf(path)
1113
 
        try:
1114
 
            try:
1115
 
                return vf.add_lines_with_ghosts(version_id, parents, lines,
1116
 
                    parent_texts=parent_texts,
1117
 
                    left_matching_blocks=left_matching_blocks,
1118
 
                    nostore_sha=nostore_sha, random_id=random_id,
1119
 
                    check_content=check_content)
1120
 
            except NotImplementedError:
1121
 
                return vf.add_lines(version_id, parents, lines,
1122
 
                    parent_texts=parent_texts,
1123
 
                    left_matching_blocks=left_matching_blocks,
1124
 
                    nostore_sha=nostore_sha, random_id=random_id,
1125
 
                    check_content=check_content)
1126
 
        except errors.NoSuchFile:
1127
 
            # parent directory may be missing, try again.
1128
 
            self._transport.mkdir(osutils.dirname(path))
1129
 
            try:
1130
 
                return vf.add_lines_with_ghosts(version_id, parents, lines,
1131
 
                    parent_texts=parent_texts,
1132
 
                    left_matching_blocks=left_matching_blocks,
1133
 
                    nostore_sha=nostore_sha, random_id=random_id,
1134
 
                    check_content=check_content)
1135
 
            except NotImplementedError:
1136
 
                return vf.add_lines(version_id, parents, lines,
1137
 
                    parent_texts=parent_texts,
1138
 
                    left_matching_blocks=left_matching_blocks,
1139
 
                    nostore_sha=nostore_sha, random_id=random_id,
1140
 
                    check_content=check_content)
1141
 
 
1142
 
    def annotate(self, key):
1143
 
        """Return a list of (version-key, line) tuples for the text of key.
1144
 
 
1145
 
        :raise RevisionNotPresent: If the key is not present.
1146
 
        """
1147
 
        prefix = key[:-1]
1148
 
        path = self._mapper.map(prefix)
1149
 
        vf = self._get_vf(path)
1150
 
        origins = vf.annotate(key[-1])
1151
 
        result = []
1152
 
        for origin, line in origins:
1153
 
            result.append((prefix + (origin,), line))
1154
 
        return result
1155
 
 
1156
 
    def get_annotator(self):
1157
 
        return annotate.Annotator(self)
1158
 
 
1159
 
    def check(self, progress_bar=None, keys=None):
1160
 
        """See VersionedFiles.check()."""
1161
 
        # XXX: This is over-enthusiastic but as we only thunk for Weaves today
1162
 
        # this is tolerable. Ideally we'd pass keys down to check() and 
1163
 
        # have the older VersiondFile interface updated too.
1164
 
        for prefix, vf in self._iter_all_components():
1165
 
            vf.check()
1166
 
        if keys is not None:
1167
 
            return self.get_record_stream(keys, 'unordered', True)
1168
 
 
1169
 
    def get_parent_map(self, keys):
1170
 
        """Get a map of the parents of keys.
1171
 
 
1172
 
        :param keys: The keys to look up parents for.
1173
 
        :return: A mapping from keys to parents. Absent keys are absent from
1174
 
            the mapping.
1175
 
        """
1176
 
        prefixes = self._partition_keys(keys)
1177
 
        result = {}
1178
 
        for prefix, suffixes in prefixes.items():
1179
 
            path = self._mapper.map(prefix)
1180
 
            vf = self._get_vf(path)
1181
 
            parent_map = vf.get_parent_map(suffixes)
1182
 
            for key, parents in parent_map.items():
1183
 
                result[prefix + (key,)] = tuple(
1184
 
                    prefix + (parent,) for parent in parents)
1185
 
        return result
1186
 
 
1187
 
    def _get_vf(self, path):
1188
 
        if not self._is_locked():
1189
 
            raise errors.ObjectNotLocked(self)
1190
 
        return self._file_factory(path, self._transport, create=True,
1191
 
            get_scope=lambda:None)
1192
 
 
1193
 
    def _partition_keys(self, keys):
1194
 
        """Turn keys into a dict of prefix:suffix_list."""
1195
 
        result = {}
1196
 
        for key in keys:
1197
 
            prefix_keys = result.setdefault(key[:-1], [])
1198
 
            prefix_keys.append(key[-1])
1199
 
        return result
1200
 
 
1201
 
    def _get_all_prefixes(self):
1202
 
        # Identify all key prefixes.
1203
 
        # XXX: A bit hacky, needs polish.
1204
 
        if type(self._mapper) == ConstantMapper:
1205
 
            paths = [self._mapper.map(())]
1206
 
            prefixes = [()]
1207
 
        else:
1208
 
            relpaths = set()
1209
 
            for quoted_relpath in self._transport.iter_files_recursive():
1210
 
                path, ext = os.path.splitext(quoted_relpath)
1211
 
                relpaths.add(path)
1212
 
            paths = list(relpaths)
1213
 
            prefixes = [self._mapper.unmap(path) for path in paths]
1214
 
        return zip(paths, prefixes)
1215
 
 
1216
 
    def get_record_stream(self, keys, ordering, include_delta_closure):
1217
 
        """See VersionedFiles.get_record_stream()."""
1218
 
        # Ordering will be taken care of by each partitioned store; group keys
1219
 
        # by partition.
1220
 
        keys = sorted(keys)
1221
 
        for prefix, suffixes, vf in self._iter_keys_vf(keys):
1222
 
            suffixes = [(suffix,) for suffix in suffixes]
1223
 
            for record in vf.get_record_stream(suffixes, ordering,
1224
 
                include_delta_closure):
1225
 
                if record.parents is not None:
1226
 
                    record.parents = tuple(
1227
 
                        prefix + parent for parent in record.parents)
1228
 
                record.key = prefix + record.key
1229
 
                yield record
1230
 
 
1231
 
    def _iter_keys_vf(self, keys):
1232
 
        prefixes = self._partition_keys(keys)
1233
 
        sha1s = {}
1234
 
        for prefix, suffixes in prefixes.items():
1235
 
            path = self._mapper.map(prefix)
1236
 
            vf = self._get_vf(path)
1237
 
            yield prefix, suffixes, vf
1238
 
 
1239
 
    def get_sha1s(self, keys):
1240
 
        """See VersionedFiles.get_sha1s()."""
1241
 
        sha1s = {}
1242
 
        for prefix,suffixes, vf in self._iter_keys_vf(keys):
1243
 
            vf_sha1s = vf.get_sha1s(suffixes)
1244
 
            for suffix, sha1 in vf_sha1s.iteritems():
1245
 
                sha1s[prefix + (suffix,)] = sha1
1246
 
        return sha1s
1247
 
 
1248
 
    def insert_record_stream(self, stream):
1249
 
        """Insert a record stream into this container.
1250
 
 
1251
 
        :param stream: A stream of records to insert.
1252
 
        :return: None
1253
 
        :seealso VersionedFile.get_record_stream:
1254
 
        """
1255
 
        for record in stream:
1256
 
            prefix = record.key[:-1]
1257
 
            key = record.key[-1:]
1258
 
            if record.parents is not None:
1259
 
                parents = [parent[-1:] for parent in record.parents]
1260
 
            else:
1261
 
                parents = None
1262
 
            thunk_record = AdapterFactory(key, parents, record)
1263
 
            path = self._mapper.map(prefix)
1264
 
            # Note that this parses the file many times; we can do better but
1265
 
            # as this only impacts weaves in terms of performance, it is
1266
 
            # tolerable.
1267
 
            vf = self._get_vf(path)
1268
 
            vf.insert_record_stream([thunk_record])
1269
 
 
1270
 
    def iter_lines_added_or_present_in_keys(self, keys, pb=None):
1271
 
        """Iterate over the lines in the versioned files from keys.
1272
 
 
1273
 
        This may return lines from other keys. Each item the returned
1274
 
        iterator yields is a tuple of a line and a text version that that line
1275
 
        is present in (not introduced in).
1276
 
 
1277
 
        Ordering of results is in whatever order is most suitable for the
1278
 
        underlying storage format.
1279
 
 
1280
 
        If a progress bar is supplied, it may be used to indicate progress.
1281
 
        The caller is responsible for cleaning up progress bars (because this
1282
 
        is an iterator).
1283
 
 
1284
 
        NOTES:
1285
 
         * Lines are normalised by the underlying store: they will all have \n
1286
 
           terminators.
1287
 
         * Lines are returned in arbitrary order.
1288
 
 
1289
 
        :return: An iterator over (line, key).
1290
 
        """
1291
 
        for prefix, suffixes, vf in self._iter_keys_vf(keys):
1292
 
            for line, version in vf.iter_lines_added_or_present_in_versions(suffixes):
1293
 
                yield line, prefix + (version,)
1294
 
 
1295
 
    def _iter_all_components(self):
1296
 
        for path, prefix in self._get_all_prefixes():
1297
 
            yield prefix, self._get_vf(path)
1298
 
 
1299
 
    def keys(self):
1300
 
        """See VersionedFiles.keys()."""
1301
 
        result = set()
1302
 
        for prefix, vf in self._iter_all_components():
1303
 
            for suffix in vf.versions():
1304
 
                result.add(prefix + (suffix,))
1305
 
        return result
1306
 
 
1307
 
 
1308
 
class _PlanMergeVersionedFile(VersionedFiles):
1309
 
    """A VersionedFile for uncommitted and committed texts.
1310
 
 
1311
 
    It is intended to allow merges to be planned with working tree texts.
1312
 
    It implements only the small part of the VersionedFiles interface used by
1313
 
    PlanMerge.  It falls back to multiple versionedfiles for data not stored in
1314
 
    _PlanMergeVersionedFile itself.
1315
 
 
1316
 
    :ivar: fallback_versionedfiles a list of VersionedFiles objects that can be
1317
 
        queried for missing texts.
1318
 
    """
1319
 
 
1320
 
    def __init__(self, file_id):
1321
 
        """Create a _PlanMergeVersionedFile.
1322
 
 
1323
 
        :param file_id: Used with _PlanMerge code which is not yet fully
1324
 
            tuple-keyspace aware.
1325
 
        """
1326
 
        self._file_id = file_id
1327
 
        # fallback locations
1328
 
        self.fallback_versionedfiles = []
1329
 
        # Parents for locally held keys.
1330
 
        self._parents = {}
1331
 
        # line data for locally held keys.
1332
 
        self._lines = {}
1333
 
        # key lookup providers
1334
 
        self._providers = [DictParentsProvider(self._parents)]
1335
 
 
1336
 
    def plan_merge(self, ver_a, ver_b, base=None):
1337
 
        """See VersionedFile.plan_merge"""
1338
 
        from bzrlib.merge import _PlanMerge
1339
 
        if base is None:
1340
 
            return _PlanMerge(ver_a, ver_b, self, (self._file_id,)).plan_merge()
1341
 
        old_plan = list(_PlanMerge(ver_a, base, self, (self._file_id,)).plan_merge())
1342
 
        new_plan = list(_PlanMerge(ver_a, ver_b, self, (self._file_id,)).plan_merge())
1343
 
        return _PlanMerge._subtract_plans(old_plan, new_plan)
1344
 
 
1345
 
    def plan_lca_merge(self, ver_a, ver_b, base=None):
1346
 
        from bzrlib.merge import _PlanLCAMerge
1347
 
        graph = Graph(self)
1348
 
        new_plan = _PlanLCAMerge(ver_a, ver_b, self, (self._file_id,), graph).plan_merge()
1349
 
        if base is None:
1350
 
            return new_plan
1351
 
        old_plan = _PlanLCAMerge(ver_a, base, self, (self._file_id,), graph).plan_merge()
1352
 
        return _PlanLCAMerge._subtract_plans(list(old_plan), list(new_plan))
1353
 
 
1354
 
    def add_lines(self, key, parents, lines):
1355
 
        """See VersionedFiles.add_lines
1356
 
 
1357
 
        Lines are added locally, not to fallback versionedfiles.  Also, ghosts
1358
 
        are permitted.  Only reserved ids are permitted.
1359
 
        """
1360
 
        if type(key) is not tuple:
1361
 
            raise TypeError(key)
1362
 
        if not revision.is_reserved_id(key[-1]):
1363
 
            raise ValueError('Only reserved ids may be used')
1364
 
        if parents is None:
1365
 
            raise ValueError('Parents may not be None')
1366
 
        if lines is None:
1367
 
            raise ValueError('Lines may not be None')
1368
 
        self._parents[key] = tuple(parents)
1369
 
        self._lines[key] = lines
1370
 
 
1371
 
    def get_record_stream(self, keys, ordering, include_delta_closure):
1372
 
        pending = set(keys)
1373
 
        for key in keys:
1374
 
            if key in self._lines:
1375
 
                lines = self._lines[key]
1376
 
                parents = self._parents[key]
1377
 
                pending.remove(key)
1378
 
                yield ChunkedContentFactory(key, parents, None, lines)
1379
 
        for versionedfile in self.fallback_versionedfiles:
1380
 
            for record in versionedfile.get_record_stream(
1381
 
                pending, 'unordered', True):
1382
 
                if record.storage_kind == 'absent':
1383
 
                    continue
1384
 
                else:
1385
 
                    pending.remove(record.key)
1386
 
                    yield record
1387
 
            if not pending:
1388
 
                return
1389
 
        # report absent entries
1390
 
        for key in pending:
1391
 
            yield AbsentContentFactory(key)
1392
 
 
1393
 
    def get_parent_map(self, keys):
1394
 
        """See VersionedFiles.get_parent_map"""
1395
 
        # We create a new provider because a fallback may have been added.
1396
 
        # If we make fallbacks private we can update a stack list and avoid
1397
 
        # object creation thrashing.
1398
 
        keys = set(keys)
1399
 
        result = {}
1400
 
        if revision.NULL_REVISION in keys:
1401
 
            keys.remove(revision.NULL_REVISION)
1402
 
            result[revision.NULL_REVISION] = ()
1403
 
        self._providers = self._providers[:1] + self.fallback_versionedfiles
1404
 
        result.update(
1405
 
            StackedParentsProvider(self._providers).get_parent_map(keys))
1406
 
        for key, parents in result.iteritems():
1407
 
            if parents == ():
1408
 
                result[key] = (revision.NULL_REVISION,)
1409
 
        return result
1410
 
 
1411
 
 
1412
465
class PlanWeaveMerge(TextMerge):
1413
466
    """Weave merge that takes a plan as its input.
1414
 
 
 
467
    
1415
468
    This exists so that VersionedFile.plan_merge is implementable.
1416
469
    Most callers will want to use WeaveMerge instead.
1417
470
    """
1438
491
                yield(lines_a,)
1439
492
            else:
1440
493
                yield (lines_a, lines_b)
1441
 
 
 
494
       
1442
495
        # We previously considered either 'unchanged' or 'killed-both' lines
1443
496
        # to be possible places to resynchronize.  However, assuming agreement
1444
497
        # on killed-both lines may be too aggressive. -- mbp 20060324
1450
503
                lines_a = []
1451
504
                lines_b = []
1452
505
                ch_a = ch_b = False
1453
 
 
 
506
                
1454
507
            if state == 'unchanged':
1455
508
                if line:
1456
509
                    yield ([line],)
1466
519
            elif state == 'new-b':
1467
520
                ch_b = True
1468
521
                lines_b.append(line)
1469
 
            elif state == 'conflicted-a':
1470
 
                ch_b = ch_a = True
1471
 
                lines_a.append(line)
1472
 
            elif state == 'conflicted-b':
1473
 
                ch_b = ch_a = True
1474
 
                lines_b.append(line)
1475
 
            elif state == 'killed-both':
1476
 
                # This counts as a change, even though there is no associated
1477
 
                # line
1478
 
                ch_b = ch_a = True
1479
522
            else:
1480
 
                if state not in ('irrelevant', 'ghost-a', 'ghost-b',
1481
 
                        'killed-base'):
1482
 
                    raise AssertionError(state)
 
523
                assert state in ('irrelevant', 'ghost-a', 'ghost-b', 
 
524
                                 'killed-base', 'killed-both'), state
1483
525
        for struct in outstanding_struct():
1484
526
            yield struct
1485
527
 
1486
528
 
1487
529
class WeaveMerge(PlanWeaveMerge):
1488
 
    """Weave merge that takes a VersionedFile and two versions as its input."""
 
530
    """Weave merge that takes a VersionedFile and two versions as its input"""
1489
531
 
1490
 
    def __init__(self, versionedfile, ver_a, ver_b,
 
532
    def __init__(self, versionedfile, ver_a, ver_b, 
1491
533
        a_marker=PlanWeaveMerge.A_MARKER, b_marker=PlanWeaveMerge.B_MARKER):
1492
534
        plan = versionedfile.plan_merge(ver_a, ver_b)
1493
535
        PlanWeaveMerge.__init__(self, plan, a_marker, b_marker)
1494
536
 
1495
537
 
1496
 
class VirtualVersionedFiles(VersionedFiles):
1497
 
    """Dummy implementation for VersionedFiles that uses other functions for
1498
 
    obtaining fulltexts and parent maps.
1499
 
 
1500
 
    This is always on the bottom of the stack and uses string keys
1501
 
    (rather than tuples) internally.
 
538
class InterVersionedFile(InterObject):
 
539
    """This class represents operations taking place between two versionedfiles..
 
540
 
 
541
    Its instances have methods like join, and contain
 
542
    references to the source and target versionedfiles these operations can be 
 
543
    carried out on.
 
544
 
 
545
    Often we will provide convenience methods on 'versionedfile' which carry out
 
546
    operations with another versionedfile - they will always forward to
 
547
    InterVersionedFile.get(other).method_name(parameters).
1502
548
    """
1503
549
 
1504
 
    def __init__(self, get_parent_map, get_lines):
1505
 
        """Create a VirtualVersionedFiles.
1506
 
 
1507
 
        :param get_parent_map: Same signature as Repository.get_parent_map.
1508
 
        :param get_lines: Should return lines for specified key or None if
1509
 
                          not available.
1510
 
        """
1511
 
        super(VirtualVersionedFiles, self).__init__()
1512
 
        self._get_parent_map = get_parent_map
1513
 
        self._get_lines = get_lines
1514
 
 
1515
 
    def check(self, progressbar=None):
1516
 
        """See VersionedFiles.check.
1517
 
 
1518
 
        :note: Always returns True for VirtualVersionedFiles.
1519
 
        """
1520
 
        return True
1521
 
 
1522
 
    def add_mpdiffs(self, records):
1523
 
        """See VersionedFiles.mpdiffs.
1524
 
 
1525
 
        :note: Not implemented for VirtualVersionedFiles.
1526
 
        """
1527
 
        raise NotImplementedError(self.add_mpdiffs)
1528
 
 
1529
 
    def get_parent_map(self, keys):
1530
 
        """See VersionedFiles.get_parent_map."""
1531
 
        return dict([((k,), tuple([(p,) for p in v]))
1532
 
            for k,v in self._get_parent_map([k for (k,) in keys]).iteritems()])
1533
 
 
1534
 
    def get_sha1s(self, keys):
1535
 
        """See VersionedFiles.get_sha1s."""
1536
 
        ret = {}
1537
 
        for (k,) in keys:
1538
 
            lines = self._get_lines(k)
1539
 
            if lines is not None:
1540
 
                if not isinstance(lines, list):
1541
 
                    raise AssertionError
1542
 
                ret[(k,)] = osutils.sha_strings(lines)
1543
 
        return ret
1544
 
 
1545
 
    def get_record_stream(self, keys, ordering, include_delta_closure):
1546
 
        """See VersionedFiles.get_record_stream."""
1547
 
        for (k,) in list(keys):
1548
 
            lines = self._get_lines(k)
1549
 
            if lines is not None:
1550
 
                if not isinstance(lines, list):
1551
 
                    raise AssertionError
1552
 
                yield ChunkedContentFactory((k,), None,
1553
 
                        sha1=osutils.sha_strings(lines),
1554
 
                        chunks=lines)
 
550
    _optimisers = set()
 
551
    """The available optimised InterVersionedFile types."""
 
552
 
 
553
    def join(self, pb=None, msg=None, version_ids=None, ignore_missing=False):
 
554
        """Integrate versions from self.source into self.target.
 
555
 
 
556
        If version_ids is None all versions from source should be
 
557
        incorporated into this versioned file.
 
558
 
 
559
        Must raise RevisionNotPresent if any of the specified versions
 
560
        are not present in the other files history unless ignore_missing is 
 
561
        supplied when they are silently skipped.
 
562
        """
 
563
        # the default join: 
 
564
        # - if the target is empty, just add all the versions from 
 
565
        #   source to target, otherwise:
 
566
        # - make a temporary versioned file of type target
 
567
        # - insert the source content into it one at a time
 
568
        # - join them
 
569
        if not self.target.versions():
 
570
            target = self.target
 
571
        else:
 
572
            # Make a new target-format versioned file. 
 
573
            temp_source = self.target.create_empty("temp", MemoryTransport())
 
574
            target = temp_source
 
575
        version_ids = self._get_source_version_ids(version_ids, ignore_missing)
 
576
        graph = self.source.get_graph(version_ids)
 
577
        order = topo_sort(graph.items())
 
578
        pb = ui.ui_factory.nested_progress_bar()
 
579
        parent_texts = {}
 
580
        try:
 
581
            # TODO for incremental cross-format work:
 
582
            # make a versioned file with the following content:
 
583
            # all revisions we have been asked to join
 
584
            # all their ancestors that are *not* in target already.
 
585
            # the immediate parents of the above two sets, with 
 
586
            # empty parent lists - these versions are in target already
 
587
            # and the incorrect version data will be ignored.
 
588
            # TODO: for all ancestors that are present in target already,
 
589
            # check them for consistent data, this requires moving sha1 from
 
590
            # 
 
591
            # TODO: remove parent texts when they are not relevant any more for 
 
592
            # memory pressure reduction. RBC 20060313
 
593
            # pb.update('Converting versioned data', 0, len(order))
 
594
            # deltas = self.source.get_deltas(order)
 
595
            for index, version in enumerate(order):
 
596
                pb.update('Converting versioned data', index, len(order))
 
597
                parent_text = target.add_lines(version,
 
598
                                               self.source.get_parents(version),
 
599
                                               self.source.get_lines(version),
 
600
                                               parent_texts=parent_texts)
 
601
                parent_texts[version] = parent_text
 
602
                #delta_parent, sha1, noeol, delta = deltas[version]
 
603
                #target.add_delta(version,
 
604
                #                 self.source.get_parents(version),
 
605
                #                 delta_parent,
 
606
                #                 sha1,
 
607
                #                 noeol,
 
608
                #                 delta)
 
609
                #target.get_lines(version)
 
610
            
 
611
            # this should hit the native code path for target
 
612
            if target is not self.target:
 
613
                return self.target.join(temp_source,
 
614
                                        pb,
 
615
                                        msg,
 
616
                                        version_ids,
 
617
                                        ignore_missing)
 
618
        finally:
 
619
            pb.finished()
 
620
 
 
621
    def _get_source_version_ids(self, version_ids, ignore_missing):
 
622
        """Determine the version ids to be used from self.source.
 
623
 
 
624
        :param version_ids: The caller-supplied version ids to check. (None 
 
625
                            for all). If None is in version_ids, it is stripped.
 
626
        :param ignore_missing: if True, remove missing ids from the version 
 
627
                               list. If False, raise RevisionNotPresent on
 
628
                               a missing version id.
 
629
        :return: A set of version ids.
 
630
        """
 
631
        if version_ids is None:
 
632
            # None cannot be in source.versions
 
633
            return set(self.source.versions())
 
634
        else:
 
635
            if ignore_missing:
 
636
                return set(self.source.versions()).intersection(set(version_ids))
1555
637
            else:
1556
 
                yield AbsentContentFactory((k,))
1557
 
 
1558
 
    def iter_lines_added_or_present_in_keys(self, keys, pb=None):
1559
 
        """See VersionedFile.iter_lines_added_or_present_in_versions()."""
1560
 
        for i, (key,) in enumerate(keys):
1561
 
            if pb is not None:
1562
 
                pb.update("Finding changed lines", i, len(keys))
1563
 
            for l in self._get_lines(key):
1564
 
                yield (l, key)
1565
 
 
1566
 
 
1567
 
def network_bytes_to_kind_and_offset(network_bytes):
1568
 
    """Strip of a record kind from the front of network_bytes.
1569
 
 
1570
 
    :param network_bytes: The bytes of a record.
1571
 
    :return: A tuple (storage_kind, offset_of_remaining_bytes)
1572
 
    """
1573
 
    line_end = network_bytes.find('\n')
1574
 
    storage_kind = network_bytes[:line_end]
1575
 
    return storage_kind, line_end + 1
1576
 
 
1577
 
 
1578
 
class NetworkRecordStream(object):
1579
 
    """A record_stream which reconstitures a serialised stream."""
1580
 
 
1581
 
    def __init__(self, bytes_iterator):
1582
 
        """Create a NetworkRecordStream.
1583
 
 
1584
 
        :param bytes_iterator: An iterator of bytes. Each item in this
1585
 
            iterator should have been obtained from a record_streams'
1586
 
            record.get_bytes_as(record.storage_kind) call.
1587
 
        """
1588
 
        self._bytes_iterator = bytes_iterator
1589
 
        self._kind_factory = {
1590
 
            'fulltext': fulltext_network_to_record,
1591
 
            'groupcompress-block': groupcompress.network_block_to_records,
1592
 
            'knit-ft-gz': knit.knit_network_to_record,
1593
 
            'knit-delta-gz': knit.knit_network_to_record,
1594
 
            'knit-annotated-ft-gz': knit.knit_network_to_record,
1595
 
            'knit-annotated-delta-gz': knit.knit_network_to_record,
1596
 
            'knit-delta-closure': knit.knit_delta_closure_to_records,
1597
 
            }
1598
 
 
1599
 
    def read(self):
1600
 
        """Read the stream.
1601
 
 
1602
 
        :return: An iterator as per VersionedFiles.get_record_stream().
1603
 
        """
1604
 
        for bytes in self._bytes_iterator:
1605
 
            storage_kind, line_end = network_bytes_to_kind_and_offset(bytes)
1606
 
            for record in self._kind_factory[storage_kind](
1607
 
                storage_kind, bytes, line_end):
1608
 
                yield record
1609
 
 
1610
 
 
1611
 
def fulltext_network_to_record(kind, bytes, line_end):
1612
 
    """Convert a network fulltext record to record."""
1613
 
    meta_len, = struct.unpack('!L', bytes[line_end:line_end+4])
1614
 
    record_meta = bytes[line_end+4:line_end+4+meta_len]
1615
 
    key, parents = bencode.bdecode_as_tuple(record_meta)
1616
 
    if parents == 'nil':
1617
 
        parents = None
1618
 
    fulltext = bytes[line_end+4+meta_len:]
1619
 
    return [FulltextContentFactory(key, parents, None, fulltext)]
1620
 
 
1621
 
 
1622
 
def _length_prefix(bytes):
1623
 
    return struct.pack('!L', len(bytes))
1624
 
 
1625
 
 
1626
 
def record_to_fulltext_bytes(record):
1627
 
    if record.parents is None:
1628
 
        parents = 'nil'
1629
 
    else:
1630
 
        parents = record.parents
1631
 
    record_meta = bencode.bencode((record.key, parents))
1632
 
    record_content = record.get_bytes_as('fulltext')
1633
 
    return "fulltext\n%s%s%s" % (
1634
 
        _length_prefix(record_meta), record_meta, record_content)
1635
 
 
1636
 
 
1637
 
def sort_groupcompress(parent_map):
1638
 
    """Sort and group the keys in parent_map into groupcompress order.
1639
 
 
1640
 
    groupcompress is defined (currently) as reverse-topological order, grouped
1641
 
    by the key prefix.
1642
 
 
1643
 
    :return: A sorted-list of keys
1644
 
    """
1645
 
    # gc-optimal ordering is approximately reverse topological,
1646
 
    # properly grouped by file-id.
1647
 
    per_prefix_map = {}
1648
 
    for item in parent_map.iteritems():
1649
 
        key = item[0]
1650
 
        if isinstance(key, str) or len(key) == 1:
1651
 
            prefix = ''
1652
 
        else:
1653
 
            prefix = key[0]
1654
 
        try:
1655
 
            per_prefix_map[prefix].append(item)
1656
 
        except KeyError:
1657
 
            per_prefix_map[prefix] = [item]
1658
 
 
1659
 
    present_keys = []
1660
 
    for prefix in sorted(per_prefix_map):
1661
 
        present_keys.extend(reversed(tsort.topo_sort(per_prefix_map[prefix])))
1662
 
    return present_keys
 
638
                new_version_ids = set()
 
639
                for version in version_ids:
 
640
                    if version is None:
 
641
                        continue
 
642
                    if not self.source.has_version(version):
 
643
                        raise errors.RevisionNotPresent(version, str(self.source))
 
644
                    else:
 
645
                        new_version_ids.add(version)
 
646
                return new_version_ids
 
647
 
 
648
 
 
649
class InterVersionedFileTestProviderAdapter(object):
 
650
    """A tool to generate a suite testing multiple inter versioned-file classes.
 
651
 
 
652
    This is done by copying the test once for each InterVersionedFile provider
 
653
    and injecting the transport_server, transport_readonly_server,
 
654
    versionedfile_factory and versionedfile_factory_to classes into each copy.
 
655
    Each copy is also given a new id() to make it easy to identify.
 
656
    """
 
657
 
 
658
    def __init__(self, transport_server, transport_readonly_server, formats):
 
659
        self._transport_server = transport_server
 
660
        self._transport_readonly_server = transport_readonly_server
 
661
        self._formats = formats
 
662
    
 
663
    def adapt(self, test):
 
664
        result = TestSuite()
 
665
        for (interversionedfile_class,
 
666
             versionedfile_factory,
 
667
             versionedfile_factory_to) in self._formats:
 
668
            new_test = deepcopy(test)
 
669
            new_test.transport_server = self._transport_server
 
670
            new_test.transport_readonly_server = self._transport_readonly_server
 
671
            new_test.interversionedfile_class = interversionedfile_class
 
672
            new_test.versionedfile_factory = versionedfile_factory
 
673
            new_test.versionedfile_factory_to = versionedfile_factory_to
 
674
            def make_new_test_id():
 
675
                new_id = "%s(%s)" % (new_test.id(), interversionedfile_class.__name__)
 
676
                return lambda: new_id
 
677
            new_test.id = make_new_test_id()
 
678
            result.addTest(new_test)
 
679
        return result
 
680
 
 
681
    @staticmethod
 
682
    def default_test_list():
 
683
        """Generate the default list of interversionedfile permutations to test."""
 
684
        from bzrlib.weave import WeaveFile
 
685
        from bzrlib.knit import KnitVersionedFile
 
686
        result = []
 
687
        # test the fallback InterVersionedFile from annotated knits to weave
 
688
        result.append((InterVersionedFile, 
 
689
                       KnitVersionedFile,
 
690
                       WeaveFile))
 
691
        for optimiser in InterVersionedFile._optimisers:
 
692
            result.append((optimiser,
 
693
                           optimiser._matching_file_from_factory,
 
694
                           optimiser._matching_file_to_factory
 
695
                           ))
 
696
        # if there are specific combinations we want to use, we can add them 
 
697
        # here.
 
698
        return result