/brz/remove-bazaar

To get this branch, use:
bzr branch http://gegoxaren.bato24.eu/bzr/brz/remove-bazaar

« back to all changes in this revision

Viewing changes to bzrlib/versionedfile.py

  • Committer: Robert Collins
  • Date: 2008-05-12 01:23:41 UTC
  • mto: (3350.4.4 remove-deprecations)
  • mto: This revision was merged to the branch mainline in revision 3424.
  • Revision ID: robertc@robertcollins.net-20080512012341-vzjmv73r8b96eumr
Review feedback.

Show diffs side-by-side

added added

removed removed

Lines of Context:
 
1
# Copyright (C) 2005, 2006 Canonical Ltd
 
2
#
 
3
# Authors:
 
4
#   Johan Rydberg <jrydberg@gnu.org>
 
5
#
 
6
# This program is free software; you can redistribute it and/or modify
 
7
# it under the terms of the GNU General Public License as published by
 
8
# the Free Software Foundation; either version 2 of the License, or
 
9
# (at your option) any later version.
 
10
#
 
11
# This program is distributed in the hope that it will be useful,
 
12
# but WITHOUT ANY WARRANTY; without even the implied warranty of
 
13
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 
14
# GNU General Public License for more details.
 
15
#
 
16
# You should have received a copy of the GNU General Public License
 
17
# along with this program; if not, write to the Free Software
 
18
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 
19
 
 
20
"""Versioned text file storage api."""
 
21
 
 
22
from bzrlib.lazy_import import lazy_import
 
23
lazy_import(globals(), """
 
24
 
 
25
from bzrlib import (
 
26
    errors,
 
27
    osutils,
 
28
    multiparent,
 
29
    tsort,
 
30
    revision,
 
31
    ui,
 
32
    )
 
33
from bzrlib.graph import Graph
 
34
from bzrlib.transport.memory import MemoryTransport
 
35
""")
 
36
 
 
37
from cStringIO import StringIO
 
38
 
 
39
from bzrlib.inter import InterObject
 
40
from bzrlib.registry import Registry
 
41
from bzrlib.symbol_versioning import *
 
42
from bzrlib.textmerge import TextMerge
 
43
 
 
44
 
 
45
adapter_registry = Registry()
 
46
adapter_registry.register_lazy(('knit-delta-gz', 'fulltext'), 'bzrlib.knit',
 
47
    'DeltaPlainToFullText')
 
48
adapter_registry.register_lazy(('knit-ft-gz', 'fulltext'), 'bzrlib.knit',
 
49
    'FTPlainToFullText')
 
50
adapter_registry.register_lazy(('knit-annotated-delta-gz', 'knit-delta-gz'),
 
51
    'bzrlib.knit', 'DeltaAnnotatedToUnannotated')
 
52
adapter_registry.register_lazy(('knit-annotated-delta-gz', 'fulltext'),
 
53
    'bzrlib.knit', 'DeltaAnnotatedToFullText')
 
54
adapter_registry.register_lazy(('knit-annotated-ft-gz', 'knit-ft-gz'),
 
55
    'bzrlib.knit', 'FTAnnotatedToUnannotated')
 
56
adapter_registry.register_lazy(('knit-annotated-ft-gz', 'fulltext'),
 
57
    'bzrlib.knit', 'FTAnnotatedToFullText')
 
58
 
 
59
 
 
60
class ContentFactory(object):
 
61
    """Abstract interface for insertion and retrieval from a VersionedFile.
 
62
    
 
63
    :ivar sha1: None, or the sha1 of the content fulltext.
 
64
    :ivar storage_kind: The native storage kind of this factory. One of
 
65
        'mpdiff', 'knit-annotated-ft', 'knit-annotated-delta', 'knit-ft',
 
66
        'knit-delta', 'fulltext', 'knit-annotated-ft-gz',
 
67
        'knit-annotated-delta-gz', 'knit-ft-gz', 'knit-delta-gz'.
 
68
    :ivar key: The key of this content. Each key is a tuple with a single
 
69
        string in it.
 
70
    :ivar parents: A tuple of parent keys for self.key. If the object has
 
71
        no parent information, None (as opposed to () for an empty list of
 
72
        parents).
 
73
        """
 
74
 
 
75
    def __init__(self):
 
76
        """Create a ContentFactory."""
 
77
        self.sha1 = None
 
78
        self.storage_kind = None
 
79
        self.key = None
 
80
        self.parents = None
 
81
 
 
82
 
 
83
class AbsentContentFactory(object):
 
84
    """A placeholder content factory for unavailable texts.
 
85
    
 
86
    :ivar sha1: None.
 
87
    :ivar storage_kind: 'absent'.
 
88
    :ivar key: The key of this content. Each key is a tuple with a single
 
89
        string in it.
 
90
    :ivar parents: None.
 
91
    """
 
92
 
 
93
    def __init__(self, key):
 
94
        """Create a ContentFactory."""
 
95
        self.sha1 = None
 
96
        self.storage_kind = 'absent'
 
97
        self.key = key
 
98
        self.parents = None
 
99
 
 
100
 
 
101
def filter_absent(record_stream):
 
102
    """Adapt a record stream to remove absent records."""
 
103
    for record in record_stream:
 
