~bzr-pqm/bzr/bzr.dev

« back to all changes in this revision

Viewing changes to bzrlib/versionedfile.py

  • Committer: John Arbash Meinel
  • Date: 2008-03-20 15:10:05 UTC
  • mto: This revision was merged to the branch mainline in revision 3299.
  • Revision ID: john@arbash-meinel.com-20080320151005-z9lajjy69m20of17
uncommit --local in an unbound branch raises the same exception as commit --local

Show diffs side-by-side

added added

removed removed

Lines of Context:
1
 
# Copyright (C) 2006-2011 Canonical Ltd
 
1
# Copyright (C) 2005, 2006 Canonical Ltd
 
2
#
 
3
# Authors:
 
4
#   Johan Rydberg <jrydberg@gnu.org>
2
5
#
3
6
# This program is free software; you can redistribute it and/or modify
4
7
# it under the terms of the GNU General Public License as published by
12
15
#
13
16
# You should have received a copy of the GNU General Public License
14
17
# along with this program; if not, write to the Free Software
15
 
# 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
16
19
 
17
20
"""Versioned text file storage api."""
18
21
 
19
 
from __future__ import absolute_import
20
 
 
21
 
from copy import copy
22
 
from cStringIO import StringIO
23
 
import os
24
 
import struct
25
 
from zlib import adler32
26
 
 
27
22
from bzrlib.lazy_import import lazy_import
28
23
lazy_import(globals(), """
 
24
 
29
25
from bzrlib import (
30
 
    annotate,
31
 
    bencode,
32
26
    errors,
33
 
    graph as _mod_graph,
34
 
    groupcompress,
35
 
    index,
36
 
    knit,
37
27
    osutils,
38
28
    multiparent,
39
29
    tsort,
40
30
    revision,
41
 
    urlutils,
 
31
    ui,
42
32
    )
 
33
from bzrlib.transport.memory import MemoryTransport
43
34
""")
44
 
from bzrlib.registry import Registry
 
35
 
 
36
from cStringIO import StringIO
 
37
 
 
38
from bzrlib.inter import InterObject
45
39
from bzrlib.textmerge import TextMerge
46
40
 
47
41
 
48
 
adapter_registry = Registry()
49
 
adapter_registry.register_lazy(('knit-delta-gz', 'fulltext'), 'bzrlib.knit',
50
 
    'DeltaPlainToFullText')
51
 
adapter_registry.register_lazy(('knit-ft-gz', 'fulltext'), 'bzrlib.knit',
52
 
    'FTPlainToFullText')
53
 
adapter_registry.register_lazy(('knit-annotated-delta-gz', 'knit-delta-gz'),
54
 
    'bzrlib.knit', 'DeltaAnnotatedToUnannotated')
55
 
adapter_registry.register_lazy(('knit-annotated-delta-gz', 'fulltext'),
56
 
    'bzrlib.knit', 'DeltaAnnotatedToFullText')
57
 
adapter_registry.register_lazy(('knit-annotated-ft-gz', 'knit-ft-gz'),
58
 
    'bzrlib.knit', 'FTAnnotatedToUnannotated')
59
 
adapter_registry.register_lazy(('knit-annotated-ft-gz', 'fulltext'),
60
 
    'bzrlib.knit', 'FTAnnotatedToFullText')
61
 
# adapter_registry.register_lazy(('knit-annotated-ft-gz', 'chunked'),
62
 
#     'bzrlib.knit', 'FTAnnotatedToChunked')
63
 
 
64
 
 
65
 
class ContentFactory(object):
66
 
    """Abstract interface for insertion and retrieval from a VersionedFile.
67
 
 
68
 
    :ivar sha1: None, or the sha1 of the content fulltext.
69
 
    :ivar storage_kind: The native storage kind of this factory. One of
70
 
        'mpdiff', 'knit-annotated-ft', 'knit-annotated-delta', 'knit-ft',
71
 
        'knit-delta', 'fulltext', 'knit-annotated-ft-gz',
72
 
        'knit-annotated-delta-gz', 'knit-ft-gz', 'knit-delta-gz'.
73
 
    :ivar key: The key of this content. Each key is a tuple with a single
74
 
        string in it.
75
 
    :ivar parents: A tuple of parent keys for self.key. If the object has
76
 
        no parent information, None (as opposed to () for an empty list of
77
 
        parents).
78
 
    """
79
 
 
80
 
    def __init__(self):
81
 
        """Create a ContentFactory."""
82
 
        self.sha1 = None
83
 
        self.storage_kind = None
84
 
        self.key = None
85
 
        self.parents = None
86
 
 
87
 
 
88
 
class ChunkedContentFactory(ContentFactory):
89
 
    """Static data content factory.
90
 
 
91
 
    This takes a 'chunked' list of strings. The only requirement on 'chunked' is
92
 
    that ''.join(lines) becomes a valid fulltext. A tuple of a single string
93
 
    satisfies this, as does a list of lines.
94
 
 
95
 
    :ivar sha1: None, or the sha1 of the content fulltext.
96
 
    :ivar storage_kind: The native storage kind of this factory. Always
97
 
        'chunked'
98
 
    :ivar key: The key of this content. Each key is a tuple with a single
99
 
        string in it.
100
 
    :ivar parents: A tuple of parent keys for self.key. If the object has
101
 
        no parent information, None (as opposed to () for an empty list of
102
 
        parents).
103
 
     """
104
 
 
105
 
    def __init__(self, key, parents, sha1, chunks):
106
 
        """Create a ContentFactory."""
107
 
        self.sha1 = sha1
108
 
        self.storage_kind = 'chunked'
109
 
        self.key = key
110
 
        self.parents = parents
111
 
        self._chunks = chunks
112
 
 
113
 
    def get_bytes_as(self, storage_kind):
114
 
        if storage_kind == 'chunked':
115
 
            return self._chunks
116
 
        elif storage_kind == 'fulltext':
117
 
            return ''.join(self._chunks)
118
 
        raise errors.UnavailableRepresentation(self.key, storage_kind,
119
 
            self.storage_kind)
120
 
 
121
 
 
122
 
class FulltextContentFactory(ContentFactory):
123
 
    """Static data content factory.
124
 
 
125
 
    This takes a fulltext when created and just returns that during
126
 
    get_bytes_as('fulltext').
127
 
 
128
 
    :ivar sha1: None, or the sha1 of the content fulltext.
129
 
    :ivar storage_kind: The native storage kind of this factory. Always
130
 
        'fulltext'.
131
 
    :ivar key: The key of this content. Each key is a tuple with a single
132
 
        string in it.
133
 
    :ivar parents: A tuple of parent keys for self.key. If the object has
134
 
        no parent information, None (as opposed to () for an empty list of
135
 
        parents).
136
 
     """
137
 
 
138
 
    def __init__(self, key, parents, sha1, text):
139
 
        """Create a ContentFactory."""
140
 
        self.sha1 = sha1
141
 
        self.storage_kind = 'fulltext'
142
 
        self.key = key
143
 
        self.parents = parents
144
 
        self._text = text
145
 
 
146
 
    def get_bytes_as(self, storage_kind):
147
 
        if storage_kind == self.storage_kind:
148
 
            return self._text
149
 
        elif storage_kind == 'chunked':
150
 
            return [self._text]
151
 
        raise errors.UnavailableRepresentation(self.key, storage_kind,
152
 
            self.storage_kind)
153
 
 
154
 
 
155
 
class AbsentContentFactory(ContentFactory):
156
 
    """A placeholder content factory for unavailable texts.
157
 
 
158
 
    :ivar sha1: None.
159
 
    :ivar storage_kind: 'absent'.
160
 
    :ivar key: The key of this content. Each key is a tuple with a single
161
 
        string in it.
162
 
    :ivar parents: None.
163
 
    """
164
 
 
165
 
    def __init__(self, key):
166
 
        """Create a ContentFactory."""
167
 
        self.sha1 = None
168
 
        self.storage_kind = 'absent'
169
 
        self.key = key
170
 
        self.parents = None
171
 
 
172
 
    def get_bytes_as(self, storage_kind):
173
 
        raise ValueError('A request was made for key: %s, but that'
174
 
                         ' content is not available, and the calling'
175
 
                         ' code does not handle if it is missing.'
176
 
                         % (self.key,))
177
 
 
178
 
 
179
 
class AdapterFactory(ContentFactory):
180
 
    """A content factory to adapt between key prefix's."""
181
 
 
182
 
    def __init__(self, key, parents, adapted):
183
 
        """Create an adapter factory instance."""
184
 
        self.key = key
185
 
        self.parents = parents
186
 
        self._adapted = adapted
187
 
 
188
 
    def __getattr__(self, attr):
189
 
        """Return a member from the adapted object."""
190
 
        if attr in ('key', 'parents'):
191
 
            return self.__dict__[attr]
192
 
        else:
193
 
            return getattr(self._adapted, attr)
194
 
 
195
 
 
196
 
def filter_absent(record_stream):
197
 
    """Adapt a record stream to remove absent records."""
198
 
    for record in record_stream:
199
 
        if record.storage_kind != 'absent':
200
 
            yield record
201
 
 
202
 
 
203
 
class _MPDiffGenerator(object):
204
 
    """Pull out the functionality for generating mp_diffs."""
205
 
 
206
 
    def __init__(self, vf, keys):
207
 
        self.vf = vf
208
 
        # This is the order the keys were requested in
209
 
        self.ordered_keys = tuple(keys)
210
 
        # keys + their parents, what we need to compute the diffs
211
 
        self.needed_keys = ()
212
 
        # Map from key: mp_diff
213
 
        self.diffs = {}
214
 
        # Map from key: parents_needed (may have ghosts)
215
 
        self.parent_map = {}
216
 
        # Parents that aren't present
217
 
        self.ghost_parents = ()
218
 
        # Map from parent_key => number of children for this text
219
 
        self.refcounts = {}
220
 
        # Content chunks that are cached while we still need them
221
 
        self.chunks = {}
222
 
 
223
 
    def _find_needed_keys(self):
224
 
        """Find the set of keys we need to request.
225
 
 
226
 
        This includes all the original keys passed in, and the non-ghost
227
 
        parents of those keys.
228
 
 
229
 
        :return: (needed_keys, refcounts)
230
 
            needed_keys is the set of all texts we need to extract
231
 
            refcounts is a dict of {key: num_children} letting us know when we
232
 
                no longer need to cache a given parent text
233
 
        """
234
 
        # All the keys and their parents
235
 
        needed_keys = set(self.ordered_keys)
236
 
        parent_map = self.vf.get_parent_map(needed_keys)
237
 
        self.parent_map = parent_map
238
 
        # TODO: Should we be using a different construct here? I think this
239
 
        #       uses difference_update internally, and we expect the result to
240
 
        #       be tiny
241
 
        missing_keys = needed_keys.difference(parent_map)
242
 
        if missing_keys:
243
 
            raise errors.RevisionNotPresent(list(missing_keys)[0], self.vf)
244
 
        # Parents that might be missing. They are allowed to be ghosts, but we
245
 
        # should check for them
246
 
        refcounts = {}
247
 
        setdefault = refcounts.setdefault
248
 
        just_parents = set()
249
 
        for child_key, parent_keys in parent_map.iteritems():
250
 
            if not parent_keys:
251
 
                # parent_keys may be None if a given VersionedFile claims to
252
 
                # not support graph operations.
253
 
                continue
254
 
            just_parents.update(parent_keys)
255
 
            needed_keys.update(parent_keys)
256
 
            for p in parent_keys:
257
 
                refcounts[p] = setdefault(p, 0) + 1
258
 
        just_parents.difference_update(parent_map)
259
 
        # Remove any parents that are actually ghosts from the needed set
260
 
        self.present_parents = set(self.vf.get_parent_map(just_parents))
261
 
        self.ghost_parents = just_parents.difference(self.present_parents)
262
 
        needed_keys.difference_update(self.ghost_parents)
263
 
        self.needed_keys = needed_keys
264
 
        self.refcounts = refcounts
265
 
        return needed_keys, refcounts
266
 
 
267
 
    def _compute_diff(self, key, parent_lines, lines):
268
 
        """Compute a single mp_diff, and store it in self._diffs"""
269
 
        if len(parent_lines) > 0:
270
 
            # XXX: _extract_blocks is not usefully defined anywhere...
271
 
            #      It was meant to extract the left-parent diff without
