1
# Copyright (C) 2005, 2006 Canonical Ltd
 
 
4
#   Johan Rydberg <jrydberg@gnu.org>
 
 
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.
 
 
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.
 
 
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
 
 
20
"""Versioned text file storage api."""
 
 
22
from bzrlib.lazy_import import lazy_import
 
 
23
lazy_import(globals(), """
 
 
33
from bzrlib.graph import Graph
 
 
34
from bzrlib.transport.memory import MemoryTransport
 
 
37
from cStringIO import StringIO
 
 
39
from bzrlib.inter import InterObject
 
 
40
from bzrlib.symbol_versioning import *
 
 
41
from bzrlib.textmerge import TextMerge
 
 
44
class VersionedFile(object):
 
 
45
    """Versioned text file storage.
 
 
47
    A versioned file manages versions of line-based text files,
 
 
48
    keeping track of the originating version for each line.
 
 
50
    To clients the "lines" of the file are represented as a list of
 
 
51
    strings. These strings will typically have terminal newline
 
 
52
    characters, but this is not required.  In particular files commonly
 
 
53
    do not have a newline at the end of the file.
 
 
55
    Texts are identified by a version-id string.
 
 
58
    def __init__(self, access_mode):
 
 
60
        self._access_mode = access_mode
 
 
63
    def check_not_reserved_id(version_id):
 
 
64
        revision.check_not_reserved_id(version_id)
 
 
66
    def copy_to(self, name, transport):
 
 
67
        """Copy this versioned file to name on transport."""
 
 
68
        raise NotImplementedError(self.copy_to)
 
 
71
        """Return a unsorted list of versions."""
 
 
72
        raise NotImplementedError(self.versions)
 
 
74
    @deprecated_method(one_four)
 
 
75
    def has_ghost(self, version_id):
 
 
76
        """Returns whether version is present as a ghost."""
 
 
77
        raise NotImplementedError(self.has_ghost)
 
 
79
    def has_version(self, version_id):
 
 
80
        """Returns whether version is present."""
 
 
81
        raise NotImplementedError(self.has_version)
 
 
83
    def add_lines(self, version_id, parents, lines, parent_texts=None,
 
 
84
        left_matching_blocks=None, nostore_sha=None, random_id=False,
 
 
86
        """Add a single text on top of the versioned file.
 
 
88
        Must raise RevisionAlreadyPresent if the new version is
 
 
89
        already present in file history.
 
 
91
        Must raise RevisionNotPresent if any of the given parents are
 
 
92
        not present in file history.
 
 
94
        :param lines: A list of lines. Each line must be a bytestring. And all
 
 
95
            of them except the last must be terminated with \n and contain no
 
 
96
            other \n's. The last line may either contain no \n's or a single
 
 
97
            terminated \n. If the lines list does meet this constraint the add
 
 
98
            routine may error or may succeed - but you will be unable to read
 
 
99
            the data back accurately. (Checking the lines have been split
 
 
100
            correctly is expensive and extremely unlikely to catch bugs so it
 
 
101
            is not done at runtime unless check_content is True.)
 
 
102
        :param parent_texts: An optional dictionary containing the opaque 
 
 
103
            representations of some or all of the parents of version_id to
 
 
104
            allow delta optimisations.  VERY IMPORTANT: the texts must be those
 
 
105
            returned by add_lines or data corruption can be caused.
 
 
106
        :param left_matching_blocks: a hint about which areas are common
 
 
107
            between the text and its left-hand-parent.  The format is
 
 
108
            the SequenceMatcher.get_matching_blocks format.
 
 
109
        :param nostore_sha: Raise ExistingContent and do not add the lines to
 
 
110
            the versioned file if the digest of the lines matches this.
 
 
111
        :param random_id: If True a random id has been selected rather than
 
 
112
            an id determined by some deterministic process such as a converter
 
 
113
            from a foreign VCS. When True the backend may choose not to check
 
 
114
            for uniqueness of the resulting key within the versioned file, so
 
 
115
            this should only be done when the result is expected to be unique
 
 
117
        :param check_content: If True, the lines supplied are verified to be
 
 
118
            bytestrings that are correctly formed lines.
 
 
119
        :return: The text sha1, the number of bytes in the text, and an opaque
 
 
120
                 representation of the inserted version which can be provided
 
 
121
                 back to future add_lines calls in the parent_texts dictionary.
 
 
123
        self._check_write_ok()
 
 
124
        return self._add_lines(version_id, parents, lines, parent_texts,
 
 
125
            left_matching_blocks, nostore_sha, random_id, check_content)
 
 
127
    def _add_lines(self, version_id, parents, lines, parent_texts,
 
 
128
        left_matching_blocks, nostore_sha, random_id, check_content):
 
 
129
        """Helper to do the class specific add_lines."""
 
 
130
        raise NotImplementedError(self.add_lines)
 
 
132
    def add_lines_with_ghosts(self, version_id, parents, lines,
 
 
133
        parent_texts=None, nostore_sha=None, random_id=False,
 
 
134
        check_content=True, left_matching_blocks=None):
 
 
135
        """Add lines to the versioned file, allowing ghosts to be present.
 
 
137
        This takes the same parameters as add_lines and returns the same.
 
 
139
        self._check_write_ok()
 
 
140
        return self._add_lines_with_ghosts(version_id, parents, lines,
 
 
141
            parent_texts, nostore_sha, random_id, check_content, left_matching_blocks)
 
 
143
    def _add_lines_with_ghosts(self, version_id, parents, lines, parent_texts,
 
 
144
        nostore_sha, random_id, check_content, left_matching_blocks):
 
 
145
        """Helper to do class specific add_lines_with_ghosts."""
 
 
146
        raise NotImplementedError(self.add_lines_with_ghosts)
 
 
148
    def check(self, progress_bar=None):
 
 
149
        """Check the versioned file for integrity."""
 
 
150
        raise NotImplementedError(self.check)
 
 
152
    def _check_lines_not_unicode(self, lines):
 
 
153
        """Check that lines being added to a versioned file are not unicode."""
 
 
155
            if line.__class__ is not str:
 
 
156
                raise errors.BzrBadParameterUnicode("lines")
 
 
158
    def _check_lines_are_lines(self, lines):
 
 
159
        """Check that the lines really are full lines without inline EOL."""
 
 
161
            if '\n' in line[:-1]:
 
 
162
                raise errors.BzrBadParameterContainsNewline("lines")
 
 
164
    def _check_write_ok(self):
 
 
165
        """Is the versioned file marked as 'finished' ? Raise if it is."""
 
 
167
            raise errors.OutSideTransaction()
 
 
168
        if self._access_mode != 'w':
 
 
169
            raise errors.ReadOnlyObjectDirtiedError(self)
 
 
171
    def enable_cache(self):
 
 
172
        """Tell this versioned file that it should cache any data it reads.
 
 
174
        This is advisory, implementations do not have to support caching.
 
 
178
    def clear_cache(self):
 
 
179
        """Remove any data cached in the versioned file object.
 
 
181
        This only needs to be supported if caches are supported
 
 
185
    def clone_text(self, new_version_id, old_version_id, parents):
 
 
186
        """Add an identical text to old_version_id as new_version_id.
 
 
188
        Must raise RevisionNotPresent if the old version or any of the
 
 
189
        parents are not present in file history.
 
 
191
        Must raise RevisionAlreadyPresent if the new version is
 
 
192
        already present in file history."""
 
 
193
        self._check_write_ok()
 
 
194
        return self._clone_text(new_version_id, old_version_id, parents)
 
 
196
    def _clone_text(self, new_version_id, old_version_id, parents):
 
 
197
        """Helper function to do the _clone_text work."""
 
 
198
        raise NotImplementedError(self.clone_text)
 
 
200
    def get_format_signature(self):
 
 
201
        """Get a text description of the data encoding in this file.
 
 
205
        raise NotImplementedError(self.get_format_signature)
 
 
207
    def make_mpdiffs(self, version_ids):
 
 
208
        """Create multiparent diffs for specified versions."""
 
 
209
        knit_versions = set()
 
 
210
        knit_versions.update(version_ids)
 
 
211
        parent_map = self.get_parent_map(version_ids)
 
 
212
        for version_id in version_ids:
 
 
214
                knit_versions.update(parent_map[version_id])
 
 
216
                raise RevisionNotPresent(version_id, self)
 
 
217
        # We need to filter out ghosts, because we can't diff against them.
 
 
218
        knit_versions = set(self.get_parent_map(knit_versions).keys())
 
 
219
        lines = dict(zip(knit_versions,
 
 
220
            self._get_lf_split_line_list(knit_versions)))
 
 
222
        for version_id in version_ids:
 
 
223
            target = lines[version_id]
 
 
225
                parents = [lines[p] for p in parent_map[version_id] if p in
 
 
228
                raise RevisionNotPresent(version_id, self)
 
 
230
                left_parent_blocks = self._extract_blocks(version_id,
 
 
233
                left_parent_blocks = None
 
 
234
            diffs.append(multiparent.MultiParent.from_lines(target, parents,
 
 
238
    def _extract_blocks(self, version_id, source, target):
 
 
241
    def add_mpdiffs(self, records):
 
 
242
        """Add mpdiffs to this VersionedFile.
 
 
244
        Records should be iterables of version, parents, expected_sha1,
 
 
245
        mpdiff. mpdiff should be a MultiParent instance.
 
 
247
        # Does this need to call self._check_write_ok()? (IanC 20070919)
 
 
249
        mpvf = multiparent.MultiMemoryVersionedFile()
 
 
251
        for version, parent_ids, expected_sha1, mpdiff in records:
 
 
252
            versions.append(version)
 
 
253
            mpvf.add_diff(mpdiff, version, parent_ids)
 
 
254
        needed_parents = set()
 
 
255
        for version, parent_ids, expected_sha1, mpdiff in records:
 
 
256
            needed_parents.update(p for p in parent_ids
 
 
257
                                  if not mpvf.has_version(p))
 
 
258
        present_parents = set(self.get_parent_map(needed_parents).keys())
 
 
259
        for parent_id, lines in zip(present_parents,
 
 
260
                                 self._get_lf_split_line_list(present_parents)):
 
 
261
            mpvf.add_version(lines, parent_id, [])
 
 
262
        for (version, parent_ids, expected_sha1, mpdiff), lines in\
 
 
263
            zip(records, mpvf.get_line_list(versions)):
 
 
264
            if len(parent_ids) == 1:
 
 
265
                left_matching_blocks = list(mpdiff.get_matching_blocks(0,
 
 
266
                    mpvf.get_diff(parent_ids[0]).num_lines()))
 
 
268
                left_matching_blocks = None
 
 
270
                _, _, version_text = self.add_lines_with_ghosts(version,
 
 
271
                    parent_ids, lines, vf_parents,
 
 
272
                    left_matching_blocks=left_matching_blocks)
 
 
273
            except NotImplementedError:
 
 
274
                # The vf can't handle ghosts, so add lines normally, which will
 
 
275
                # (reasonably) fail if there are ghosts in the data.
 
 
276
                _, _, version_text = self.add_lines(version,
 
 
277
                    parent_ids, lines, vf_parents,
 
 
278
                    left_matching_blocks=left_matching_blocks)
 
 
279
            vf_parents[version] = version_text
 
 
280
        for (version, parent_ids, expected_sha1, mpdiff), sha1 in\
 
 
281
             zip(records, self.get_sha1s(versions)):
 
 
282
            if expected_sha1 != sha1:
 
 
283
                raise errors.VersionedFileInvalidChecksum(version)
 
 
285
    def get_sha1(self, version_id):
 
 
286
        """Get the stored sha1 sum for the given revision.
 
 
288
        :param version_id: The name of the version to lookup
 
 
290
        raise NotImplementedError(self.get_sha1)
 
 
292
    def get_sha1s(self, version_ids):
 
 
293
        """Get the stored sha1 sums for the given revisions.
 
 
295
        :param version_ids: The names of the versions to lookup
 
 
296
        :return: a list of sha1s in order according to the version_ids
 
 
298
        raise NotImplementedError(self.get_sha1s)
 
 
300
    def get_suffixes(self):
 
 
301
        """Return the file suffixes associated with this versioned file."""
 
 
302
        raise NotImplementedError(self.get_suffixes)
 
 
304
    def get_text(self, version_id):
 
 
305
        """Return version contents as a text string.
 
 
307
        Raises RevisionNotPresent if version is not present in
 
 
310
        return ''.join(self.get_lines(version_id))
 
 
311
    get_string = get_text
 
 
313
    def get_texts(self, version_ids):
 
 
314
        """Return the texts of listed versions as a list of strings.
 
 
316
        Raises RevisionNotPresent if version is not present in
 
 
319
        return [''.join(self.get_lines(v)) for v in version_ids]
 
 
321
    def get_lines(self, version_id):
 
 
322
        """Return version contents as a sequence of lines.
 
 
324
        Raises RevisionNotPresent if version is not present in
 
 
327
        raise NotImplementedError(self.get_lines)
 
 
329
    def _get_lf_split_line_list(self, version_ids):
 
 
330
        return [StringIO(t).readlines() for t in self.get_texts(version_ids)]
 
 
332
    def get_ancestry(self, version_ids, topo_sorted=True):
 
 
333
        """Return a list of all ancestors of given version(s). This
 
 
334
        will not include the null revision.
 
 
336
        This list will not be topologically sorted if topo_sorted=False is
 
 
339
        Must raise RevisionNotPresent if any of the given versions are
 
 
340
        not present in file history."""
 
 
341
        if isinstance(version_ids, basestring):
 
 
342
            version_ids = [version_ids]
 
 
343
        raise NotImplementedError(self.get_ancestry)
 
 
345
    def get_ancestry_with_ghosts(self, version_ids):
 
 
346
        """Return a list of all ancestors of given version(s). This
 
 
347
        will not include the null revision.
 
 
349
        Must raise RevisionNotPresent if any of the given versions are
 
 
350
        not present in file history.
 
 
352
        Ghosts that are known about will be included in ancestry list,
 
 
353
        but are not explicitly marked.
 
 
355
        raise NotImplementedError(self.get_ancestry_with_ghosts)
 
 
357
    def get_graph(self, version_ids=None):
 
 
358
        """Return a graph from the versioned file. 
 
 
360
        Ghosts are not listed or referenced in the graph.
 
 
361
        :param version_ids: Versions to select.
 
 
362
                            None means retrieve all versions.
 
 
364
        if version_ids is None:
 
 
365
            return dict(self.iter_parents(self.versions()))
 
 
367
        pending = set(version_ids)
 
 
369
            this_iteration = pending
 
 
371
            for version, parents in self.iter_parents(this_iteration):
 
 
372
                result[version] = parents
 
 
373
                for parent in parents:
 
 
379
    @deprecated_method(one_four)
 
 
380
    def get_graph_with_ghosts(self):
 
 
381
        """Return a graph for the entire versioned file.
 
 
383
        Ghosts are referenced in parents list but are not
 
 
386
        raise NotImplementedError(self.get_graph_with_ghosts)
 
 
388
    def get_parent_map(self, version_ids):
 
 
389
        """Get a map of the parents of version_ids.
 
 
391
        :param version_ids: The version ids to look up parents for.
 
 
392
        :return: A mapping from version id to parents.
 
 
394
        raise NotImplementedError(self.get_parent_map)
 
 
396
    @deprecated_method(one_four)
 
 
397
    def get_parents(self, version_id):
 
 
398
        """Return version names for parents of a version.
 
 
400
        Must raise RevisionNotPresent if version is not present in
 
 
404
            all = self.get_parent_map([version_id])[version_id]
 
 
406
            raise errors.RevisionNotPresent(version_id, self)
 
 
408
        parent_parents = self.get_parent_map(all)
 
 
409
        for version_id in all:
 
 
410
            if version_id in parent_parents:
 
 
411
                result.append(version_id)
 
 
414
    def get_parents_with_ghosts(self, version_id):
 
 
415
        """Return version names for parents of version_id.
 
 
417
        Will raise RevisionNotPresent if version_id is not present
 
 
420
        Ghosts that are known about will be included in the parent list,
 
 
421
        but are not explicitly marked.
 
 
424
            return list(self.get_parent_map([version_id])[version_id])
 
 
426
            raise errors.RevisionNotPresent(version_id, self)
 
 
428
    def annotate_iter(self, version_id):
 
 
429
        """Yield list of (version-id, line) pairs for the specified
 
 
432
        Must raise RevisionNotPresent if the given version is
 
 
433
        not present in file history.
 
 
435
        raise NotImplementedError(self.annotate_iter)
 
 
437
    def annotate(self, version_id):
 
 
438
        return list(self.annotate_iter(version_id))
 
 
440
    def join(self, other, pb=None, msg=None, version_ids=None,
 
 
441
             ignore_missing=False):
 
 
442
        """Integrate versions from other into this versioned file.
 
 
444
        If version_ids is None all versions from other should be
 
 
445
        incorporated into this versioned file.
 
 
447
        Must raise RevisionNotPresent if any of the specified versions
 
 
448
        are not present in the other file's history unless ignore_missing
 
 
449
        is supplied in which case they are silently skipped.
 
 
451
        self._check_write_ok()
 
 
452
        return InterVersionedFile.get(other, self).join(
 
 
458
    def iter_lines_added_or_present_in_versions(self, version_ids=None,
 
 
460
        """Iterate over the lines in the versioned file from version_ids.
 
 
462
        This may return lines from other versions. Each item the returned
 
 
463
        iterator yields is a tuple of a line and a text version that that line
 
 
464
        is present in (not introduced in).
 
 
466
        Ordering of results is in whatever order is most suitable for the
 
 
467
        underlying storage format.
 
 
469
        If a progress bar is supplied, it may be used to indicate progress.
 
 
470
        The caller is responsible for cleaning up progress bars (because this
 
 
473
        NOTES: Lines are normalised: they will all have \n terminators.
 
 
474
               Lines are returned in arbitrary order.
 
 
476
        :return: An iterator over (line, version_id).
 
 
478
        raise NotImplementedError(self.iter_lines_added_or_present_in_versions)
 
 
480
    def iter_parents(self, version_ids):
 
 
481
        """Iterate through the parents for many version ids.
 
 
483
        :param version_ids: An iterable yielding version_ids.
 
 
484
        :return: An iterator that yields (version_id, parents). Requested 
 
 
485
            version_ids not present in the versioned file are simply skipped.
 
 
486
            The order is undefined, allowing for different optimisations in
 
 
487
            the underlying implementation.
 
 
489
        return self.get_parent_map(version_ids).iteritems()
 
 
491
    def transaction_finished(self):
 
 
492
        """The transaction that this file was opened in has finished.
 
 
494
        This records self.finished = True and should cause all mutating
 
 
499
    def plan_merge(self, ver_a, ver_b):
 
 
500
        """Return pseudo-annotation indicating how the two versions merge.
 
 
502
        This is computed between versions a and b and their common
 
 
505
        Weave lines present in none of them are skipped entirely.
 
 
508
        killed-base Dead in base revision
 
 
509
        killed-both Killed in each revision
 
 
512
        unchanged   Alive in both a and b (possibly created in both)
 
 
515
        ghost-a     Killed in a, unborn in b    
 
 
516
        ghost-b     Killed in b, unborn in a
 
 
517
        irrelevant  Not in either revision
 
 
519
        raise NotImplementedError(VersionedFile.plan_merge)
 
 
521
    def weave_merge(self, plan, a_marker=TextMerge.A_MARKER,
 
 
522
                    b_marker=TextMerge.B_MARKER):
 
 
523
        return PlanWeaveMerge(plan, a_marker, b_marker).merge_lines()[0]
 
 
526
class _PlanMergeVersionedFile(object):
 
 
527
    """A VersionedFile for uncommitted and committed texts.
 
 
529
    It is intended to allow merges to be planned with working tree texts.
 
 
530
    It implements only the small part of the VersionedFile interface used by
 
 
531
    PlanMerge.  It falls back to multiple versionedfiles for data not stored in
 
 
532
    _PlanMergeVersionedFile itself.
 
 
535
    def __init__(self, file_id, fallback_versionedfiles=None):
 
 
538
        :param file_id: Used when raising exceptions.
 
 
539
        :param fallback_versionedfiles: If supplied, the set of fallbacks to
 
 
540
            use.  Otherwise, _PlanMergeVersionedFile.fallback_versionedfiles
 
 
541
            can be appended to later.
 
 
543
        self._file_id = file_id
 
 
544
        if fallback_versionedfiles is None:
 
 
545
            self.fallback_versionedfiles = []
 
 
547
            self.fallback_versionedfiles = fallback_versionedfiles
 
 
551
    def plan_merge(self, ver_a, ver_b, base=None):
 
 
552
        """See VersionedFile.plan_merge"""
 
 
553
        from bzrlib.merge import _PlanMerge
 
 
555
            return _PlanMerge(ver_a, ver_b, self).plan_merge()
 
 
556
        old_plan = list(_PlanMerge(ver_a, base, self).plan_merge())
 
 
557
        new_plan = list(_PlanMerge(ver_a, ver_b, self).plan_merge())
 
 
558
        return _PlanMerge._subtract_plans(old_plan, new_plan)
 
 
560
    def plan_lca_merge(self, ver_a, ver_b, base=None):
 
 
561
        from bzrlib.merge import _PlanLCAMerge
 
 
562
        graph = self._get_graph()
 
 
563
        new_plan = _PlanLCAMerge(ver_a, ver_b, self, graph).plan_merge()
 
 
566
        old_plan = _PlanLCAMerge(ver_a, base, self, graph).plan_merge()
 
 
567
        return _PlanLCAMerge._subtract_plans(list(old_plan), list(new_plan))
 
 
569
    def add_lines(self, version_id, parents, lines):
 
 
570
        """See VersionedFile.add_lines
 
 
572
        Lines are added locally, not fallback versionedfiles.  Also, ghosts are
 
 
573
        permitted.  Only reserved ids are permitted.
 
 
575
        if not revision.is_reserved_id(version_id):
 
 
576
            raise ValueError('Only reserved ids may be used')
 
 
578
            raise ValueError('Parents may not be None')
 
 
580
            raise ValueError('Lines may not be None')
 
 
581
        self._parents[version_id] = tuple(parents)
 
 
582
        self._lines[version_id] = lines
 
 
584
    def get_lines(self, version_id):
 
 
585
        """See VersionedFile.get_ancestry"""
 
 
586
        lines = self._lines.get(version_id)
 
 
587
        if lines is not None:
 
 
589
        for versionedfile in self.fallback_versionedfiles:
 
 
591
                return versionedfile.get_lines(version_id)
 
 
592
            except errors.RevisionNotPresent:
 
 
595
            raise errors.RevisionNotPresent(version_id, self._file_id)
 
 
597
    def get_ancestry(self, version_id, topo_sorted=False):
 
 
598
        """See VersionedFile.get_ancestry.
 
 
600
        Note that this implementation assumes that if a VersionedFile can
 
 
601
        answer get_ancestry at all, it can give an authoritative answer.  In
 
 
602
        fact, ghosts can invalidate this assumption.  But it's good enough
 
 
603
        99% of the time, and far cheaper/simpler.
 
 
605
        Also note that the results of this version are never topologically
 
 
606
        sorted, and are a set.
 
 
609
            raise ValueError('This implementation does not provide sorting')
 
 
610
        parents = self._parents.get(version_id)
 
 
612
            for vf in self.fallback_versionedfiles:
 
 
614
                    return vf.get_ancestry(version_id, topo_sorted=False)
 
 
615
                except errors.RevisionNotPresent:
 
 
618
                raise errors.RevisionNotPresent(version_id, self._file_id)
 
 
619
        ancestry = set([version_id])
 
 
620
        for parent in parents:
 
 
621
            ancestry.update(self.get_ancestry(parent, topo_sorted=False))
 
 
624
    def get_parent_map(self, version_ids):
 
 
625
        """See VersionedFile.get_parent_map"""
 
 
627
        pending = set(version_ids)
 
 
628
        for key in version_ids:
 
 
630
                result[key] = self._parents[key]
 
 
633
        pending = pending - set(result.keys())
 
 
634
        for versionedfile in self.fallback_versionedfiles:
 
 
635
            parents = versionedfile.get_parent_map(pending)
 
 
636
            result.update(parents)
 
 
637
            pending = pending - set(parents.keys())
 
 
642
    def _get_graph(self):
 
 
643
        from bzrlib.graph import (
 
 
646
            _StackedParentsProvider,
 
 
648
        from bzrlib.repofmt.knitrepo import _KnitParentsProvider
 
 
649
        parent_providers = [DictParentsProvider(self._parents)]
 
 
650
        for vf in self.fallback_versionedfiles:
 
 
651
            parent_providers.append(_KnitParentsProvider(vf))
 
 
652
        return Graph(_StackedParentsProvider(parent_providers))
 
 
655
class PlanWeaveMerge(TextMerge):
 
 
656
    """Weave merge that takes a plan as its input.
 
 
658
    This exists so that VersionedFile.plan_merge is implementable.
 
 
659
    Most callers will want to use WeaveMerge instead.
 
 
662
    def __init__(self, plan, a_marker=TextMerge.A_MARKER,
 
 
663
                 b_marker=TextMerge.B_MARKER):
 
 
664
        TextMerge.__init__(self, a_marker, b_marker)
 
 
667
    def _merge_struct(self):
 
 
672
        def outstanding_struct():
 
 
673
            if not lines_a and not lines_b:
 
 
675
            elif ch_a and not ch_b:
 
 
678
            elif ch_b and not ch_a:
 
 
680
            elif lines_a == lines_b:
 
 
683
                yield (lines_a, lines_b)
 
 
685
        # We previously considered either 'unchanged' or 'killed-both' lines
 
 
686
        # to be possible places to resynchronize.  However, assuming agreement
 
 
687
        # on killed-both lines may be too aggressive. -- mbp 20060324
 
 
688
        for state, line in self.plan:
 
 
689
            if state == 'unchanged':
 
 
690
                # resync and flush queued conflicts changes if any
 
 
691
                for struct in outstanding_struct():
 
 
697
            if state == 'unchanged':
 
 
700
            elif state == 'killed-a':
 
 
703
            elif state == 'killed-b':
 
 
706
            elif state == 'new-a':
 
 
709
            elif state == 'new-b':
 
 
712
            elif state == 'conflicted-a':
 
 
715
            elif state == 'conflicted-b':
 
 
719
                assert state in ('irrelevant', 'ghost-a', 'ghost-b', 
 
 
720
                                 'killed-base', 'killed-both'), state
 
 
721
        for struct in outstanding_struct():
 
 
725
class WeaveMerge(PlanWeaveMerge):
 
 
726
    """Weave merge that takes a VersionedFile and two versions as its input."""
 
 
728
    def __init__(self, versionedfile, ver_a, ver_b, 
 
 
729
        a_marker=PlanWeaveMerge.A_MARKER, b_marker=PlanWeaveMerge.B_MARKER):
 
 
730
        plan = versionedfile.plan_merge(ver_a, ver_b)
 
 
731
        PlanWeaveMerge.__init__(self, plan, a_marker, b_marker)
 
 
734
class InterVersionedFile(InterObject):
 
 
735
    """This class represents operations taking place between two VersionedFiles.
 
 
737
    Its instances have methods like join, and contain
 
 
738
    references to the source and target versionedfiles these operations can be 
 
 
741
    Often we will provide convenience methods on 'versionedfile' which carry out
 
 
742
    operations with another versionedfile - they will always forward to
 
 
743
    InterVersionedFile.get(other).method_name(parameters).
 
 
747
    """The available optimised InterVersionedFile types."""
 
 
749
    def join(self, pb=None, msg=None, version_ids=None, ignore_missing=False):
 
 
750
        """Integrate versions from self.source into self.target.
 
 
752
        If version_ids is None all versions from source should be
 
 
753
        incorporated into this versioned file.
 
 
755
        Must raise RevisionNotPresent if any of the specified versions
 
 
756
        are not present in the other file's history unless ignore_missing is 
 
 
757
        supplied in which case they are silently skipped.
 
 
760
        version_ids = self._get_source_version_ids(version_ids, ignore_missing)
 
 
761
        graph = Graph(self.source)
 
 
762
        search = graph._make_breadth_first_searcher(version_ids)
 
 
763
        transitive_ids = set()
 
 
764
        map(transitive_ids.update, list(search))
 
 
765
        parent_map = self.source.get_parent_map(transitive_ids)
 
 
766
        order = tsort.topo_sort(parent_map.items())
 
 
767
        pb = ui.ui_factory.nested_progress_bar()
 
 
770
            # TODO for incremental cross-format work:
 
 
771
            # make a versioned file with the following content:
 
 
772
            # all revisions we have been asked to join
 
 
773
            # all their ancestors that are *not* in target already.
 
 
774
            # the immediate parents of the above two sets, with 
 
 
775
            # empty parent lists - these versions are in target already
 
 
776
            # and the incorrect version data will be ignored.
 
 
777
            # TODO: for all ancestors that are present in target already,
 
 
778
            # check them for consistent data, this requires moving sha1 from
 
 
780
            # TODO: remove parent texts when they are not relevant any more for 
 
 
781
            # memory pressure reduction. RBC 20060313
 
 
782
            # pb.update('Converting versioned data', 0, len(order))
 
 
784
            for index, version in enumerate(order):
 
 
785
                pb.update('Converting versioned data', index, total)
 
 
786
                if version in target:
 
 
788
                _, _, parent_text = target.add_lines(version,
 
 
790
                                               self.source.get_lines(version),
 
 
791
                                               parent_texts=parent_texts)
 
 
792
                parent_texts[version] = parent_text
 
 
797
    def _get_source_version_ids(self, version_ids, ignore_missing):
 
 
798
        """Determine the version ids to be used from self.source.
 
 
800
        :param version_ids: The caller-supplied version ids to check. (None 
 
 
801
                            for all). If None is in version_ids, it is stripped.
 
 
802
        :param ignore_missing: if True, remove missing ids from the version 
 
 
803
                               list. If False, raise RevisionNotPresent on
 
 
804
                               a missing version id.
 
 
805
        :return: A set of version ids.
 
 
807
        if version_ids is None:
 
 
808
            # None cannot be in source.versions
 
 
809
            return set(self.source.versions())
 
 
812
                return set(self.source.versions()).intersection(set(version_ids))
 
 
814
                new_version_ids = set()
 
 
815
                for version in version_ids:
 
 
818
                    if not self.source.has_version(version):
 
 
819
                        raise errors.RevisionNotPresent(version, str(self.source))
 
 
821
                        new_version_ids.add(version)
 
 
822
                return new_version_ids