104
        if record.storage_kind != 'absent':
 
105
            yield record
 
106
 
 
107
 
 
108
class VersionedFile(object):
 
109
    """Versioned text file storage.
 
110
    
 
111
    A versioned file manages versions of line-based text files,
 
112
    keeping track of the originating version for each line.
 
113
 
 
114
    To clients the "lines" of the file are represented as a list of
 
115
    strings. These strings will typically have terminal newline
 
116
    characters, but this is not required.  In particular files commonly
 
117
    do not have a newline at the end of the file.
 
118
 
 
119
    Texts are identified by a version-id string.
 
120
    """
 
121
 
 
122
    @staticmethod
 
123
    def check_not_reserved_id(version_id):
 
124
        revision.check_not_reserved_id(version_id)
 
125
 
 
126
    def copy_to(self, name, transport):
 
127
        """Copy this versioned file to name on transport."""
 
128
        raise NotImplementedError(self.copy_to)
 
129
 
 
130
    def get_record_stream(self, versions, ordering, include_delta_closure):
 
131
        """Get a stream of records for versions.
 
132
 
 
133
        :param versions: The versions to include. Each version is a tuple
 
134
            (version,).
 
135
        :param ordering: Either 'unordered' or 'topological'. A topologically
 
136
            sorted stream has compression parents strictly before their
 
137
            children.
 
138
        :param include_delta_closure: If True then the closure across any
 
139
            compression parents will be included (in the data content of the
 
140
            stream, not in the emitted records). This guarantees that
 
141
            'fulltext' can be used successfully on every record.
 
142
        :return: An iterator of ContentFactory objects, each of which is only
 
143
            valid until the iterator is advanced.
 
144
        """
 
145
        raise NotImplementedError(self.get_record_stream)
 
146
 
 
147
    @deprecated_method(one_four)
 
148
    def has_ghost(self, version_id):
 
149
        """Returns whether version is present as a ghost."""
 
150
        raise NotImplementedError(self.has_ghost)
 
151
 
 
152
    def has_version(self, version_id):
 
153
        """Returns whether version is present."""
 
154
        raise NotImplementedError(self.has_version)
 
155
 
 
156
    def insert_record_stream(self, stream):
 
157
        """Insert a record stream into this versioned file.
 
158
 
 
159
        :param stream: A stream of records to insert. 
 
160
        :return: None
 
161
        :seealso VersionedFile.get_record_stream:
 
162
        """
 
163
        raise NotImplementedError
 
164
 
 
165
    def add_lines(self, version_id, parents, lines, parent_texts=None,
 
166
        left_matching_blocks=None, nostore_sha=None, random_id=False,
 
167
        check_content=True):
 
168
        """Add a single text on top of the versioned file.
 
169
 
 
170
        Must raise RevisionAlreadyPresent if the new version is
 
171
        already present in file history.
 
172
 
 
173
        Must raise RevisionNotPresent if any of the given parents are
 
174
        not present in file history.
 
175
 
 
176
        :param lines: A list of lines. Each line must be a bytestring. And all
 
177
            of them except the last must be terminated with \n and contain no
 
178
            other \n's. The last line may either contain no \n's or a single
 
179
            terminated \n. If the lines list does meet this constraint the add
 
180
            routine may error or may succeed - but you will be unable to read
 
181
            the data back accurately. (Checking the lines have been split
 
182
            correctly is expensive and extremely unlikely to catch bugs so it
 
183
            is not done at runtime unless check_content is True.)
 
184
        :param parent_texts: An optional dictionary containing the opaque 
 
185
            representations of some or all of the parents of version_id to
 
186
            allow delta optimisations.  VERY IMPORTANT: the texts must be those
 
187
            returned by add_lines or data corruption can be caused.
 
188
        :param left_matching_blocks: a hint about which areas are common
 
189
            between the text and its left-hand-parent.  The format is
 
190
            the SequenceMatcher.get_matching_blocks format.
 
191
        :param nostore_sha: Raise ExistingContent and do not add the lines to
 
192
            the versioned file if the digest of the lines matches this.
 
193
        :param random_id: If True a random id has been selected rather than
 
194
            an id determined by some deterministic process such as a converter
 
195
            from a foreign VCS. When True the backend may choose not to check
 
196
            for uniqueness of the resulting key within the versioned file, so
 
197
            this should only be done when the result is expected to be unique
 
198
            anyway.
 
199
        :param check_content: If True, the lines supplied are verified to be
 
200
            bytestrings that are correctly formed lines.
 
201
        :return: The text sha1, the number of bytes in the text, and an opaque
 
202
                 representation of the inserted version which can be provided
 
203
                 back to future add_lines calls in the parent_texts dictionary.
 
204
        """
 
205
        self._check_write_ok()
 
206
        return self._add_lines(version_id, parents, lines, parent_texts,
 
207
            left_matching_blocks, nostore_sha, random_id, check_content)
 
208
 
 
209
    def _add_lines(self, version_id, parents, lines, parent_texts,
 
210
        left_matching_blocks, nostore_sha, random_id, check_content):
 
211
        """Helper to do the class specific add_lines."""
 
212
        raise NotImplementedError(self.add_lines)
 