272
 
            #      having to recompute it for Knit content (pack-0.92,
273
 
            #      etc). That seems to have regressed somewhere
274
 
            left_parent_blocks = self.vf._extract_blocks(key,
275
 
                parent_lines[0], lines)
276
 
        else:
277
 
            left_parent_blocks = None
278
 
        diff = multiparent.MultiParent.from_lines(lines,
279
 
                    parent_lines, left_parent_blocks)
280
 
        self.diffs[key] = diff
281
 
 
282
 
    def _process_one_record(self, key, this_chunks):
283
 
        parent_keys = None
284
 
        if key in self.parent_map:
285
 
            # This record should be ready to diff, since we requested
286
 
            # content in 'topological' order
287
 
            parent_keys = self.parent_map.pop(key)
288
 
            # If a VersionedFile claims 'no-graph' support, then it may return
289
 
            # None for any parent request, so we replace it with an empty tuple
290
 
            if parent_keys is None:
291
 
                parent_keys = ()
292
 
            parent_lines = []
293
 
            for p in parent_keys:
294
 
                # Alternatively we could check p not in self.needed_keys, but
295
 
                # ghost_parents should be tiny versus huge
296
 
                if p in self.ghost_parents:
297
 
                    continue
298
 
                refcount = self.refcounts[p]
299
 
                if refcount == 1: # Last child reference
300
 
                    self.refcounts.pop(p)
301
 
                    parent_chunks = self.chunks.pop(p)
302
 
                else:
303
 
                    self.refcounts[p] = refcount - 1
304
 
                    parent_chunks = self.chunks[p]
305
 
                p_lines = osutils.chunks_to_lines(parent_chunks)
306
 
                # TODO: Should we cache the line form? We did the
307
 
                #       computation to get it, but storing it this way will
308
 
                #       be less memory efficient...
309
 
                parent_lines.append(p_lines)
310
 
                del p_lines
311
 
            lines = osutils.chunks_to_lines(this_chunks)
312
 
            # Since we needed the lines, we'll go ahead and cache them this way
313
 
            this_chunks = lines
314
 
            self._compute_diff(key, parent_lines, lines)
315
 
            del lines
316
 
        # Is this content required for any more children?
317
 
        if key in self.refcounts:
318
 
            self.chunks[key] = this_chunks
319
 
 
320
 
    def _extract_diffs(self):
321
 
        needed_keys, refcounts = self._find_needed_keys()
322
 
        for record in self.vf.get_record_stream(needed_keys,
323
 
                                                'topological', True):
324
 
            if record.storage_kind == 'absent':
325
 
                raise errors.RevisionNotPresent(record.key, self.vf)
326
 
            self._process_one_record(record.key,
327
 
                                     record.get_bytes_as('chunked'))
328
 
        
329
 
    def compute_diffs(self):
330
 
        self._extract_diffs()
331
 
        dpop = self.diffs.pop
332
 
        return [dpop(k) for k in self.ordered_keys]
333
 
 
334
 
 
335
42
class VersionedFile(object):
336
43
    """Versioned text file storage.
337
 
 
 
44
    
338
45
    A versioned file manages versions of line-based text files,
339
46
    keeping track of the originating version for each line.
340
47
 
346
53
    Texts are identified by a version-id string.
347
54
    """
348
55
 
 
56
    def __init__(self, access_mode):
 
57
        self.finished = False
 
58
        self._access_mode = access_mode
 
59
 
349
60
    @staticmethod
350
61
    def check_not_reserved_id(version_id):
351
62
        revision.check_not_reserved_id(version_id)
354
65
        """Copy this versioned file to name on transport."""
355
66
        raise NotImplementedError(self.copy_to)
356
67
 
357
 
    def get_record_stream(self, versions, ordering, include_delta_closure):
358
 
        """Get a stream of records for versions.
 
68
    def versions(self):
 
69
        """Return a unsorted list of versions."""
 
70
        raise NotImplementedError(self.versions)
359
71
 
360
 
        :param versions: The versions to include. Each version is a tuple
361
 
            (version,).
362
 
        :param ordering: Either 'unordered' or 'topological'. A topologically
363
 
            sorted stream has compression parents strictly before their
364
 
            children.
365
 
        :param include_delta_closure: If True then the closure across any
366
 
            compression parents will be included (in the data content of the
367
 
            stream, not in the emitted records). This guarantees that
368
 
            'fulltext' can be used successfully on every record.
369
 
        :return: An iterator of ContentFactory objects, each of which is only
370
 
            valid until the iterator is advanced.
371
 
        """
372
 
        raise NotImplementedError(self.get_record_stream)
 
72
    def has_ghost(self, version_id):
 
73
        """Returns whether version is present as a ghost."""
 
74
        raise NotImplementedError(self.has_ghost)
373
75
 
374
76
    def has_version(self, version_id):
375
77
        """Returns whether version is present."""
376
78
        raise NotImplementedError(self.has_version)
377
79
 
378
 
    def insert_record_stream(self, stream):
379
 
        """Insert a record stream into this versioned file.
380
 
 
381
 
        :param stream: A stream of records to insert.
382
 
        :return: None
383
 
        :seealso VersionedFile.get_record_stream:
384
 
        """
385
 
        raise NotImplementedError
386
 
 
387
80
    def add_lines(self, version_id, parents, lines, parent_texts=None,
388
81
        left_matching_blocks=None, nostore_sha=None, random_id=False,
389
82
        check_content=True):
403
96
            the data back accurately. (Checking the lines have been split
404
97
            correctly is expensive and extremely unlikely to catch bugs so it
405
98
            is not done at runtime unless check_content is True.)
406
 
        :param parent_texts: An optional dictionary containing the opaque
 
99
        :param parent_texts: An optional dictionary containing the opaque 
407
100
            representations of some or all of the parents of version_id to
408
101
            allow delta optimisations.  VERY IMPORTANT: the texts must be those
409
102
            returned by add_lines or data corruption can be caused.
435
128
 
436
129
    def add_lines_with_ghosts(self, version_id, parents, lines,
437
130
        parent_texts=None, nostore_sha=None, random_id=False,
438
 
        check_content=True, left_matching_blocks=None):
 
131
        check_content=True):
439
132
        """Add lines to the versioned file, allowing ghosts to be present.
440
 
 
 
133
        
441
134
        This takes the same parameters as add_lines and returns the same.
442
135
        """
443
136
        self._check_write_ok()
444
137
        return self._add_lines_with_ghosts(version_id, parents, lines,
445
 
            parent_texts, nostore_sha, random_id, check_content, left_matching_blocks)
 
138
            parent_texts, nostore_sha, random_id, check_content)
446
139
 
447
140
    def _add_lines_with_ghosts(self, version_id, parents, lines, parent_texts,
448
 
        nostore_sha, random_id, check_content, left_matching_blocks):
 
141
        nostore_sha, random_id, check_content):
449
142
        """Helper to do class specific add_lines_with_ghosts."""
450
143
        raise NotImplementedError(self.add_lines_with_ghosts)
451
144
 
465
158
            if '\n' in line[:-1]:
466
159
                raise errors.BzrBadParameterContainsNewline("lines")
467
160
 
 
161
    def _check_write_ok(self):
 
162
        """Is the versioned file marked as 'finished' ? Raise if it is."""
 
163
        if self.finished:
 
164
            raise errors.OutSideTransaction()
 
165
        if self._access_mode != 'w':
 
166
            raise errors.ReadOnlyObjectDirtiedError(self)
 
167
 
 
168
    def enable_cache(self):
 
169
        """Tell this versioned file that it should cache any data it reads.
 
170
        
 
171
        This is advisory, implementations do not have to support caching.
 
172
        """
 
173
        pass
 
174
    
 
175
    def clear_cache(self):
 
176
        """Remove any data cached in the versioned file object.
 
177
 
 
178
        This only needs to be supported if caches are supported
 
179
        """
 
180
        pass
 
181
 
 
182
    def clone_text(self, new_version_id, old_version_id, parents):
 
183
        """Add an identical text to old_version_id as new_version_id.
 
184
 
 
185
        Must raise RevisionNotPresent if the old version or any of the
 
186
        parents are not present in file history.
 
187
 
 
188
        Must raise RevisionAlreadyPresent if the new version is
 
189
        already present in file history."""
 
190
        self._check_write_ok()
 
191
        return self._clone_text(new_version_id, old_version_id, parents)
 
192
 
 
193
    def _clone_text(self, new_version_id, old_version_id, parents):
 
194
        """Helper function to do the _clone_text work."""
 
195
        raise NotImplementedError(self.clone_text)
 
196
 
 
197
    def create_empty(self, name, transport, mode=None):
 
198
        """Create a new versioned file of this exact type.
 
199
 
 
200
        :param name: the file name
 
201
        :param transport: the transport
 
202
        :param mode: optional file mode.
 
203
        """
 
204
        raise NotImplementedError(self.create_empty)
 
205
 
468
206
    def get_format_signature(self):
469
207
        """Get a text description of the data encoding in this file.
470
 
 
 
208
        
471
209
        :since: 0.90
472
210
        """
473
211
        raise NotImplementedError(self.get_format_signature)
474
212
 
475
213
    def make_mpdiffs(self, version_ids):
476
214
        """Create multiparent diffs for specified versions."""
477
 
        # XXX: Can't use _MPDiffGenerator just yet. This is because version_ids
478
 
        #      is a list of strings, not keys. And while self.get_record_stream
479
 
        #      is supported, it takes *keys*, while self.get_parent_map() takes
480
 
        #      strings... *sigh*
481
215
        knit_versions = set()
482
 
        knit_versions.update(version_ids)
483
 
        parent_map = self.get_parent_map(version_ids)
484
216
        for version_id in version_ids:
485
 
            try:
486
 
                knit_versions.update(parent_map[version_id])
487
 
            except KeyError:
488
 
                raise errors.RevisionNotPresent(version_id, self)
489
 
        # We need to filter out ghosts, because we can't diff against them.
490
 
        knit_versions = set(self.get_parent_map(knit_versions).keys())
 
217
            knit_versions.add(version_id)
 
218
            knit_versions.update(self.get_parents(version_id))
491
219
        lines = dict(zip(knit_versions,
492
220
            self._get_lf_split_line_list(knit_versions)))
493
221
        diffs = []
494
222
        for version_id in version_ids:
495
223
            target = lines[version_id]
496
 
            try:
497
 
                parents = [lines[p] for p in parent_map[version_id] if p in
498
 
                    knit_versions]
499
 
            except KeyError:
500
 
                # I don't know how this could ever trigger.
501
 
                # parent_map[version_id] was already triggered in the previous
502
 
                # for loop, and lines[p] has the 'if p in knit_versions' check,
503
 
                # so we again won't have a KeyError.
504
 
                raise errors.RevisionNotPresent(version_id, self)
 
224
            parents = [lines[p] for p in self.get_parents(version_id)]
505
225
            if len(parents) > 0:
506
226
                left_parent_blocks = self._extract_blocks(version_id,
507
227
                                                          parents[0], target)
531
251
        for version, parent_ids, expected_sha1, mpdiff in records:
532
252
            needed_parents.update(p for p in parent_ids
533
253
                                  if not mpvf.has_version(p))
534
 
        present_parents = set(self.get_parent_map(needed_parents).keys())
535
 
        for parent_id, lines in zip(present_parents,
536
 
                                 self._get_lf_split_line_list(present_parents)):
 
254
        for parent_id, lines in zip(needed_parents,
 
255
                                 self._get_lf_split_line_list(needed_parents)):
537
256
            mpvf.add_version(lines, parent_id, [])
538
257
        for (version, parent_ids, expected_sha1, mpdiff), lines in\
539
258
            zip(records, mpvf.get_line_list(versions)):
542
261
                    mpvf.get_diff(parent_ids[0]).num_lines()))
543
262
            else:
544
263
                left_matching_blocks = None
545
 
            try:
546
 
                _, _, version_text = self.add_lines_with_ghosts(version,
547
 
                    parent_ids, lines, vf_parents,
548
 
                    left_matching_blocks=left_matching_blocks)
549
 
            except NotImplementedError:
550
 
                # The vf can't handle ghosts, so add lines normally, which will
551
 
                # (reasonably) fail if there are ghosts in the data.
552
 
                _, _, version_text = self.add_lines(version,
553
 
                    parent_ids, lines, vf_parents,
554
 
                    left_matching_blocks=left_matching_blocks)
 
