/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

Merge bzr.dev.

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