213
 
 
214
    def add_lines_with_ghosts(self, version_id, parents, lines,
 
215
        parent_texts=None, nostore_sha=None, random_id=False,
 
216
        check_content=True, left_matching_blocks=None):
 
217
        """Add lines to the versioned file, allowing ghosts to be present.
 
218
        
 
219
        This takes the same parameters as add_lines and returns the same.
 
220
        """
 
221
        self._check_write_ok()
 
222
        return self._add_lines_with_ghosts(version_id, parents, lines,
 
223
            parent_texts, nostore_sha, random_id, check_content, left_matching_blocks)
 
224
 
 
225
    def _add_lines_with_ghosts(self, version_id, parents, lines, parent_texts,
 
226
        nostore_sha, random_id, check_content, left_matching_blocks):
 
227
        """Helper to do class specific add_lines_with_ghosts."""
 
228
        raise NotImplementedError(self.add_lines_with_ghosts)
 
229
 
 
230
    def check(self, progress_bar=None):
 
231
        """Check the versioned file for integrity."""
 
232
        raise NotImplementedError(self.check)
 
233
 
 
234
    def _check_lines_not_unicode(self, lines):
 
235
        """Check that lines being added to a versioned file are not unicode."""
 
236
        for line in lines:
 
237
            if line.__class__ is not str:
 
238
                raise errors.BzrBadParameterUnicode("lines")
 
239
 
 
240
    def _check_lines_are_lines(self, lines):
 
241
        """Check that the lines really are full lines without inline EOL."""
 
242
        for line in lines:
 
243
            if '\n' in line[:-1]:
 
244
                raise errors.BzrBadParameterContainsNewline("lines")
 
245
 
 
246
    @deprecated_method(one_four)
 
247
    def enable_cache(self):
 
248
        """Tell this versioned file that it should cache any data it reads.
 
249
        
 
250
        This is advisory, implementations do not have to support caching.
 
251
        """
 
252
        pass
 
253
    
 
254
    @deprecated_method(one_four)
 
255
    def clear_cache(self):
 
256
        """Remove any data cached in the versioned file object.
 
257
 
 
258
        This only needs to be supported if caches are supported
 
259
        """
 
260
        pass
 
261
 
 
262
    @deprecated_method(one_four)
 
263
    def clone_text(self, new_version_id, old_version_id, parents):
 
264
        """Add an identical text to old_version_id as new_version_id.
 
265
 
 
266
        Must raise RevisionNotPresent if the old version or any of the
 
267
        parents are not present in file history.
 
268
 
 
269
        Must raise RevisionAlreadyPresent if the new version is
 
270
        already present in file history."""
 
271
        self._check_write_ok()
 
272
        return self.add_lines(new_version_id, parents,
 
273
            self.get_lines(old_version_id))
 
274
 
 
275
    def get_format_signature(self):
 
276
        """Get a text description of the data encoding in this file.
 
277
        
 
278
        :since: 0.90
 
279
        """
 
280
        raise NotImplementedError(self.get_format_signature)
 
281
 
 
282
    def make_mpdiffs(self, version_ids):
 
283
        """Create multiparent diffs for specified versions."""
 
284
        knit_versions = set()
 
285
        knit_versions.update(version_ids)
 
286
        parent_map = self.get_parent_map(version_ids)
 
287
        for version_id in version_ids:
 
288
            try:
 
289
                knit_versions.update(parent_map[version_id])
 
290
            except KeyError:
 
291
                raise RevisionNotPresent(version_id, self)
 
292
        # We need to filter out ghosts, because we can't diff against them.
 
293
        knit_versions = set(self.get_parent_map(knit_versions).keys())
 
294
        lines = dict(zip(knit_versions,
 
295
            self._get_lf_split_line_list(knit_versions)))
 
296
        diffs = []
 
297
        for version_id in version_ids:
 
298
            target = lines[version_id]
 
299
            try:
 
300
                parents = [lines[p] for p in parent_map[version_id] if p in
 
301
                    knit_versions]
 
302
            except KeyError:
 
303
                raise RevisionNotPresent(version_id, self)
 
304
            if len(parents) > 0:
 
305
                left_parent_blocks = self._extract_blocks(version_id,
 
306
                                                          parents[0], target)
 
307
            else:
 
308
                left_parent_blocks = None
 
309
            diffs.append(multiparent.MultiParent.from_lines(target, parents,
 
310
                         left_parent_blocks))
 
311
        return diffs
 
312
 
 
313
    def _extract_blocks(self, version_id, source, target):
 
314
        return None
 
315
 
 
316
    def add_mpdiffs(self, records):
 
317
        """Add mpdiffs to this VersionedFile.
 
318
 
 
319
        Records should be iterables of version, parents, expected_sha1,
 
320
        mpdiff. mpdiff should be a MultiParent instance.
 
321
        """
 
322
        # Does this need to call self._check_write_ok()? (IanC 20070919)
 
323
        vf_parents = {}
 
324
        mpvf = multiparent.MultiMemoryVersionedFile()
 
325
        versions = []
 
326
        for version, parent_ids, expected_sha1, mpdiff in records:
 
327
            versions.append(version)
 
328
            mpvf.add_diff(mpdiff, version, parent_ids)
 
329
        needed_parents = set()
 