264
            _, _, version_text = self.add_lines(version, parent_ids, lines,
 
265
                vf_parents, left_matching_blocks=left_matching_blocks)
555
266
            vf_parents[version] = version_text
556
 
        sha1s = self.get_sha1s(versions)
557
 
        for version, parent_ids, expected_sha1, mpdiff in records:
558
 
            if expected_sha1 != sha1s[version]:
 
267
        for (version, parent_ids, expected_sha1, mpdiff), sha1 in\
 
268
             zip(records, self.get_sha1s(versions)):
 
269
            if expected_sha1 != sha1:
559
270
                raise errors.VersionedFileInvalidChecksum(version)
560
271
 
 
272
    def get_sha1(self, version_id):
 
273
        """Get the stored sha1 sum for the given revision.
 
274
        
 
275
        :param version_id: The name of the version to lookup
 
276
        """
 
277
        raise NotImplementedError(self.get_sha1)
 
278
 
 
279
    def get_sha1s(self, version_ids):
 
280
        """Get the stored sha1 sums for the given revisions.
 
281
 
 
282
        :param version_ids: The names of the versions to lookup
 
283
        :return: a list of sha1s in order according to the version_ids
 
284
        """
 
285
        raise NotImplementedError(self.get_sha1s)
 
286
 
 
287
    def get_suffixes(self):
 
288
        """Return the file suffixes associated with this versioned file."""
 
289
        raise NotImplementedError(self.get_suffixes)
 
290
    
561
291
    def get_text(self, version_id):
562
292
        """Return version contents as a text string.
563
293
 
598
328
        if isinstance(version_ids, basestring):
599
329
            version_ids = [version_ids]
600
330
        raise NotImplementedError(self.get_ancestry)
601
 
 
 
331
        
602
332
    def get_ancestry_with_ghosts(self, version_ids):
603
333
        """Return a list of all ancestors of given version(s). This
604
334
        will not include the null revision.
605
335
 
606
336
        Must raise RevisionNotPresent if any of the given versions are
607
337
        not present in file history.
608
 
 
 
338
        
609
339
        Ghosts that are known about will be included in ancestry list,
610
340
        but are not explicitly marked.
611
341
        """
612
342
        raise NotImplementedError(self.get_ancestry_with_ghosts)
613
 
 
614
 
    def get_parent_map(self, version_ids):
615
 
        """Get a map of the parents of version_ids.
616
 
 
617
 
        :param version_ids: The version ids to look up parents for.
618
 
        :return: A mapping from version id to parents.
619
 
        """
620
 
        raise NotImplementedError(self.get_parent_map)
 
343
        
 
344
    def get_graph(self, version_ids=None):
 
345
        """Return a graph from the versioned file. 
 
346
        
 
347
        Ghosts are not listed or referenced in the graph.
 
348
        :param version_ids: Versions to select.
 
349
                            None means retrieve all versions.
 
350
        """
 
351
        if version_ids is None:
 
352
            return dict(self.iter_parents(self.versions()))
 
353
        result = {}
 
354
        pending = set(version_ids)
 
355
        while pending:
 
356
            this_iteration = pending
 
357
            pending = set()
 
358
            for version, parents in self.iter_parents(this_iteration):
 
359
                result[version] = parents
 
360
                for parent in parents:
 
361
                    if parent in result:
 
362
                        continue
 
363
                    pending.add(parent)
 
364
        return result
 
365
 
 
366
    def get_graph_with_ghosts(self):
 
367
        """Return a graph for the entire versioned file.
 
368
        
 
369
        Ghosts are referenced in parents list but are not
 
370
        explicitly listed.
 
371
        """
 
372
        raise NotImplementedError(self.get_graph_with_ghosts)
 
373
 
 
374
    def get_parents(self, version_id):
 
375
        """Return version names for parents of a version.
 
376
 
 
377
        Must raise RevisionNotPresent if version is not present in
 
378
        file history.
 
379
        """
 
380
        raise NotImplementedError(self.get_parents)
621
381
 
622
382
    def get_parents_with_ghosts(self, version_id):
623
383
        """Return version names for parents of version_id.
628
388
        Ghosts that are known about will be included in the parent list,
629
389
        but are not explicitly marked.
630
390
        """
631
 
        try:
632
 
            return list(self.get_parent_map([version_id])[version_id])
633
 
        except KeyError:
634
 
            raise errors.RevisionNotPresent(version_id, self)
 
391
        raise NotImplementedError(self.get_parents_with_ghosts)
 
392
 
 
393
    def annotate_iter(self, version_id):
 
394
        """Yield list of (version-id, line) pairs for the specified
 
395
        version.
 
396
 
 
397
        Must raise RevisionNotPresent if the given version is
 
398
        not present in file history.
 
399
        """
 
400
        raise NotImplementedError(self.annotate_iter)
635
401
 
636
402
    def annotate(self, version_id):
637
 
        """Return a list of (version-id, line) tuples for version_id.
638
 
 
639
 
        :raise RevisionNotPresent: If the given version is
640
 
        not present in file history.
 
403
        return list(self.annotate_iter(version_id))
 
404
 
 
405
    def join(self, other, pb=None, msg=None, version_ids=None,
 
406
             ignore_missing=False):
 
407
        """Integrate versions from other into this versioned file.
 
408
 
 
409
        If version_ids is None all versions from other should be
 
410
        incorporated into this versioned file.
 
411
 
 
412
        Must raise RevisionNotPresent if any of the specified versions
 
413
        are not present in the other file's history unless ignore_missing
 
414
        is supplied in which case they are silently skipped.
641
415
        """
642
 
        raise NotImplementedError(self.annotate)
 
416
        self._check_write_ok()
 
417
        return InterVersionedFile.get(other, self).join(
 
418
            pb,
 
419
            msg,
 
420
            version_ids,
 
421
            ignore_missing)
643
422
 
644
423
    def iter_lines_added_or_present_in_versions(self, version_ids=None,
645
424
                                                pb=None):
663
442
        """
664
443
        raise NotImplementedError(self.iter_lines_added_or_present_in_versions)
665
444
 
 
445
    def iter_parents(self, version_ids):
 
446
        """Iterate through the parents for many version ids.
 
447
 
 
448
        :param version_ids: An iterable yielding version_ids.
 
449
        :return: An iterator that yields (version_id, parents). Requested 
 
450
            version_ids not present in the versioned file are simply skipped.
 
451
            The order is undefined, allowing for different optimisations in
 
452
            the underlying implementation.
 
453
        """
 
454
        for version_id in version_ids:
 
455
            try:
 
456
                yield version_id, tuple(self.get_parents(version_id))
 
457
            except errors.RevisionNotPresent:
 
458
                pass
 
459
 
 
460
    def transaction_finished(self):
 
461
        """The transaction that this file was opened in has finished.
 
462
 
 
463
        This records self.finished = True and should cause all mutating
 
464
        operations to error.
 
465
        """
 
466
        self.finished = True
 
467
 
666
468
    def plan_merge(self, ver_a, ver_b):
667
469
        """Return pseudo-annotation indicating how the two versions merge.
668
470
 
679
481
        unchanged   Alive in both a and b (possibly created in both)
680
482
        new-a       Created in a
681
483
        new-b       Created in b
682
 
        ghost-a     Killed in a, unborn in b
 
484
        ghost-a     Killed in a, unborn in b    
683
485
        ghost-b     Killed in b, unborn in a
684
486
        irrelevant  Not in either revision
685
487
        """
686
488
        raise NotImplementedError(VersionedFile.plan_merge)
687
 
 
 
489
        
688
490
    def weave_merge(self, plan, a_marker=TextMerge.A_MARKER,
689
491
                    b_marker=TextMerge.B_MARKER):
690
492
        return PlanWeaveMerge(plan, a_marker, b_marker).merge_lines()[0]
691
493
 
692
494
 
693
 
class RecordingVersionedFilesDecorator(object):
694
 
    """A minimal versioned files that records calls made on it.
695
 
 
696
 
    Only enough methods have been added to support tests using it to date.
697
 
 
698
 
    :ivar calls: A list of the calls made; can be reset at any time by
699
 
        assigning [] to it.
700
 
    """
701
 
 
702
 
    def __init__(self, backing_vf):
703
 
        """Create a RecordingVersionedFilesDecorator decorating backing_vf.
704
 
 
705
 
        :param backing_vf: The versioned file to answer all methods.
706
 
        """
707
 
        self._backing_vf = backing_vf
708
 
        self.calls = []
709
 
 
710
 
    def add_lines(self, key, parents, lines, parent_texts=None,
711
 
        left_matching_blocks=None, nostore_sha=None, random_id=False,
712
 
        check_content=True):
713
 
        self.calls.append(("add_lines", key, parents, lines, parent_texts,
714
 
            left_matching_blocks, nostore_sha, random_id, check_content))
715
 
        return self._backing_vf.add_lines(key, parents, lines, parent_texts,
716
 
            left_matching_blocks, nostore_sha, random_id, check_content)
717
 
 
718
 
    def check(self):
719
 
        self._backing_vf.check()
720
 
 
721
 
    def get_parent_map(self, keys):
722
 
        self.calls.append(("get_parent_map", copy(keys)))
723
 
        return self._backing_vf.get_parent_map(keys)
724
 
 
725
 
    def get_record_stream(self, keys, sort_order, include_delta_closure):
726
 
        self.calls.append(("get_record_stream", list(keys), sort_order,
727
 
            include_delta_closure))
728
 
        return self._backing_vf.get_record_stream(keys, sort_order,
729
 
            include_delta_closure)
730
 
 
731
 
    def get_sha1s(self, keys):
732
 
        self.calls.append(("get_sha1s", copy(keys)))
733
 
        return self._backing_vf.get_sha1s(keys)
734
 
 
735
 
    def iter_lines_added_or_present_in_keys(self, keys, pb=None):
736
 
        self.calls.append(("iter_lines_added_or_present_in_keys", copy(keys)))
737
 
        return self._backing_vf.iter_lines_added_or_present_in_keys(keys, pb=pb)
738
 
 
739
 
    def keys(self):
740
 
        self.calls.append(("keys",))
741
 
        return self._backing_vf.keys()
742
 
 
743
 
 
744
 
class OrderingVersionedFilesDecorator(RecordingVersionedFilesDecorator):
745
 
    """A VF that records calls, and returns keys in specific order.
746
 
 
747
 
    :ivar calls: A list of the calls made; can be reset at any time by
748
 
        assigning [] to it.
749
 
    """
750
 
 
751
 
    def __init__(self, backing_vf, key_priority):
752
 
        """Create a RecordingVersionedFilesDecorator decorating backing_vf.
753
 
 
754
 
        :param backing_vf: The versioned file to answer all methods.
755
 
        :param key_priority: A dictionary defining what order keys should be
756
 
            returned from an 'unordered' get_record_stream request.
757
 
            Keys with lower priority are returned first, keys not present in
758
 
            the map get an implicit priority of 0, and are returned in
759
 
            lexicographical order.
760
 
        """
761
 
        RecordingVersionedFilesDecorator.__init__(self, backing_vf)
762
 
        self._key_priority = key_priority
763
 
 
764
 
    def get_record_stream(self, keys, sort_order, include_delta_closure):
765
 
        self.calls.append(("get_record_stream", list(keys), sort_order,
766
 
            include_delta_closure))
767
 
        if sort_order == 'unordered':
768
 
            def sort_key(key):
769
 
                return (self._key_priority.get(key, 0), key)
770
 
            # Use a defined order by asking for the keys one-by-one from the
771
 
            # backing_vf
772
 
            for key in sorted(keys, key=sort_key):
773
 
                for record in self._backing_vf.get_record_stream([key],
774
 
                                'unordered', include_delta_closure):
775
 
                    yield record
776
 
        else:
777
 
            for record in self._backing_vf.get_record_stream(keys, sort_order,
778
 
                            include_delta_closure):
779
 
                yield record
780
 
 
781
 
 
782
 
class KeyMapper(object):
783
 
    """KeyMappers map between keys and underlying partitioned storage."""
784
 
 
785
 
    def map(self, key):
786
 
        """Map key to an underlying storage identifier.
787
 
 
788
 
        :param key: A key tuple e.g. ('file-id', 'revision-id').
789
 
        :return: An underlying storage identifier, specific to the partitioning
790
 
            mechanism.
791
 
        """
792
 
        raise NotImplementedError(self.map)
793
 
 
794
 
    def unmap(self, partition_id):
795
 
        """Map a partitioned storage id back to a key prefix.
796
 
 
797
 
        :param partition_id: The underlying partition id.
798
 
        :return: As much of a key (or prefix) as is derivable from the partition
799
 
            id.
800
 
        """
801
 
        raise NotImplementedError(self.unmap)
802
 
 
803
 
 
804
 
class ConstantMapper(KeyMapper):
805
 
    """A key mapper that maps to a constant result."""
806
 
 
807
 
    def __init__(self, result):
808
 
        """Create a ConstantMapper which will return result for all maps."""
809
 
        self._result = result
810
 
 
811
 
    def map(self, key):
812
 
        """See KeyMapper.map()."""
813
 
        return self._result
814
 
 
815
 
 
816
 
class URLEscapeMapper(KeyMapper):
817
 
    """Base class for use with transport backed storage.
818
 
 
819
 
    This provides a map and unmap wrapper that respectively url escape and
820
 
    unescape their outputs and inputs.
821
 
    """
822
 
 
823
 
    def map(self, key):
824
 
        """See KeyMapper.map()."""
825
 
        return urlutils.quote(self._map(key))
826
 
 
827
 
    def unmap(self, partition_id):
828
 
        """See KeyMapper.unmap()."""
829
 
        return self._unmap(urlutils.unquote(partition_id))
830
 
 
831
 
 
832
 
class PrefixMapper(URLEscapeMapper):
833
 
    """A key mapper that extracts the first component of a key.
834
 
 
835
 
    This mapper is for use with a transport based backend.
836
 
    """
837
 
 
838
 
    def _map(self, key):
839
 
        """See KeyMapper.map()."""
840
 
        return key[0]
841
 
 
842
 
    def _unmap(self, partition_id):
843
 
        """See KeyMapper.unmap()."""
844
 
        return (partition_id,)
845
 
 
846
 
 
847
 
class HashPrefixMapper(URLEscapeMapper):
848
 
    """A key mapper that combines the first component of a key with a hash.
849
 
 
850
 
    This mapper is for use with a transport based backend.
851
 
    """
852
 
 
853
 
    def _map(self, key):
854
 
        """See KeyMapper.map()."""
855
 
        prefix = self._escape(key[0])
856
 
        return "%02x/%s" % (adler32(prefix) & 0xff, prefix)
857
 
 
858
 
    def _escape(self, prefix):
859
 
        """No escaping needed here."""
860
 
        return prefix
861
 
 
862
 
    def _unmap(self, partition_id):
863
 
        """See KeyMapper.unmap()."""
864
 
        return (self._unescape(osutils.basename(partition_id)),)
865
 
 
866
 
    def _unescape(self, basename):
867
 
        """No unescaping needed for HashPrefixMapper."""
868
 
        return basename
869
 
 
870
 
 
871
 
class HashEscapedPrefixMapper(HashPrefixMapper):
872
 
    """Combines the escaped first component of a key with a hash.
873
 
 
874
 
    This mapper is for use with a transport based backend.
875
 
    """
876
 
 
877
 
    _safe = "abcdefghijklmnopqrstuvwxyz0123456789-_@,."
878
 
 
879
 
    def _escape(self, prefix):
880
 
        """Turn a key element into a filesystem safe string.
881
 
 
882
 
        This is similar to a plain urlutils.quote, except
883
 
        it uses specific safe characters, so that it doesn't
884
 
        have to translate a lot of valid file ids.
885
 
        """
886
 
        # @ does not get escaped. This is because it is a valid
887
 
        # filesystem character we use all the time, and it looks
888
 
        # a lot better than seeing %40 all the time.
889
 
        r = [((c in self._safe) and c or ('%%%02x' % ord(c)))
890
 
             for c in prefix]
891
 
        return ''.join(r)
892
 
 
893
 
    def _unescape(self, basename):
894
 
        """Escaped names are easily unescaped by urlutils."""
895
 
        return urlutils.unquote(basename)
896
 
 
897
 
 
898
 
def make_versioned_files_factory(versioned_file_factory, mapper):
899
 
    """Create a ThunkedVersionedFiles factory.
900
 
 
901
 
    This will create a callable which when called creates a
902
 
    ThunkedVersionedFiles on a transport, using mapper to access individual
903
 
    versioned files, and versioned_file_factory to create each individual file.
904
 
    """
905
 
    def factory(transport):
906
 
        return ThunkedVersionedFiles(transport, versioned_file_factory, mapper,
907
 
            lambda:True)
908
 
    return factory
909
 
 
910
 
 
911
 
class VersionedFiles(object):
912
 
    """Storage for many versioned files.
913
 
 
914
 
    This object allows a single keyspace for accessing the history graph and
915
 
    contents of named bytestrings.
916
 
 
917
 
    Currently no implementation allows the graph of different key prefixes to
918
 
    intersect, but the API does allow such implementations in the future.
919
 
 
920
 
    The keyspace is expressed via simple tuples. Any instance of VersionedFiles
921
 
    may have a different length key-size, but that size will be constant for
922
 
    all texts added to or retrieved from it. For instance, bzrlib uses
923
 
    instances with a key-size of 2 for storing user files in a repository, with
924
 
    the first element the fileid, and the second the version of that file.
925
 
 
926
 
    The use of tuples allows a single code base to support several different
927
 
    uses with only the mapping logic changing from instance to instance.
928
 
 
929
 
    :ivar _immediate_fallback_vfs: For subclasses that support stacking,
930
 
        this is a list of other VersionedFiles immediately underneath this
931
 
        one.  They may in turn each have further fallbacks.
932
 
    """
933
 
 
934
 
    def add_lines(self, key, parents, lines, parent_texts=None,
935
 
        left_matching_blocks=None, nostore_sha=None, random_id=False,
936
 
        check_content=True):
937
 
        """Add a text to the store.
938
 
 
939
 
        :param key: The key tuple of the text to add. If the last element is
940
 
            None, a CHK string will be generated during the addition.
941
 
        :param parents: The parents key tuples of the text to add.
942
 
        :param lines: A list of lines. Each line must be a bytestring. And all
943
 
            of them except the last must be terminated with \n and contain no
944
 
            other \n's. The last line may either contain no \n's or a single
945
 
            terminating \n. If the lines list does meet this constraint the add
946
 
            routine may error or may succeed - but you will be unable to read
947
 
            the data back accurately. (Checking the lines have been split
948
 
            correctly is expensive and extremely unlikely to catch bugs so it
949
 
            is not done at runtime unless check_content is True.)
950
 
        :param parent_texts: An optional dictionary containing the opaque
951
 
            representations of some or all of the parents of version_id to
952
 
            allow delta optimisations.  VERY IMPORTANT: the texts must be those
953
 
            returned by add_lines or data corruption can be caused.
954
 
        :param left_matching_blocks: a hint about which areas are common
955
 
            between the text and its left-hand-parent.  The format is
956
 
            the SequenceMatcher.get_matching_blocks format.
957
 
        :param nostore_sha: Raise ExistingContent and do not add the lines to
958
 
            the versioned file if the digest of the lines matches this.
959
 
        :param random_id: If True a random id has been selected rather than
960
 
            an id determined by some deterministic process such as a converter
961
 
            from a foreign VCS. When True the backend may choose not to check
962
 
            for uniqueness of the resulting key within the versioned file, so
963
 
            this should only be done when the result is expected to be unique
964
 
            anyway.
965
 
        :param check_content: If True, the lines supplied are verified to be
966
 
            bytestrings that are correctly formed lines.
967
 
        :return: The text sha1, the number of bytes in the text, and an opaque
968
 
                 representation of the inserted version which can be provided
969
 
                 back to future add_lines calls in the parent_texts dictionary.
970
 
        """
971
 
        raise NotImplementedError(self.add_lines)
972
 
 
973
 
    def _add_text(self, key, parents, text, nostore_sha=None, random_id=False):
974
 
        """Add a text to the store.
975
 
 
976
 
        This is a private function for use by VersionedFileCommitBuilder.
977
 
 
978
 
        :param key: The key tuple of the text to add. If the last element is
979
 
            None, a CHK string will be generated during the addition.
980
 
        :param parents: The parents key tuples of the text to add.
981
 
        :param text: A string containing the text to be committed.
982
 
        :param nostore_sha: Raise ExistingContent and do not add the lines to
983
 
            the versioned file if the digest of the lines matches this.
984
 
        :param random_id: If True a random id has been selected rather than
985
 
            an id determined by some deterministic process such as a converter
986
 
            from a foreign VCS. When True the backend may choose not to check
987
 
            for uniqueness of the resulting key within the versioned file, so
988
 
            this should only be done when the result is expected to be unique
989
 
            anyway.
990
 
        :param check_content: If True, the lines supplied are verified to be
991
 
            bytestrings that are correctly formed lines.
992
 
        :return: The text sha1, the number of bytes in the text, and an opaque
993
 
                 representation of the inserted version which can be provided
994
 
                 back to future _add_text calls in the parent_texts dictionary.
995
 
        """
996
 
        # The default implementation just thunks over to .add_lines(),
997
 
        # inefficient, but it works.
998
 
        return self.add_lines(key, parents, osutils.split_lines(text),
999
 
                              nostore_sha=nostore_sha,
1000
 
                              random_id=random_id,
1001
 
                              check_content=True)
1002
 
 
1003
 
    def add_mpdiffs(self, records):
1004
 
        """Add mpdiffs to this VersionedFile.
1005
 
 
1006
 
        Records should be iterables of version, parents, expected_sha1,
1007
 
        mpdiff. mpdiff should be a MultiParent instance.
1008
 
        """
1009
 
        vf_parents = {}
1010
 
        mpvf = multiparent.MultiMemoryVersionedFile()
1011
 
        versions = []
1012
 
        for version, parent_ids, expected_sha1, mpdiff in records:
1013
 
            versions.append(version)
1014
 
            mpvf.add_diff(mpdiff, version, parent_ids)
1015
 
        needed_parents = set()
1016
 
        for version, parent_ids, expected_sha1, mpdiff in records:
1017
 
            needed_parents.update(p for p in parent_ids
1018
 
                                  if not mpvf.has_version(p))
1019
 
        # It seems likely that adding all the present parents as fulltexts can
1020
 
        # easily exhaust memory.
1021
 
        chunks_to_lines = osutils.chunks_to_lines
1022
 
        for record in self.get_record_stream(needed_parents, 'unordered',
1023
 
            True):
1024
 
            if record.storage_kind == 'absent':
1025
 
                continue
1026
 
            mpvf.add_version(chunks_to_lines(record.get_bytes_as('chunked')),
1027
 
                record.key, [])
1028
 
        for (key, parent_keys, expected_sha1, mpdiff), lines in\
1029
 
            zip(records, mpvf.get_line_list(versions)):
1030
 
            if len(parent_keys) == 1:
1031
 
                left_matching_blocks = list(mpdiff.get_matching_blocks(0,
1032
 
                    mpvf.get_diff(parent_keys[0]).num_lines()))
1033
 
            else:
1034
 
                left_matching_blocks = None
1035
 
            version_sha1, _, version_text = self.add_lines(key,
1036
 
                parent_keys, lines, vf_parents,
1037
 
                left_matching_blocks=left_matching_blocks)
1038
 
            if version_sha1 != expected_sha1:
1039
 
                raise errors.VersionedFileInvalidChecksum(version)
1040
 
            vf_parents[key] = version_text
1041
 
 
1042
 
    def annotate(self, key):
1043
 
        """Return a list of (version-key, line) tuples for the text of key.
1044
 
 
1045
 
        :raise RevisionNotPresent: If the key is not present.
1046
 
        """
1047
 
        raise NotImplementedError(self.annotate)
1048
 
 
1049
 
    def check(self, progress_bar=None):
1050
 
        """Check this object for integrity.
1051
 
        
1052
 
        :param progress_bar: A progress bar to output as the check progresses.
1053
 
        :param keys: Specific keys within the VersionedFiles to check. When
1054
 
            this parameter is not None, check() becomes a generator as per
1055
 
            get_record_stream. The difference to get_record_stream is that
1056
 
            more or deeper checks will be performed.
1057
 
        :return: None, or if keys was supplied a generator as per
1058
 
            get_record_stream.