330
        for version, parent_ids, expected_sha1, mpdiff in records:
 
331
            needed_parents.update(p for p in parent_ids
 
332
                                  if not mpvf.has_version(p))
 
333
        present_parents = set(self.get_parent_map(needed_parents).keys())
 
334
        for parent_id, lines in zip(present_parents,
 
335
                                 self._get_lf_split_line_list(present_parents)):
 
336
            mpvf.add_version(lines, parent_id, [])
 
337
        for (version, parent_ids, expected_sha1, mpdiff), lines in\
 
338
            zip(records, mpvf.get_line_list(versions)):
 
339
            if len(parent_ids) == 1:
 
340
                left_matching_blocks = list(mpdiff.get_matching_blocks(0,
 
341
                    mpvf.get_diff(parent_ids[0]).num_lines()))
 
342
            else:
 
343
                left_matching_blocks = None
 
344
            try:
 
345
                _, _, version_text = self.add_lines_with_ghosts(version,
 
346
                    parent_ids, lines, vf_parents,
 
347
                    left_matching_blocks=left_matching_blocks)
 
348
            except NotImplementedError:
 
349
                # The vf can't handle ghosts, so add lines normally, which will
 
350
                # (reasonably) fail if there are ghosts in the data.
 
351
                _, _, version_text = self.add_lines(version,
 
352
                    parent_ids, lines, vf_parents,
 
353
                    left_matching_blocks=left_matching_blocks)
 
354
            vf_parents[version] = version_text
 
355
        for (version, parent_ids, expected_sha1, mpdiff), sha1 in\
 
356
             zip(records, self.get_sha1s(versions)):
 
357
            if expected_sha1 != sha1:
 
358
                raise errors.VersionedFileInvalidChecksum(version)
 
359
 
 
360
    @deprecated_method(one_four)
 
361
    def get_sha1(self, version_id):
 
362
        """Get the stored sha1 sum for the given revision.
 
363
        
 
364
        :param version_id: The name of the version to lookup
 
365
        """
 
366
        return self.get_sha1s([version_id])[0]
 
367
 
 
368
    def get_sha1s(self, version_ids):
 
369
        """Get the stored sha1 sums for the given revisions.
 
370
 
 
371
        :param version_ids: The names of the versions to lookup
 
372
        :return: a list of sha1s in order according to the version_ids
 
373
        """
 
374
        raise NotImplementedError(self.get_sha1s)
 
375
 
 
376
    def get_text(self, version_id):
 
377
        """Return version contents as a text string.
 
378
 
 
379
        Raises RevisionNotPresent if version is not present in
 
380
        file history.
 
381
        """
 
382
        return ''.join(self.get_lines(version_id))
 
383
    get_string = get_text
 
384
 
 
385
    def get_texts(self, version_ids):
 
386
        """Return the texts of listed versions as a list of strings.
 
387
 
 
388
        Raises RevisionNotPresent if version is not present in
 
389
        file history.
 
390
        """
 
391
        return [''.join(self.get_lines(v)) for v in version_ids]
 
392
 
 
393
    def get_lines(self, version_id):
 
394
        """Return version contents as a sequence of lines.
 
395
 
 
396
        Raises RevisionNotPresent if version is not present in
 
397
        file history.
 
398
        """
 
399
        raise NotImplementedError(self.get_lines)
 
400
 
 
401
    def _get_lf_split_line_list(self, version_ids):
 
402
        return [StringIO(t).readlines() for t in self.get_texts(version_ids)]
 
403
 
 
404
    def get_ancestry(self, version_ids, topo_sorted=True):
 
405
        """Return a list of all ancestors of given version(s). This
 
406
        will not include the null revision.
 
407
 
 
408
        This list will not be topologically sorted if topo_sorted=False is
 
409
        passed.
 
410
 
 
411
        Must raise RevisionNotPresent if any of the given versions are
 
412
        not present in file history."""
 
413
        if isinstance(version_ids, basestring):
 
414
            version_ids = [version_ids]
 
415
        raise NotImplementedError(self.get_ancestry)
 
416
        
 
417
    def get_ancestry_with_ghosts(self, version_ids):
 
418
        """Return a list of all ancestors of given version(s). This
 
419
        will not include the null revision.
 
420
 
 
421
        Must raise RevisionNotPresent if any of the given versions are
 
422
        not present in file history.
 
423
        
 
424
        Ghosts that are known about will be included in ancestry list,
 
425
        but are not explicitly marked.
 
426
        """
 
427
        raise NotImplementedError(self.get_ancestry_with_ghosts)
 
428
    
 
429
    @deprecated_method(one_four)
 
430
    def get_graph(self, version_ids=None):
 
431
        """Return a graph from the versioned file. 
 
432
        
 
433
        Ghosts are not listed or referenced in the graph.
 
434
        :param version_ids: Versions to select.
 
435
                            None means retrieve all versions.
 
436
        """
 
437
        if version_ids is None:
 
438
            result = self.get_parent_map(self.versions())
 
439
        else:
 
440
            result = {}
 
441
            pending = set(version_ids)
 
442
            while pending:
 
443
                this_iteration = pending
 
444
                pending = set()
 
445
                parents = self.get_parent_map(this_iteration)
 
446
                for version, parents in parents.iteritems():
 
447
                    result[version] = parents
 
448
                    for parent in parents:
 
449
                        if parent in result:
 
450
                            continue
 
451
                        pending.add(parent)
 
452
        references = set()
 
453
        for parents in result.itervalues():
 
454
            references.update(parents)
 
455
        existing_parents = self.get_parent_map(references)
 
456
        for key, parents in result.iteritems():
 
457
            present_parents = [parent for parent in parents if parent in
 
458
                existing_parents]
 
459
            result[key] = tuple(present_parents)
 
460
        return result
 
461
 
 
462
    @deprecated_method(one_four)
 
463
    def get_graph_with_ghosts(self):
 
464
        """Return a graph for the entire versioned file.
 
465
        
 
466
        Ghosts are referenced in parents list but are not
 
467
        explicitly listed.
 
468
        """
 
469
        raise NotImplementedError(self.get_graph_with_ghosts)
 
470
 
 
471
    def get_parent_map(self, version_ids):
 
472
        """Get a map of the parents of version_ids.
 
473
 
 
474
        :param version_ids: The version ids to look up parents for.
 
475
        :return: A mapping from version id to parents.
 
476
        """
 
477
        raise NotImplementedError(self.get_parent_map)
 
478
 
 
479
    @deprecated_method(one_four)
 
480
    def get_parents(self, version_id):
 
481
        """Return version names for parents of a version.
 
482
 
 
483
        Must raise RevisionNotPresent if version is not present in
 
484
        file history.
 
485
        """
 
486
        try:
 
487
            all = self.get_parent_map([version_id])[version_id]
 
488
        except KeyError:
 
489
            raise errors.RevisionNotPresent(version_id, self)
 
490
        result = []
 
491
        parent_parents = self.get_parent_map(all)
 
492
        for version_id in all:
 
493
            if version_id in parent_parents:
 
494
                result.append(version_id)
 
495
        return result
 
496
 
 
497
    def get_parents_with_ghosts(self, version_id):
 
498
        """Return version names for parents of version_id.
 
499
 
 
500
        Will raise RevisionNotPresent if version_id is not present
 
501
        in the history.
 
502
 
 
503
        Ghosts that are known about will be included in the parent list,
 
504
        but are not explicitly marked.
 
505
        """
 
506
        try:
 
507
            return list(self.get_parent_map([version_id])[version_id])
 
508
        except KeyError:
 
509
            raise errors.RevisionNotPresent(version_id, self)
 
510
 
 
511
    @deprecated_method(one_four)
 
512
    def annotate_iter(self, version_id):
 
513
        """Yield list of (version-id, line) pairs for the specified
 
514
        version.
 
515
 
 
516
        Must raise RevisionNotPresent if the given version is
 
517
        not present in file history.
 
518
        """
 
519
        return iter(self.annotate(version_id))
 
520
 
 
521
    def annotate(self, version_id):
 
522
        """Return a list of (version-id, line) tuples for version_id.
 
523
 
 
524
        :raise RevisionNotPresent: If the given version is
 
525
        not present in file history.
 
526
        """
 
527
        raise NotImplementedError(self.annotate)
 
528
 
 
529
    @deprecated_method(one_five)
 
530
    def join(self, other, pb=None, msg=None, version_ids=None,
 
531
             ignore_missing=False):
 
532
        """Integrate versions from other into this versioned file.
 
533
 
 
534
        If version_ids is None all versions from other should be
 
535
        incorporated into this versioned file.
 
536
 
 
537
        Must raise RevisionNotPresent if any of the specified versions
 
538
        are not present in the other file's history unless ignore_missing
 
539
        is supplied in which case they are silently skipped.
 
540
        """
 
541
        self._check_write_ok()
 
542
        return InterVersionedFile.get(other, self).join(
 
543
            pb,
 
544
            msg,
 
545
            version_ids,
 
546
            ignore_missing)
 
547
 
 
548
    def iter_lines_added_or_present_in_versions(self, version_ids=None,
 
549
                                                pb=None):
 
550
        """Iterate over the lines in the versioned file from version_ids.
 
551
 
 
552
        This may return lines from other versions. Each item the returned
 
553
        iterator yields is a tuple of a line and a text version that that line
 
554
        is present in (not introduced in).
 
555
 
 
556
        Ordering of results is in whatever order is most suitable for the
 
557
        underlying storage format.
 
558
 
 
559
        If a progress bar is supplied, it may be used to indicate progress.
 
560
        The caller is responsible for cleaning up progress bars (because this
 
561
        is an iterator).
 
562
 
 
563
        NOTES: Lines are normalised: they will all have \n terminators.
 
564
               Lines are returned in arbitrary order.
 
565
 
 
566
        :return: An iterator over (line, version_id).
 
567
        """
 
568
        raise NotImplementedError(self.iter_lines_added_or_present_in_versions)
 
569
 
 
570
    @deprecated_method(one_four)
 
571
    def iter_parents(self, version_ids):
 
572
        """Iterate through the parents for many version ids.
 
573
 
 
574
        :param version_ids: An iterable yielding version_ids.
 
575
        :return: An iterator that yields (version_id, parents). Requested 
 
576
            version_ids not present in the versioned file are simply skipped.
 
577
            The order is undefined, allowing for different optimisations in
 
578
            the underlying implementation.
 
579
        """
 