1059
 
        """
1060
 
        raise NotImplementedError(self.check)
1061
 
 
1062
 
    @staticmethod
1063
 
    def check_not_reserved_id(version_id):
1064
 
        revision.check_not_reserved_id(version_id)
1065
 
 
1066
 
    def clear_cache(self):
1067
 
        """Clear whatever caches this VersionedFile holds.
1068
 
 
1069
 
        This is generally called after an operation has been performed, when we
1070
 
        don't expect to be using this versioned file again soon.
1071
 
        """
1072
 
 
1073
 
    def _check_lines_not_unicode(self, lines):
1074
 
        """Check that lines being added to a versioned file are not unicode."""
1075
 
        for line in lines:
1076
 
            if line.__class__ is not str:
1077
 
                raise errors.BzrBadParameterUnicode("lines")
1078
 
 
1079
 
    def _check_lines_are_lines(self, lines):
1080
 
        """Check that the lines really are full lines without inline EOL."""
1081
 
        for line in lines:
1082
 
            if '\n' in line[:-1]:
1083
 
                raise errors.BzrBadParameterContainsNewline("lines")
1084
 
 
1085
 
    def get_known_graph_ancestry(self, keys):
1086
 
        """Get a KnownGraph instance with the ancestry of keys."""
1087
 
        # most basic implementation is a loop around get_parent_map
1088
 
        pending = set(keys)
1089
 
        parent_map = {}
1090
 
        while pending:
1091
 
            this_parent_map = self.get_parent_map(pending)
1092
 
            parent_map.update(this_parent_map)
1093
 
            pending = set()
1094
 
            map(pending.update, this_parent_map.itervalues())
1095
 
            pending = pending.difference(parent_map)
1096
 
        kg = _mod_graph.KnownGraph(parent_map)
1097
 
        return kg
1098
 
 
1099
 
    def get_parent_map(self, keys):
1100
 
        """Get a map of the parents of keys.
1101
 
 
1102
 
        :param keys: The keys to look up parents for.
1103
 
        :return: A mapping from keys to parents. Absent keys are absent from
1104
 
            the mapping.
1105
 
        """
1106
 
        raise NotImplementedError(self.get_parent_map)
1107
 
 
1108
 
    def get_record_stream(self, keys, ordering, include_delta_closure):
1109
 
        """Get a stream of records for keys.
1110
 
 
1111
 
        :param keys: The keys to include.
1112
 
        :param ordering: Either 'unordered' or 'topological'. A topologically
1113
 
            sorted stream has compression parents strictly before their
1114
 
            children.
1115
 
        :param include_delta_closure: If True then the closure across any
1116
 
            compression parents will be included (in the opaque data).
1117
 
        :return: An iterator of ContentFactory objects, each of which is only
1118
 
            valid until the iterator is advanced.
1119
 
        """
1120
 
        raise NotImplementedError(self.get_record_stream)
1121
 
 
1122
 
    def get_sha1s(self, keys):
1123
 
        """Get the sha1's of the texts for the given keys.
1124
 
 
1125
 
        :param keys: The names of the keys to lookup
1126
 
        :return: a dict from key to sha1 digest. Keys of texts which are not
1127
 
            present in the store are not present in the returned
1128
 
            dictionary.
1129
 
        """
1130
 
        raise NotImplementedError(self.get_sha1s)
1131
 
 
1132
 
    has_key = index._has_key_from_parent_map
1133
 
 
1134
 
    def get_missing_compression_parent_keys(self):
1135
 
        """Return an iterable of keys of missing compression parents.
1136
 
 
1137
 
        Check this after calling insert_record_stream to find out if there are
1138
 
        any missing compression parents.  If there are, the records that
1139
 
        depend on them are not able to be inserted safely. The precise
1140
 
        behaviour depends on the concrete VersionedFiles class in use.
1141
 
 
1142
 
        Classes that do not support this will raise NotImplementedError.
1143
 
        """
1144
 
        raise NotImplementedError(self.get_missing_compression_parent_keys)
1145
 
 
1146
 
    def insert_record_stream(self, stream):
1147
 
        """Insert a record stream into this container.
1148
 
 
1149
 
        :param stream: A stream of records to insert.
1150
 
        :return: None
1151
 
        :seealso VersionedFile.get_record_stream:
1152
 
        """
1153
 
        raise NotImplementedError
1154
 
 
1155
 
    def iter_lines_added_or_present_in_keys(self, keys, pb=None):
1156
 
        """Iterate over the lines in the versioned files from keys.
1157
 
 
1158
 
        This may return lines from other keys. Each item the returned
1159
 
        iterator yields is a tuple of a line and a text version that that line
1160
 
        is present in (not introduced in).
1161
 
 
1162
 
        Ordering of results is in whatever order is most suitable for the
1163
 
        underlying storage format.
1164
 
 
1165
 
        If a progress bar is supplied, it may be used to indicate progress.
1166
 
        The caller is responsible for cleaning up progress bars (because this
1167
 
        is an iterator).
1168
 
 
1169
 
        NOTES:
1170
 
         * Lines are normalised by the underlying store: they will all have \n
1171
 
           terminators.
1172
 
         * Lines are returned in arbitrary order.
1173
 
 
1174
 
        :return: An iterator over (line, key).
1175
 
        """
1176
 
        raise NotImplementedError(self.iter_lines_added_or_present_in_keys)
1177
 
 
1178
 
    def keys(self):
1179
 
        """Return a iterable of the keys for all the contained texts."""
1180
 
        raise NotImplementedError(self.keys)
1181
 
 
1182
 
    def make_mpdiffs(self, keys):
1183
 
        """Create multiparent diffs for specified keys."""
1184
 
        generator = _MPDiffGenerator(self, keys)
1185
 
        return generator.compute_diffs()
1186
 
 
1187
 
    def get_annotator(self):
1188
 
        return annotate.Annotator(self)
1189
 
 
1190
 
    missing_keys = index._missing_keys_from_parent_map
1191
 
 
1192
 
    def _extract_blocks(self, version_id, source, target):
1193
 
        return None
1194
 
 
1195
 
    def _transitive_fallbacks(self):
1196
 
        """Return the whole stack of fallback versionedfiles.
1197
 
 
1198
 
        This VersionedFiles may have a list of fallbacks, but it doesn't
1199
 
        necessarily know about the whole stack going down, and it can't know
1200
 
        at open time because they may change after the objects are opened.
1201
 
        """
1202
 
        all_fallbacks = []
1203
 
        for a_vfs in self._immediate_fallback_vfs:
1204
 
            all_fallbacks.append(a_vfs)
1205
 
            all_fallbacks.extend(a_vfs._transitive_fallbacks())
1206
 
        return all_fallbacks
1207
 
 
1208
 
 
1209
 
class ThunkedVersionedFiles(VersionedFiles):
1210
 
    """Storage for many versioned files thunked onto a 'VersionedFile' class.
1211
 
 
1212
 
    This object allows a single keyspace for accessing the history graph and
1213
 
    contents of named bytestrings.
1214
 
 
1215
 
    Currently no implementation allows the graph of different key prefixes to
1216
 
    intersect, but the API does allow such implementations in the future.
1217
 
    """
1218
 
 
1219
 
    def __init__(self, transport, file_factory, mapper, is_locked):
1220
 
        """Create a ThunkedVersionedFiles."""
1221
 
        self._transport = transport
1222
 
        self._file_factory = file_factory
1223
 
        self._mapper = mapper
1224
 
        self._is_locked = is_locked
1225
 
 
1226
 
    def add_lines(self, key, parents, lines, parent_texts=None,
1227
 
        left_matching_blocks=None, nostore_sha=None, random_id=False,
1228
 
        check_content=True):
1229
 
        """See VersionedFiles.add_lines()."""
1230
 
        path = self._mapper.map(key)
1231
 
        version_id = key[-1]
1232
 
        parents = [parent[-1] for parent in parents]
1233
 
        vf = self._get_vf(path)
1234
 
        try:
1235
 
            try:
1236
 
                return vf.add_lines_with_ghosts(version_id, parents, lines,
1237
 
                    parent_texts=parent_texts,
1238
 
                    left_matching_blocks=left_matching_blocks,
1239
 
                    nostore_sha=nostore_sha, random_id=random_id,
1240
 
                    check_content=check_content)
1241
 
            except NotImplementedError:
1242
 
                return vf.add_lines(version_id, parents, lines,
1243
 
                    parent_texts=parent_texts,
1244
 
                    left_matching_blocks=left_matching_blocks,
1245
 
                    nostore_sha=nostore_sha, random_id=random_id,
1246
 
                    check_content=check_content)
1247
 
        except errors.NoSuchFile:
1248
 
            # parent directory may be missing, try again.
1249
 
            self._transport.mkdir(osutils.dirname(path))
1250
 
            try:
1251
 
                return vf.add_lines_with_ghosts(version_id, parents, lines,
1252
 
                    parent_texts=parent_texts,
1253
 
                    left_matching_blocks=left_matching_blocks,
1254
 
                    nostore_sha=nostore_sha, random_id=random_id,
1255
 
                    check_content=check_content)
1256
 
            except NotImplementedError:
1257
 
                return vf.add_lines(version_id, parents, lines,
1258
 
                    parent_texts=parent_texts,
1259
 
                    left_matching_blocks=left_matching_blocks,
1260
 
                    nostore_sha=nostore_sha, random_id=random_id,
1261
 
                    check_content=check_content)
1262
 
 
1263
 
    def annotate(self, key):
1264
 
        """Return a list of (version-key, line) tuples for the text of key.
1265
 
 
1266
 
        :raise RevisionNotPresent: If the key is not present.
1267
 
        """
1268
 
        prefix = key[:-1]
1269
 
        path = self._mapper.map(prefix)
1270
 
        vf = self._get_vf(path)
1271
 
        origins = vf.annotate(key[-1])
1272
 
        result = []
1273
 
        for origin, line in origins:
1274
 
            result.append((prefix + (origin,), line))
1275
 
        return result
1276
 
 
1277
 
    def check(self, progress_bar=None, keys=None):
1278
 
        """See VersionedFiles.check()."""
1279
 
        # XXX: This is over-enthusiastic but as we only thunk for Weaves today
1280
 
        # this is tolerable. Ideally we'd pass keys down to check() and 
1281
 
        # have the older VersiondFile interface updated too.
1282
 
        for prefix, vf in self._iter_all_components():
1283
 
            vf.check()
1284
 
        if keys is not None:
1285
 
            return self.get_record_stream(keys, 'unordered', True)
1286
 
 
1287
 
    def get_parent_map(self, keys):
1288
 
        """Get a map of the parents of keys.
1289
 
 
1290
 
        :param keys: The keys to look up parents for.
1291
 
        :return: A mapping from keys to parents. Absent keys are absent from
1292
 
            the mapping.
1293
 
        """
1294
 
        prefixes = self._partition_keys(keys)
1295
 
        result = {}
1296
 
        for prefix, suffixes in prefixes.items():
1297
 
            path = self._mapper.map(prefix)
1298
 
            vf = self._get_vf(path)
1299
 
            parent_map = vf.get_parent_map(suffixes)
1300
 
            for key, parents in parent_map.items():
1301
 
                result[prefix + (key,)] = tuple(
1302
 
                    prefix + (parent,) for parent in parents)
1303
 
        return result
1304
 
 
1305
 
    def _get_vf(self, path):
1306
 
        if not self._is_locked():
1307
 
            raise errors.ObjectNotLocked(self)
1308
 
        return self._file_factory(path, self._transport, create=True,
1309
 
            get_scope=lambda:None)
1310
 
 
1311
 
    def _partition_keys(self, keys):
1312
 
        """Turn keys into a dict of prefix:suffix_list."""
1313
 
        result = {}
1314
 
        for key in keys:
1315
 
            prefix_keys = result.setdefault(key[:-1], [])
1316
 
            prefix_keys.append(key[-1])
1317
 
        return result
1318
 
 
1319
 
    def _get_all_prefixes(self):
1320
 
        # Identify all key prefixes.
1321
 
        # XXX: A bit hacky, needs polish.
1322
 
        if type(self._mapper) == ConstantMapper:
1323
 
            paths = [self._mapper.map(())]
1324
 
            prefixes = [()]
1325
 
        else:
1326
 
            relpaths = set()
1327
 
            for quoted_relpath in self._transport.iter_files_recursive():
1328
 
                path, ext = os.path.splitext(quoted_relpath)
1329
 
                relpaths.add(path)
1330
 
            paths = list(relpaths)
1331
 
            prefixes = [self._mapper.unmap(path) for path in paths]
1332
 
        return zip(paths, prefixes)
1333
 
 
1334
 
    def get_record_stream(self, keys, ordering, include_delta_closure):
1335
 
        """See VersionedFiles.get_record_stream()."""
1336
 
        # Ordering will be taken care of by each partitioned store; group keys
1337
 
        # by partition.
1338
 
        keys = sorted(keys)
1339
 
        for prefix, suffixes, vf in self._iter_keys_vf(keys):
1340
 
            suffixes = [(suffix,) for suffix in suffixes]
1341
 
            for record in vf.get_record_stream(suffixes, ordering,
1342
 
                include_delta_closure):
1343
 
                if record.parents is not None:
1344
 
                    record.parents = tuple(
1345
 
                        prefix + parent for parent in record.parents)
1346
 
                record.key = prefix + record.key
1347
 
                yield record
1348
 
 
1349
 
    def _iter_keys_vf(self, keys):
1350
 
        prefixes = self._partition_keys(keys)
1351
 
        sha1s = {}
1352
 
        for prefix, suffixes in prefixes.items():
1353
 
            path = self._mapper.map(prefix)
1354
 
            vf = self._get_vf(path)
1355
 
            yield prefix, suffixes, vf
1356
 
 
1357
 
    def get_sha1s(self, keys):
1358
 
        """See VersionedFiles.get_sha1s()."""
1359
 
        sha1s = {}
1360
 
        for prefix,suffixes, vf in self._iter_keys_vf(keys):
1361
 
            vf_sha1s = vf.get_sha1s(suffixes)
1362
 
            for suffix, sha1 in vf_sha1s.iteritems():
1363
 
                sha1s[prefix + (suffix,)] = sha1
1364
 
        return sha1s
1365
 
 
1366
 
    def insert_record_stream(self, stream):
1367
 
        """Insert a record stream into this container.
1368
 
 
1369
 
        :param stream: A stream of records to insert.
1370
 
        :return: None
1371
 
        :seealso VersionedFile.get_record_stream:
1372
 
        """
1373
 
        for record in stream:
1374
 
            prefix = record.key[:-1]
1375
 
            key = record.key[-1:]
1376
 
            if record.parents is not None:
1377
 
                parents = [parent[-1:] for parent in record.parents]
1378
 
            else:
1379
 
                parents = None
1380
 
            thunk_record = AdapterFactory(key, parents, record)
1381
 
            path = self._mapper.map(prefix)
1382
 
            # Note that this parses the file many times; we can do better but
1383
 
            # as this only impacts weaves in terms of performance, it is
1384
 
            # tolerable.
1385
 
            vf = self._get_vf(path)
1386
 
            vf.insert_record_stream([thunk_record])
1387
 
 
1388
 
    def iter_lines_added_or_present_in_keys(self, keys, pb=None):
1389
 
        """Iterate over the lines in the versioned files from keys.
1390
 
 
1391
 
        This may return lines from other keys. Each item the returned
1392
 
        iterator yields is a tuple of a line and a text version that that line
1393
 
        is present in (not introduced in).
1394
 
 
1395
 
        Ordering of results is in whatever order is most suitable for the
1396
 
        underlying storage format.
1397
 
 
1398
 
        If a progress bar is supplied, it may be used to indicate progress.
1399
 
        The caller is responsible for cleaning up progress bars (because this
1400
 
        is an iterator).
1401
 
 
1402
 
        NOTES:
1403
 
         * Lines are normalised by the underlying store: they will all have \n
1404
 
           terminators.
1405
 
         * Lines are returned in arbitrary order.
1406
 
 
1407
 
        :return: An iterator over (line, key).
1408
 
        """
1409
 
        for prefix, suffixes, vf in self._iter_keys_vf(keys):
1410
 
            for line, version in vf.iter_lines_added_or_present_in_versions(suffixes):
1411
 
                yield line, prefix + (version,)
1412
 
 
1413
 
    def _iter_all_components(self):
1414
 
        for path, prefix in self._get_all_prefixes():
1415
 
            yield prefix, self._get_vf(path)
1416
 
 
1417
 
    def keys(self):
1418
 
        """See VersionedFiles.keys()."""
1419
 
        result = set()
1420
 
        for prefix, vf in self._iter_all_components():
1421
 
            for suffix in vf.versions():
1422
 
                result.add(prefix + (suffix,))
1423
 
        return result
1424
 
 
1425
 
 
1426
 
class VersionedFilesWithFallbacks(VersionedFiles):
1427
 
 
1428
 
    def without_fallbacks(self):
1429
 
        """Return a clone of this object without any fallbacks configured."""
1430
 
        raise NotImplementedError(self.without_fallbacks)
1431
 
 
1432
 
    def add_fallback_versioned_files(self, a_versioned_files):
1433
 
        """Add a source of texts for texts not present in this knit.
1434
 
 
1435
 
        :param a_versioned_files: A VersionedFiles object.
1436
 
        """
1437
 
        raise NotImplementedError(self.add_fallback_versioned_files)
1438
 
 
1439
 
    def get_known_graph_ancestry(self, keys):
1440
 
        """Get a KnownGraph instance with the ancestry of keys."""
1441
 
        parent_map, missing_keys = self._index.find_ancestry(keys)
1442
 
        for fallback in self._transitive_fallbacks():
1443
 
            if not missing_keys:
1444
 
                break
1445
 
            (f_parent_map, f_missing_keys) = fallback._index.find_ancestry(
1446
 
                                                missing_keys)
1447
 
            parent_map.update(f_parent_map)
1448
 
            missing_keys = f_missing_keys
1449
 
        kg = _mod_graph.KnownGraph(parent_map)
1450
 
        return kg
1451
 
 
1452
 
 
1453
 
class _PlanMergeVersionedFile(VersionedFiles):
 
495
class _PlanMergeVersionedFile(object):
1454
496
    """A VersionedFile for uncommitted and committed texts.
1455
497
 
1456
498
    It is intended to allow merges to be planned with working tree texts.
1457
 
    It implements only the small part of the VersionedFiles interface used by
 
499
    It implements only the small part of the VersionedFile interface used by
1458
500
    PlanMerge.  It falls back to multiple versionedfiles for data not stored in
1459
501
    _PlanMergeVersionedFile itself.
1460
 
 
1461
 
    :ivar: fallback_versionedfiles a list of VersionedFiles objects that can be
1462
 
        queried for missing texts.
1463
502
    """
1464
503
 
1465
 
    def __init__(self, file_id):
1466
 
        """Create a _PlanMergeVersionedFile.
 
504
    def __init__(self, file_id, fallback_versionedfiles=None):
 
505
        """Constuctor
1467
506
 
1468
 
        :param file_id: Used with _PlanMerge code which is not yet fully
1469
 
            tuple-keyspace aware.
 
507
        :param file_id: Used when raising exceptions.
 
508
        :param fallback_versionedfiles: If supplied, the set of fallbacks to
 
509
            use.  Otherwise, _PlanMergeVersionedFile.fallback_versionedfiles
 
510
            can be appended to later.
1470
511
        """
1471
512
        self._file_id = file_id
1472
 
        # fallback locations
1473
 
        self.fallback_versionedfiles = []
1474
 
        # Parents for locally held keys.
 
513
        if fallback_versionedfiles is None:
 
514
            self.fallback_versionedfiles = []
 
515
        else:
 
516
            self.fallback_versionedfiles = fallback_versionedfiles
1475
517
        self._parents = {}
1476
 
        # line data for locally held keys.
1477
518
        self._lines = {}
1478
 
        # key lookup providers
1479
 
        self._providers = [_mod_graph.DictParentsProvider(self._parents)]
1480
519
 
1481
520
    def plan_merge(self, ver_a, ver_b, base=None):
1482
521
        """See VersionedFile.plan_merge"""
1483
522
        from bzrlib.merge import _PlanMerge
1484
523
        if base is None:
1485
 
            return _PlanMerge(ver_a, ver_b, self, (self._file_id,)).plan_merge()
1486
 
        old_plan = list(_PlanMerge(ver_a, base, self, (self._file_id,)).plan_merge())
1487
 
        new_plan = list(_PlanMerge(ver_a, ver_b, self, (self._file_id,)).plan_merge())
 
524
            return _PlanMerge(ver_a, ver_b, self).plan_merge()
 
525
        old_plan = list(_PlanMerge(ver_a, base, self).plan_merge())
 
526
        new_plan = list(_PlanMerge(ver_a, ver_b, self).plan_merge())
1488
527
        return _PlanMerge._subtract_plans(old_plan, new_plan)
1489
528
 
1490
529
    def plan_lca_merge(self, ver_a, ver_b, base=None):
1491
530
        from bzrlib.merge import _PlanLCAMerge
1492
 
        graph = _mod_graph.Graph(self)
1493
 
        new_plan = _PlanLCAMerge(ver_a, ver_b, self, (self._file_id,), graph).plan_merge()
 
531
        graph = self._get_graph()
 
532
        new_plan = _PlanLCAMerge(ver_a, ver_b, self, graph).plan_merge()
1494
533
        if base is None:
1495
534
            return new_plan
1496
 
        old_plan = _PlanLCAMerge(ver_a, base, self, (self._file_id,), graph).plan_merge()
 
535
        old_plan = _PlanLCAMerge(ver_a, base, self, graph).plan_merge()
1497
536
        return _PlanLCAMerge._subtract_plans(list(old_plan), list(new_plan))
1498
537
 
1499
 
    def add_lines(self, key, parents, lines):
1500
 
        """See VersionedFiles.add_lines
 
538
    def add_lines(self, version_id, parents, lines):
 
539
        """See VersionedFile.add_lines
1501
540
 
1502
 
        Lines are added locally, not to fallback versionedfiles.  Also, ghosts
1503
 
        are permitted.  Only reserved ids are permitted.
 
541
        Lines are added locally, not fallback versionedfiles.  Also, ghosts are
 
542
        permitted.  Only reserved ids are permitted.
1504
543
        """
1505
 
        if type(key) is not tuple:
1506
 
            raise TypeError(key)
1507
 
        if not revision.is_reserved_id(key[-1]):
 
544
        if not revision.is_reserved_id(version_id):
1508
545
            raise ValueError('Only reserved ids may be used')
1509
546
        if parents is None:
1510
547
            raise ValueError('Parents may not be None')
1511
548
        if lines is None:
1512
549
            raise ValueError('Lines may not be None')
1513
 
        self._parents[key] = tuple(parents)
1514
 
        self._lines[key] = lines
 
550
        self._parents[version_id] = parents
 
551
        self._lines[version_id] = lines
1515
552
 
1516
 
    def get_record_stream(self, keys, ordering, include_delta_closure):
1517
 
        pending = set(keys)
1518
 
        for key in keys:
1519
 
            if key in self._lines:
1520
 
                lines = self._lines[key]
1521
 
                parents = self._parents[key]
1522
 
                pending.remove(key)
1523
 
                yield ChunkedContentFactory(key, parents, None, lines)
 
553
    def get_lines(self, version_id):
 
554
        """See VersionedFile.get_ancestry"""
 
555
        lines = self._lines.get(version_id)
 
556
        if lines is not None:
 
557
            return lines
1524
558
        for versionedfile in self.fallback_versionedfiles:
1525
 
            for record in versionedfile.get_record_stream(
1526
 
                pending, 'unordered', True):
1527
 
                if record.storage_kind == 'absent':
 
559
            try:
 
560
                return versionedfile.get_lines(version_id)
 
561
            except errors.RevisionNotPresent:
 
562
                continue
 
563
        else:
 
564
            raise errors.RevisionNotPresent(version_id, self._file_id)
 
565
 
 
566
    def get_ancestry(self, version_id, topo_sorted=False):
 
567
        """See VersionedFile.get_ancestry.
 
568
 
 
569
        Note that this implementation assumes that if a VersionedFile can
 
570
        answer get_ancestry at all, it can give an authoritative answer.  In
 
571
        fact, ghosts can invalidate this assumption.  But it's good enough
 
572
        99% of the time, and far cheaper/simpler.
 
573
 
 
574
        Also note that the results of this version are never topologically
 
575
        sorted, and are a set.
 