580
        return self.get_parent_map(version_ids).iteritems()
 
581
 
 
582
    def plan_merge(self, ver_a, ver_b):
 
583
        """Return pseudo-annotation indicating how the two versions merge.
 
584
 
 
585
        This is computed between versions a and b and their common
 
586
        base.
 
587
 
 
588
        Weave lines present in none of them are skipped entirely.
 
589
 
 
590
        Legend:
 
591
        killed-base Dead in base revision
 
592
        killed-both Killed in each revision
 
593
        killed-a    Killed in a
 
594
        killed-b    Killed in b
 
595
        unchanged   Alive in both a and b (possibly created in both)
 
596
        new-a       Created in a
 
597
        new-b       Created in b
 
598
        ghost-a     Killed in a, unborn in b    
 
599
        ghost-b     Killed in b, unborn in a
 
600
        irrelevant  Not in either revision
 
601
        """
 
602
        raise NotImplementedError(VersionedFile.plan_merge)
 
603
        
 
604
    def weave_merge(self, plan, a_marker=TextMerge.A_MARKER,
 
605
                    b_marker=TextMerge.B_MARKER):
 
606
        return PlanWeaveMerge(plan, a_marker, b_marker).merge_lines()[0]
 
607
 
 
608
 
 
609
class RecordingVersionedFileDecorator(object):
 
610
    """A minimal versioned file that records calls made on it.
 
611
    
 
612
    Only enough methods have been added to support tests using it to date.
 
613
 
 
614
    :ivar calls: A list of the calls made; can be reset at any time by
 
615
        assigning [] to it.
 
616
    """
 
617
 
 
618
    def __init__(self, backing_vf):
 
619
        """Create a RecordingVersionedFileDecorator decorating backing_vf.
 
620
        
 
621
        :param backing_vf: The versioned file to answer all methods.
 
622
        """
 
623
        self._backing_vf = backing_vf
 
624
        self.calls = []
 
625
 
 
626
    def get_lines(self, version_ids):
 
627
        self.calls.append(("get_lines", version_ids))
 
628
        return self._backing_vf.get_lines(version_ids)
 
629
 
 
630
 
 
631
class _PlanMergeVersionedFile(object):
 
632
    """A VersionedFile for uncommitted and committed texts.
 
633
 
 
634
    It is intended to allow merges to be planned with working tree texts.
 
635
    It implements only the small part of the VersionedFile interface used by
 
636
    PlanMerge.  It falls back to multiple versionedfiles for data not stored in
 
637
    _PlanMergeVersionedFile itself.
 
638
    """
 
639
 
 
640
    def __init__(self, file_id, fallback_versionedfiles=None):
 
641
        """Constuctor
 
642
 
 
643
        :param file_id: Used when raising exceptions.
 
644
        :param fallback_versionedfiles: If supplied, the set of fallbacks to
 
645
            use.  Otherwise, _PlanMergeVersionedFile.fallback_versionedfiles
 
646
            can be appended to later.
 
647
        """
 
648
        self._file_id = file_id
 
649
        if fallback_versionedfiles is None:
 
650
            self.fallback_versionedfiles = []
 
651
        else:
 
652
            self.fallback_versionedfiles = fallback_versionedfiles
 
653
        self._parents = {}
 
654
        self._lines = {}
 
655
 
 
656
    def plan_merge(self, ver_a, ver_b, base=None):
 
657
        """See VersionedFile.plan_merge"""
 
658
        from bzrlib.merge import _PlanMerge
 
659
        if base is None:
 
660
            return _PlanMerge(ver_a, ver_b, self).plan_merge()
 
661
        old_plan = list(_PlanMerge(ver_a, base, self).plan_merge())
 
662
        new_plan = list(_PlanMerge(ver_a, ver_b, self).plan_merge())
 
663
        return _PlanMerge._subtract_plans(old_plan, new_plan)
 
664
 
 
665
    def plan_lca_merge(self, ver_a, ver_b, base=None):
 
666
        from bzrlib.merge import _PlanLCAMerge
 
667
        graph = self._get_graph()
 
668
        new_plan = _PlanLCAMerge(ver_a, ver_b, self, graph).plan_merge()
 
669
        if base is None:
 
670
            return new_plan
 
671
        old_plan = _PlanLCAMerge(ver_a, base, self, graph).plan_merge()
 
672
        return _PlanLCAMerge._subtract_plans(list(old_plan), list(new_plan))
 
673
 
 
674
    def add_lines(self, version_id, parents, lines):
 
675
        """See VersionedFile.add_lines
 
676
 
 
677
        Lines are added locally, not fallback versionedfiles.  Also, ghosts are
 
678
        permitted.  Only reserved ids are permitted.
 
679
        """
 
680
        if not revision.is_reserved_id(version_id):
 
681
            raise ValueError('Only reserved ids may be used')
 
682
        if parents is None:
 
683
            raise ValueError('Parents may not be None')
 
684
        if lines is None:
 
685
            raise ValueError('Lines may not be None')
 
686
        self._parents[version_id] = tuple(parents)
 
687
        self._lines[version_id] = lines
 
688
 
 
689
    def get_lines(self, version_id):
 
690
        """See VersionedFile.get_ancestry"""
 
691
        lines = self._lines.get(version_id)
 
692
        if lines is not None:
 
693
            return lines
 
694
        for versionedfile in self.fallback_versionedfiles:
 
695
            try:
 
696
                return versionedfile.get_lines(version_id)
 
697
            except errors.RevisionNotPresent:
 
698
                continue
 
699
        else:
 
700
            raise errors.RevisionNotPresent(version_id, self._file_id)
 
701
 
 
702
    def get_ancestry(self, version_id, topo_sorted=False):
 
703
        """See VersionedFile.get_ancestry.
 
704
 
 
705
        Note that this implementation assumes that if a VersionedFile can
 
706
        answer get_ancestry at all, it can give an authoritative answer.  In
 
707
        fact, ghosts can invalidate this assumption.  But it's good enough
 
708
        99% of the time, and far cheaper/simpler.
 
709
 
 
710
        Also note that the results of this version are never topologically
 
711
        sorted, and are a set.
 
712
        """
 
713
        if topo_sorted:
 
714
            raise ValueError('This implementation does not provide sorting')
 
715
        parents = self._parents.get(version_id)
 
716
        if parents is None:
 
717
            for vf in self.fallback_versionedfiles:
 
718
                try:
 
719
                    return vf.get_ancestry(version_id, topo_sorted=False)
 
720
                except errors.RevisionNotPresent:
 
721
                    continue
 
722
            else:
 
723
                raise errors.RevisionNotPresent(version_id, self._file_id)
 
724
        ancestry = set([version_id])
 
725
        for parent in parents:
 
726
            ancestry.update(self.get_ancestry(parent, topo_sorted=False))
 
727
        return ancestry
 
728
 
 
729
    def get_parent_map(self, version_ids):
 
730
        """See VersionedFile.get_parent_map"""
 
731
        result = {}
 
732
        pending = set(version_ids)
 
733
        for key in version_ids:
 
734
            try:
 
735
                result[key] = self._parents[key]
 
736
            except KeyError:
 
737
                pass
 
738
        pending = pending - set(result.keys())
 
739
        for versionedfile in self.fallback_versionedfiles:
 
740
            parents = versionedfile.get_parent_map(pending)
 
741
            result.update(parents)
 
742
            pending = pending - set(parents.keys())
 
743
            if not pending:
 
744
                return result
 
745
        return result
 
746
 
 
747
    def _get_graph(self):
 
748
        from bzrlib.graph import (
 
749
            DictParentsProvider,
 
750
            Graph,
 
751
            _StackedParentsProvider,
 
752
            )
 
753
        from bzrlib.repofmt.knitrepo import _KnitParentsProvider
 
754
        parent_providers = [DictParentsProvider(self._parents)]
 
755
        for vf in self.fallback_versionedfiles:
 
756
            parent_providers.append(_KnitParentsProvider(vf))
 
757
        return Graph(_StackedParentsProvider(parent_providers))
 
758
 
 
759
 
 
760
class PlanWeaveMerge(TextMerge):
 
761
    """Weave merge that takes a plan as its input.
 
762
    
 
763
    This exists so that VersionedFile.plan_merge is implementable.
 
764
    Most callers will want to use WeaveMerge instead.
 
765
    """
 
766
 
 
767
    def __init__(self, plan, a_marker=TextMerge.A_MARKER,
 
768
                 b_marker=TextMerge.B_MARKER):
 
769
        TextMerge.__init__(self, a_marker, b_marker)
 
770
        self.plan = plan
 
771
 
 
772
    def _merge_struct(self):
 
773
        lines_a = []
 
774
        lines_b = []
 
775
        ch_a = ch_b = False
 
776
 
 
777
        def outstanding_struct():
 
778
            if not lines_a and not lines_b:
 
779
                return
 
780
            elif ch_a and not ch_b:
 
781
                # one-sided change:
 
782
                yield(lines_a,)
 
783
            elif ch_b and not ch_a:
 
784
                yield (lines_b,)
 
785
            elif lines_a == lines_b:
 
786
                yield(lines_a,)
 
787
            else:
 
788
                yield (lines_a, lines_b)
 
789
       
 
790
        # We previously considered either 'unchanged' or 'killed-both' lines
 
791
        # to be possible places to resynchronize.  However, assuming agreement
 
792
        # on killed-both lines may be too aggressive. -- mbp 20060324
 
793
        for state, line in self.plan:
 
794
            if state == 'unchanged':
 
795
                # resync and flush queued conflicts changes if any
 
796
                for struct in outstanding_struct():
 
797
                    yield struct
 
798
                lines_a = []
 
799
                lines_b = []
 
800
                ch_a = ch_b = False
 
801
                
 
802
            if state == 'unchanged':
 
803
                if line:
 
804
                    yield ([line],)
 
805
            elif state == 'killed-a':
 
806
                ch_a = True
 
807
                lines_b.append(line)
 
808
            elif state == 'killed-b':
 
809
                ch_b = True
 
810
                lines_a.append(line)
 
811
            elif state == 'new-a':
 
812
                ch_a = True
 
813
                lines_a.append(line)
 