576
        """
 
577
        if topo_sorted:
 
578
            raise ValueError('This implementation does not provide sorting')
 
579
        parents = self._parents.get(version_id)
 
580
        if parents is None:
 
581
            for vf in self.fallback_versionedfiles:
 
582
                try:
 
583
                    return vf.get_ancestry(version_id, topo_sorted=False)
 
584
                except errors.RevisionNotPresent:
1528
585
                    continue
1529
 
                else:
1530
 
                    pending.remove(record.key)
1531
 
                    yield record
1532
 
            if not pending:
1533
 
                return
1534
 
        # report absent entries
1535
 
        for key in pending:
1536
 
            yield AbsentContentFactory(key)
1537
 
 
1538
 
    def get_parent_map(self, keys):
1539
 
        """See VersionedFiles.get_parent_map"""
1540
 
        # We create a new provider because a fallback may have been added.
1541
 
        # If we make fallbacks private we can update a stack list and avoid
1542
 
        # object creation thrashing.
1543
 
        keys = set(keys)
1544
 
        result = {}
1545
 
        if revision.NULL_REVISION in keys:
1546
 
            keys.remove(revision.NULL_REVISION)
1547
 
            result[revision.NULL_REVISION] = ()
1548
 
        self._providers = self._providers[:1] + self.fallback_versionedfiles
1549
 
        result.update(
1550
 
            _mod_graph.StackedParentsProvider(
1551
 
                self._providers).get_parent_map(keys))
1552
 
        for key, parents in result.iteritems():
1553
 
            if parents == ():
1554
 
                result[key] = (revision.NULL_REVISION,)
1555
 
        return result
 
586
            else:
 
587
                raise errors.RevisionNotPresent(version_id, self._file_id)
 
588
        ancestry = set([version_id])
 
589
        for parent in parents:
 
590
            ancestry.update(self.get_ancestry(parent, topo_sorted=False))
 
591
        return ancestry
 
592
 
 
593
    def get_parents(self, version_id):
 
594
        """See VersionedFile.get_parents"""
 
595
        parents = self._parents.get(version_id)
 
596
        if parents is not None:
 
597
            return parents
 
598
        for versionedfile in self.fallback_versionedfiles:
 
599
            try:
 
600
                return versionedfile.get_parents(version_id)
 
601
            except errors.RevisionNotPresent:
 
602
                continue
 
603
        else:
 
604
            raise errors.RevisionNotPresent(version_id, self._file_id)
 
605
 
 
606
    def _get_graph(self):
 
607
        from bzrlib.graph import (
 
608
            DictParentsProvider,
 
609
            Graph,
 
610
            _StackedParentsProvider,
 
611
            )
 
612
        from bzrlib.repofmt.knitrepo import _KnitParentsProvider
 
613
        parent_providers = [DictParentsProvider(self._parents)]
 
614
        for vf in self.fallback_versionedfiles:
 
615
            parent_providers.append(_KnitParentsProvider(vf))
 
616
        return Graph(_StackedParentsProvider(parent_providers))
1556
617
 
1557
618
 
1558
619
class PlanWeaveMerge(TextMerge):
1559
620
    """Weave merge that takes a plan as its input.
1560
 
 
 
621
    
1561
622
    This exists so that VersionedFile.plan_merge is implementable.
1562
623
    Most callers will want to use WeaveMerge instead.
1563
624
    """
1565
626
    def __init__(self, plan, a_marker=TextMerge.A_MARKER,
1566
627
                 b_marker=TextMerge.B_MARKER):
1567
628
        TextMerge.__init__(self, a_marker, b_marker)
1568
 
        self.plan = list(plan)
 
629
        self.plan = plan
1569
630
 
1570
631
    def _merge_struct(self):
1571
632
        lines_a = []
1584
645
                yield(lines_a,)
1585
646
            else:
1586
647
                yield (lines_a, lines_b)
1587
 
 
 
648
       
1588
649
        # We previously considered either 'unchanged' or 'killed-both' lines
1589
650
        # to be possible places to resynchronize.  However, assuming agreement
1590
651
        # on killed-both lines may be too aggressive. -- mbp 20060324
1596
657
                lines_a = []
1597
658
                lines_b = []
1598
659
                ch_a = ch_b = False
1599
 
 
 
660
                
1600
661
            if state == 'unchanged':
1601
662
                if line:
1602
663
                    yield ([line],)
1618
679
            elif state == 'conflicted-b':
1619
680
                ch_b = ch_a = True
1620
681
                lines_b.append(line)
1621
 
            elif state == 'killed-both':
1622
 
                # This counts as a change, even though there is no associated
1623
 
                # line
1624
 
                ch_b = ch_a = True
1625
682
            else:
1626
 
                if state not in ('irrelevant', 'ghost-a', 'ghost-b',
1627
 
                        'killed-base'):
1628
 
                    raise AssertionError(state)
 
683
                assert state in ('irrelevant', 'ghost-a', 'ghost-b', 
 
684
                                 'killed-base', 'killed-both'), state
1629
685
        for struct in outstanding_struct():
1630
686
            yield struct
1631
687
 
1632
 
    def base_from_plan(self):
1633
 
        """Construct a BASE file from the plan text."""
1634
 
        base_lines = []
1635
 
        for state, line in self.plan:
1636
 
            if state in ('killed-a', 'killed-b', 'killed-both', 'unchanged'):
1637
 
                # If unchanged, then this line is straight from base. If a or b
1638
 
                # or both killed the line, then it *used* to be in base.
1639
 
                base_lines.append(line)
1640
 
            else:
1641
 
                if state not in ('killed-base', 'irrelevant',
1642
 
                                 'ghost-a', 'ghost-b',
1643
 
                                 'new-a', 'new-b',
1644
 
                                 'conflicted-a', 'conflicted-b'):
1645
 
                    # killed-base, irrelevant means it doesn't apply
1646
 
                    # ghost-a/ghost-b are harder to say for sure, but they
1647
 
                    # aren't in the 'inc_c' which means they aren't in the
1648
 
                    # shared base of a & b. So we don't include them.  And
1649
 
                    # obviously if the line is newly inserted, it isn't in base
1650
 
 
1651
 
                    # If 'conflicted-a' or b, then it is new vs one base, but
1652
 
                    # old versus another base. However, if we make it present
1653
 
                    # in the base, it will be deleted from the target, and it
1654
 
                    # seems better to get a line doubled in the merge result,
1655
 
                    # rather than have it deleted entirely.
1656
 
                    # Example, each node is the 'text' at that point:
1657
 
                    #           MN
1658
 
                    #          /   \
1659
 
                    #        MaN   MbN
1660
 
                    #         |  X  |
1661
 
                    #        MabN MbaN
1662
 
                    #          \   /
1663
 
                    #           ???
1664
 
                    # There was a criss-cross conflict merge. Both sides
1665
 
                    # include the other, but put themselves first.
1666
 
                    # Weave marks this as a 'clean' merge, picking OTHER over
1667
 
                    # THIS. (Though the details depend on order inserted into
1668
 
                    # weave, etc.)
1669
 
                    # LCA generates a plan:
1670
 
                    # [('unchanged', M),
1671
 
                    #  ('conflicted-b', b),
1672
 
                    #  ('unchanged', a),
1673
 
                    #  ('conflicted-a', b),
1674
 
                    #  ('unchanged', N)]
1675
 
                    # If you mark 'conflicted-*' as part of BASE, then a 3-way
1676
 
                    # merge tool will cleanly generate "MaN" (as BASE vs THIS
1677
 
                    # removes one 'b', and BASE vs OTHER removes the other)
1678
 
                    # If you include neither, 3-way creates a clean "MbabN" as
1679
 
                    # THIS adds one 'b', and OTHER does too.
1680
 
                    # It seems that having the line 2 times is better than
1681
 
                    # having it omitted. (Easier to manually delete than notice
1682
 
                    # it needs to be added.)
1683
 
                    raise AssertionError('Unknown state: %s' % (state,))
1684
 
        return base_lines
1685
 
 
1686
688
 
1687
689
class WeaveMerge(PlanWeaveMerge):
1688
690
    """Weave merge that takes a VersionedFile and two versions as its input."""
1689
691
 
1690
 
    def __init__(self, versionedfile, ver_a, ver_b,
 
692
    def __init__(self, versionedfile, ver_a, ver_b, 
1691
693
        a_marker=PlanWeaveMerge.A_MARKER, b_marker=PlanWeaveMerge.B_MARKER):
1692
694
        plan = versionedfile.plan_merge(ver_a, ver_b)
1693
695
        PlanWeaveMerge.__init__(self, plan, a_marker, b_marker)
1694
696
 
1695
697
 
1696
 
class VirtualVersionedFiles(VersionedFiles):
1697
 
    """Dummy implementation for VersionedFiles that uses other functions for
1698
 
    obtaining fulltexts and parent maps.
1699
 
 
1700
 
    This is always on the bottom of the stack and uses string keys
1701
 
    (rather than tuples) internally.
1702
 
    """
1703
 
 
1704
 
    def __init__(self, get_parent_map, get_lines):
1705
 
        """Create a VirtualVersionedFiles.
1706
 
 
1707
 
        :param get_parent_map: Same signature as Repository.get_parent_map.
1708
 
        :param get_lines: Should return lines for specified key or None if
1709
 
                          not available.
1710
 
        """
1711
 
        super(VirtualVersionedFiles, self).__init__()
1712
 
        self._get_parent_map = get_parent_map
1713
 
        self._get_lines = get_lines
1714
 
 
1715
 
    def check(self, progressbar=None):
1716
 
        """See VersionedFiles.check.
1717
 
 
1718
 
        :note: Always returns True for VirtualVersionedFiles.
1719
 
        """
1720
 
        return True
1721
 
 
1722
 
    def add_mpdiffs(self, records):
1723
 
        """See VersionedFiles.mpdiffs.
1724
 
 
1725
 
        :note: Not implemented for VirtualVersionedFiles.
1726
 
        """
1727
 
        raise NotImplementedError(self.add_mpdiffs)
1728
 
 
1729
 
    def get_parent_map(self, keys):
1730
 
        """See VersionedFiles.get_parent_map."""
1731
 
        return dict([((k,), tuple([(p,) for p in v]))
1732
 
            for k,v in self._get_parent_map([k for (k,) in keys]).iteritems()])
1733
 
 
1734
 
    def get_sha1s(self, keys):
1735
 
        """See VersionedFiles.get_sha1s."""
1736
 
        ret = {}
1737
 
        for (k,) in keys:
1738
 
            lines = self._get_lines(k)
1739
 
            if lines is not None:
1740
 
                if not isinstance(lines, list):
1741
 
                    raise AssertionError
1742
 
                ret[(k,)] = osutils.sha_strings(lines)
1743
 
        return ret
1744
 
 
1745
 
    def get_record_stream(self, keys, ordering, include_delta_closure):
1746
 
        """See VersionedFiles.get_record_stream."""
1747
 
        for (k,) in list(keys):
1748
 
            lines = self._get_lines(k)
1749
 
            if lines is not None:
1750
 
                if not isinstance(lines, list):
1751
 
                    raise AssertionError
1752
 
                yield ChunkedContentFactory((k,), None,
1753
 
                        sha1=osutils.sha_strings(lines),
1754
 
                        chunks=lines)
1755
 
            else:
1756
 
                yield AbsentContentFactory((k,))
1757
 
 
1758
 
    def iter_lines_added_or_present_in_keys(self, keys, pb=None):
1759
 
        """See VersionedFile.iter_lines_added_or_present_in_versions()."""
1760
 
        for i, (key,) in enumerate(keys):
1761
 
            if pb is not None:
1762
 
                pb.update("Finding changed lines", i, len(keys))
1763
 
            for l in self._get_lines(key):
1764
 
                yield (l, key)
1765
 
 
1766
 
 
1767
 
class NoDupeAddLinesDecorator(object):
1768
 
    """Decorator for a VersionedFiles that skips doing an add_lines if the key
1769
 
    is already present.
1770
 
    """
1771
 
 
1772
 
    def __init__(self, store):
1773
 
        self._store = store
1774
 
 
1775
 
    def add_lines(self, key, parents, lines, parent_texts=None,
1776
 
            left_matching_blocks=None, nostore_sha=None, random_id=False,
1777
 
            check_content=True):
1778
 
        """See VersionedFiles.add_lines.