814
            elif state == 'new-b':
 
815
                ch_b = True
 
816
                lines_b.append(line)
 
817
            elif state == 'conflicted-a':
 
818
                ch_b = ch_a = True
 
819
                lines_a.append(line)
 
820
            elif state == 'conflicted-b':
 
821
                ch_b = ch_a = True
 
822
                lines_b.append(line)
 
823
            else:
 
824
                if state not in ('irrelevant', 'ghost-a', 'ghost-b',
 
825
                        'killed-base', 'killed-both'):
 
826
                    raise AssertionError(state)
 
827
        for struct in outstanding_struct():
 
828
            yield struct
 
829
 
 
830
 
 
831
class WeaveMerge(PlanWeaveMerge):
 
832
    """Weave merge that takes a VersionedFile and two versions as its input."""
 
833
 
 
834
    def __init__(self, versionedfile, ver_a, ver_b, 
 
835
        a_marker=PlanWeaveMerge.A_MARKER, b_marker=PlanWeaveMerge.B_MARKER):
 
836
        plan = versionedfile.plan_merge(ver_a, ver_b)
 
837
        PlanWeaveMerge.__init__(self, plan, a_marker, b_marker)
 
838
 
 
839
 
 
840
class InterVersionedFile(InterObject):
 
841
    """This class represents operations taking place between two VersionedFiles.
 
842
 
 
843
    Its instances have methods like join, and contain
 
844
    references to the source and target versionedfiles these operations can be 
 
845
    carried out on.
 
846
 
 
847
    Often we will provide convenience methods on 'versionedfile' which carry out
 
848
    operations with another versionedfile - they will always forward to
 
849
    InterVersionedFile.get(other).method_name(parameters).
 
850
    """
 
851
 
 
852
    _optimisers = []
 
853
    """The available optimised InterVersionedFile types."""
 
854
 
 
855
    def join(self, pb=None, msg=None, version_ids=None, ignore_missing=False):
 
856
        """Integrate versions from self.source into self.target.
 
857
 
 
858
        If version_ids is None all versions from source should be
 
859
        incorporated into this versioned file.
 
860
 
 
861
        Must raise RevisionNotPresent if any of the specified versions
 
862
        are not present in the other file's history unless ignore_missing is 
 
863
        supplied in which case they are silently skipped.
 
864
        """
 
865
        target = self.target
 
866
        version_ids = self._get_source_version_ids(version_ids, ignore_missing)
 
867
        graph = Graph(self.source)
 
868
        search = graph._make_breadth_first_searcher(version_ids)
 
869
        transitive_ids = set()
 
870
        map(transitive_ids.update, list(search))
 
871
        parent_map = self.source.get_parent_map(transitive_ids)
 
872
        order = tsort.topo_sort(parent_map.items())
 
873
        pb = ui.ui_factory.nested_progress_bar()
 
874
        parent_texts = {}
 
875
        try:
 
876
            # TODO for incremental cross-format work:
 
877
            # make a versioned file with the following content:
 
878
            # all revisions we have been asked to join
 
879
            # all their ancestors that are *not* in target already.
 
880
            # the immediate parents of the above two sets, with 
 
881
            # empty parent lists - these versions are in target already
 
882
            # and the incorrect version data will be ignored.
 
883
            # TODO: for all ancestors that are present in target already,
 
884
            # check them for consistent data, this requires moving sha1 from
 
885
            # 
 
886
            # TODO: remove parent texts when they are not relevant any more for 
 
887
            # memory pressure reduction. RBC 20060313
 
888
            # pb.update('Converting versioned data', 0, len(order))
 
889
            total = len(order)
 
890
            for index, version in enumerate(order):
 
891
                pb.update('Converting versioned data', index, total)
 
892
                if version in target:
 
893
                    continue
 
894
                _, _, parent_text = target.add_lines(version,
 
895
                                               parent_map[version],
 
896
                                               self.source.get_lines(version),
 
897
                                               parent_texts=parent_texts)
 
898
                parent_texts[version] = parent_text
 
899
            return total
 
900
        finally:
 
901
            pb.finished()
 
902
 
 
903
    def _get_source_version_ids(self, version_ids, ignore_missing):
 
904
        """Determine the version ids to be used from self.source.
 
905
 
 
906
        :param version_ids: The caller-supplied version ids to check. (None 
 
907
                            for all). If None is in version_ids, it is stripped.
 
908
        :param ignore_missing: if True, remove missing ids from the version 
 
909
                               list. If False, raise RevisionNotPresent on
 
910
                               a missing version id.
 
911
        :return: A set of version ids.
 
912
        """
 
913
        if version_ids is None:
 
914
            # None cannot be in source.versions
 
915
            return set(self.source.versions())
 
916
        else:
 
917
            if ignore_missing:
 
918
                return set(self.source.versions()).intersection(set(version_ids))
 
919
            else:
 
920
                new_version_ids = set()
 
921
                for version in version_ids:
 
922
                    if version is None:
 
923
                        continue
 
924
                    if not self.source.has_version(version):
 
925
                        raise errors.RevisionNotPresent(version, str(self.source))
 
926
                    else:
 
927
                        new_version_ids.add(version)
 
928
                return new_version_ids