1779
 
        
1780
 
        This implementation may return None as the third element of the return
1781
 
        value when the original store wouldn't.
1782
 
        """
1783
 
        if nostore_sha:
1784
 
            raise NotImplementedError(
1785
 
                "NoDupeAddLinesDecorator.add_lines does not implement the "
1786
 
                "nostore_sha behaviour.")
1787
 
        if key[-1] is None:
1788
 
            sha1 = osutils.sha_strings(lines)
1789
 
            key = ("sha1:" + sha1,)
1790
 
        else:
1791
 
            sha1 = None
1792
 
        if key in self._store.get_parent_map([key]):
1793
 
            # This key has already been inserted, so don't do it again.
1794
 
            if sha1 is None:
1795
 
                sha1 = osutils.sha_strings(lines)
1796
 
            return sha1, sum(map(len, lines)), None
1797
 
        return self._store.add_lines(key, parents, lines,
1798
 
                parent_texts=parent_texts,
1799
 
                left_matching_blocks=left_matching_blocks,
1800
 
                nostore_sha=nostore_sha, random_id=random_id,
1801
 
                check_content=check_content)
1802
 
 
1803
 
    def __getattr__(self, name):
1804
 
        return getattr(self._store, name)
1805
 
 
1806
 
 
1807
 
def network_bytes_to_kind_and_offset(network_bytes):
1808
 
    """Strip of a record kind from the front of network_bytes.
1809
 
 
1810
 
    :param network_bytes: The bytes of a record.
1811
 
    :return: A tuple (storage_kind, offset_of_remaining_bytes)
1812
 
    """
1813
 
    line_end = network_bytes.find('\n')
1814
 
    storage_kind = network_bytes[:line_end]
1815
 
    return storage_kind, line_end + 1
1816
 
 
1817
 
 
1818
 
class NetworkRecordStream(object):
1819
 
    """A record_stream which reconstitures a serialised stream."""
1820
 
 
1821
 
    def __init__(self, bytes_iterator):
1822
 
        """Create a NetworkRecordStream.
1823
 
 
1824
 
        :param bytes_iterator: An iterator of bytes. Each item in this
1825
 
            iterator should have been obtained from a record_streams'
1826
 
            record.get_bytes_as(record.storage_kind) call.
1827
 
        """
1828
 
        self._bytes_iterator = bytes_iterator
1829
 
        self._kind_factory = {
1830
 
            'fulltext': fulltext_network_to_record,
1831
 
            'groupcompress-block': groupcompress.network_block_to_records,
1832
 
            'knit-ft-gz': knit.knit_network_to_record,
1833
 
            'knit-delta-gz': knit.knit_network_to_record,
1834
 
            'knit-annotated-ft-gz': knit.knit_network_to_record,
1835
 
            'knit-annotated-delta-gz': knit.knit_network_to_record,
1836
 
            'knit-delta-closure': knit.knit_delta_closure_to_records,
1837
 
            }
1838
 
 
1839
 
    def read(self):
1840
 
        """Read the stream.
1841
 
 
1842
 
        :return: An iterator as per VersionedFiles.get_record_stream().
1843
 
        """
1844
 
        for bytes in self._bytes_iterator:
1845
 
            storage_kind, line_end = network_bytes_to_kind_and_offset(bytes)
1846
 
            for record in self._kind_factory[storage_kind](
1847
 
                storage_kind, bytes, line_end):
1848
 
                yield record
1849
 
 
1850
 
 
1851
 
def fulltext_network_to_record(kind, bytes, line_end):
1852
 
    """Convert a network fulltext record to record."""
1853
 
    meta_len, = struct.unpack('!L', bytes[line_end:line_end+4])
1854
 
    record_meta = bytes[line_end+4:line_end+4+meta_len]
1855
 
    key, parents = bencode.bdecode_as_tuple(record_meta)
1856
 
    if parents == 'nil':
1857
 
        parents = None
1858
 
    fulltext = bytes[line_end+4+meta_len:]
1859
 
    return [FulltextContentFactory(key, parents, None, fulltext)]
1860
 
 
1861
 
 
1862
 
def _length_prefix(bytes):
1863
 
    return struct.pack('!L', len(bytes))
1864
 
 
1865
 
 
1866
 
def record_to_fulltext_bytes(record):
1867
 
    if record.parents is None:
1868
 
        parents = 'nil'
1869
 
    else:
1870
 
        parents = record.parents
1871
 
    record_meta = bencode.bencode((record.key, parents))
1872
 
    record_content = record.get_bytes_as('fulltext')
1873
 
    return "fulltext\n%s%s%s" % (
1874
 
        _length_prefix(record_meta), record_meta, record_content)
1875
 
 
1876
 
 
1877
 
def sort_groupcompress(parent_map):
1878
 
    """Sort and group the keys in parent_map into groupcompress order.
1879
 
 
1880
 
    groupcompress is defined (currently) as reverse-topological order, grouped
1881
 
    by the key prefix.
1882
 
 
1883
 
    :return: A sorted-list of keys
1884
 
    """
1885
 
    # gc-optimal ordering is approximately reverse topological,
1886
 
    # properly grouped by file-id.
1887
 
    per_prefix_map = {}
1888
 
    for item in parent_map.iteritems():
1889
 
        key = item[0]
1890
 
        if isinstance(key, str) or len(key) == 1:
1891
 
            prefix = ''
1892
 
        else:
1893
 
            prefix = key[0]
1894
 
        try:
1895
 
            per_prefix_map[prefix].append(item)
1896
 
        except KeyError:
1897
 
            per_prefix_map[prefix] = [item]
1898
 
 
1899
 
    present_keys = []
1900
 
    for prefix in sorted(per_prefix_map):
1901
 
        present_keys.extend(reversed(tsort.topo_sort(per_prefix_map[prefix])))
1902
 
    return present_keys
1903
 
 
1904
 
 
1905
 
class _KeyRefs(object):
1906
 
 
1907
 
    def __init__(self, track_new_keys=False):
1908
 
        # dict mapping 'key' to 'set of keys referring to that key'
1909
 
        self.refs = {}
1910
 
        if track_new_keys:
1911
 
            # set remembering all new keys
1912
 
            self.new_keys = set()
1913
 
        else:
1914
 
            self.new_keys = None
1915
 
 
1916
 
    def clear(self):
1917
 
        if self.refs:
1918
 
            self.refs.clear()
1919
 
        if self.new_keys:
1920
 
            self.new_keys.clear()
1921
 
 
1922
 
    def add_references(self, key, refs):
1923
 
        # Record the new references
1924
 
        for referenced in refs:
1925
 
            try:
1926
 
                needed_by = self.refs[referenced]
1927
 
            except KeyError:
1928
 
                needed_by = self.refs[referenced] = set()
1929
 
            needed_by.add(key)
1930
 
        # Discard references satisfied by the new key
1931
 
        self.add_key(key)
1932
 
 
1933
 
    def get_new_keys(self):
1934
 
        return self.new_keys
1935
 
    
1936
 
    def get_unsatisfied_refs(self):
1937
 
        return self.refs.iterkeys()
1938
 
 
1939
 
    def _satisfy_refs_for_key(self, key):
1940
 
        try:
1941
 
            del self.refs[key]
1942
 
        except KeyError:
1943
 
            # No keys depended on this key.  That's ok.
1944
 
            pass
1945
 
 
1946
 
    def add_key(self, key):
1947
 
        # satisfy refs for key, and remember that we've seen this key.
1948
 
        self._satisfy_refs_for_key(key)
1949
 
        if self.new_keys is not None:
1950
 
            self.new_keys.add(key)
1951
 
 
1952
 
    def satisfy_refs_for_keys(self, keys):
1953
 
        for key in keys:
1954
 
            self._satisfy_refs_for_key(key)
1955
 
 
1956
 
    def get_referrers(self):
1957
 
        result = set()
1958
 
        for referrers in self.refs.itervalues():
1959
 
            result.update(referrers)
1960
 
        return result
1961
 
 
1962
 
 
1963
 
 
 
698
class InterVersionedFile(InterObject):
 
699
    """This class represents operations taking place between two VersionedFiles.
 
700
 
 
701
    Its instances have methods like join, and contain
 
702
    references to the source and target versionedfiles these operations can be 
 
703
    carried out on.
 
704
 
 
705
    Often we will provide convenience methods on 'versionedfile' which carry out
 
706
    operations with another versionedfile - they will always forward to
 
707
    InterVersionedFile.get(other).method_name(parameters).
 
708
    """
 
709
 
 
710
    _optimisers = []
 
711
    """The available optimised InterVersionedFile types."""
 
712
 
 
713
    def join(self, pb=None, msg=None, version_ids=None, ignore_missing=False):
 
714
        """Integrate versions from self.source into self.target.
 
715
 
 
716
        If version_ids is None all versions from source should be
 
717
        incorporated into this versioned file.
 
718
 
 
719
        Must raise RevisionNotPresent if any of the specified versions
 
720
        are not present in the other file's history unless ignore_missing is 
 
721
        supplied in which case they are silently skipped.
 
722
        """
 
723
        # the default join: 
 
724
        # - if the target is empty, just add all the versions from 
 
725
        #   source to target, otherwise:
 
726
        # - make a temporary versioned file of type target
 
727
        # - insert the source content into it one at a time
 
728
        # - join them
 
729
        if not self.target.versions():
 
730
            target = self.target
 
731
        else:
 
732
            # Make a new target-format versioned file. 
 
733
            temp_source = self.target.create_empty("temp", MemoryTransport())
 
734
            target = temp_source
 
735
        version_ids = self._get_source_version_ids(version_ids, ignore_missing)
 
736
        graph = self.source.get_graph(version_ids)
 
737
        order = tsort.topo_sort(graph.items())
 
738
        pb = ui.ui_factory.nested_progress_bar()
 
739
        parent_texts = {}
 
740
        try:
 
741
            # TODO for incremental cross-format work:
 
742
            # make a versioned file with the following content:
 
743
            # all revisions we have been asked to join
 
744
            # all their ancestors that are *not* in target already.
 
745
            # the immediate parents of the above two sets, with 
 
746
            # empty parent lists - these versions are in target already
 
747
            # and the incorrect version data will be ignored.
 
748
            # TODO: for all ancestors that are present in target already,
 
749
            # check them for consistent data, this requires moving sha1 from
 
750
            # 
 
751
            # TODO: remove parent texts when they are not relevant any more for 
 
752
            # memory pressure reduction. RBC 20060313
 
753
            # pb.update('Converting versioned data', 0, len(order))
 
754
            total = len(order)
 
755
            for index, version in enumerate(order):
 
756
                pb.update('Converting versioned data', index, total)
 
757
                _, _, parent_text = target.add_lines(version,
 
758
                                               self.source.get_parents(version),
 
759
                                               self.source.get_lines(version),
 
760
                                               parent_texts=parent_texts)
 
761
                parent_texts[version] = parent_text
 
762
            
 
763
            # this should hit the native code path for target
 
764
            if target is not self.target:
 
765
                return self.target.join(temp_source,
 
766
                                        pb,
 
767
                                        msg,
 
768
                                        version_ids,
 
769
                                        ignore_missing)
 
770
            else:
 
771
                return total
 
772
        finally:
 
773
            pb.finished()
 
774
 
 
775
    def _get_source_version_ids(self, version_ids, ignore_missing):
 
776
        """Determine the version ids to be used from self.source.
 
777
 
 
778
        :param version_ids: The caller-supplied version ids to check. (None 
 
779
                            for all). If None is in version_ids, it is stripped.
 
780
        :param ignore_missing: if True, remove missing ids from the version 
 
781
                               list. If False, raise RevisionNotPresent on
 
782
                               a missing version id.
 
783
        :return: A set of version ids.
 
784
        """
 
785
        if version_ids is None:
 
786
            # None cannot be in source.versions
 
787
            return set(self.source.versions())
 
788
        else:
 
789
            if ignore_missing:
 
790
                return set(self.source.versions()).intersection(set(version_ids))
 
791
            else:
 
792
                new_version_ids = set()
 
793
                for version in version_ids:
 
794
                    if version is None:
 
795
                        continue
 
796
                    if not self.source.has_version(version):
 
797
                        raise errors.RevisionNotPresent(version, str(self.source))
 
798
                    else:
 
799
                        new_version_ids.add(version)
 
800
                return new_version_ids