~bzr-pqm/bzr/bzr.dev

2052.3.2 by John Arbash Meinel
Change Copyright .. by Canonical to Copyright ... Canonical
1
# Copyright (C) 2005, 2006 Canonical Ltd
1563.2.1 by Robert Collins
Merge in a variation of the versionedfile api from versioned-file.
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.
1887.1.1 by Adeodato Simó
Do not separate paragraphs in the copyright statement with blank lines,
10
#
1563.2.1 by Robert Collins
Merge in a variation of the versionedfile api from versioned-file.
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.
1887.1.1 by Adeodato Simó
Do not separate paragraphs in the copyright statement with blank lines,
15
#
1563.2.1 by Robert Collins
Merge in a variation of the versionedfile api from versioned-file.
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
1996.3.7 by John Arbash Meinel
lazy import versionedfile, late-load bzrlib.merge
22
from bzrlib.lazy_import import lazy_import
23
lazy_import(globals(), """
24
25
from bzrlib import (
26
    errors,
2249.5.12 by John Arbash Meinel
Change the APIs for VersionedFile, Store, and some of Repository into utf-8
27
    osutils,
2520.4.3 by Aaron Bentley
Implement plain strategy for extracting and installing multiparent diffs
28
    multiparent,
1996.3.7 by John Arbash Meinel
lazy import versionedfile, late-load bzrlib.merge
29
    tsort,
2229.2.1 by Aaron Bentley
Reject reserved ids in versiondfile, tree, branch and repository
30
    revision,
1996.3.7 by John Arbash Meinel
lazy import versionedfile, late-load bzrlib.merge
31
    ui,
32
    )
3287.6.1 by Robert Collins
* ``VersionedFile.get_graph`` is deprecated, with no replacement method.
33
from bzrlib.graph import Graph
1996.3.7 by John Arbash Meinel
lazy import versionedfile, late-load bzrlib.merge
34
from bzrlib.transport.memory import MemoryTransport
35
""")
36
2520.4.90 by Aaron Bentley
Handle \r terminated lines in Weaves properly
37
from cStringIO import StringIO
38
1563.2.12 by Robert Collins
Checkpointing: created InterObject to factor out common inter object worker code, added InterVersionedFile and tests to allow making join work between any versionedfile.
39
from bzrlib.inter import InterObject
3287.5.2 by Robert Collins
Deprecate VersionedFile.get_parents, breaking pulling from a ghost containing knit or pack repository to weaves, which improves correctness and allows simplification of core code.
40
from bzrlib.symbol_versioning import *
1551.6.7 by Aaron Bentley
Implemented two-way merge, refactored weave merge
41
from bzrlib.textmerge import TextMerge
1563.2.11 by Robert Collins
Consolidate reweave and join as we have no separate usage, make reweave tests apply to all versionedfile implementations and deprecate the old reweave apis.
42
43
1563.2.1 by Robert Collins
Merge in a variation of the versionedfile api from versioned-file.
44
class VersionedFile(object):
45
    """Versioned text file storage.
46
    
47
    A versioned file manages versions of line-based text files,
48
    keeping track of the originating version for each line.
49
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.
54
55
    Texts are identified by a version-id string.
56
    """
57
1594.2.23 by Robert Collins
Test versioned file storage handling of clean/dirty status for accessed versioned files.
58
    def __init__(self, access_mode):
1594.2.21 by Robert Collins
Teach versioned files to prevent mutation after finishing.
59
        self.finished = False
1594.2.23 by Robert Collins
Test versioned file storage handling of clean/dirty status for accessed versioned files.
60
        self._access_mode = access_mode
1594.2.21 by Robert Collins
Teach versioned files to prevent mutation after finishing.
61
2229.2.1 by Aaron Bentley
Reject reserved ids in versiondfile, tree, branch and repository
62
    @staticmethod
2229.2.3 by Aaron Bentley
change reserved_id to is_reserved_id, add check_not_reserved for DRY
63
    def check_not_reserved_id(version_id):
64
        revision.check_not_reserved_id(version_id)
2229.2.1 by Aaron Bentley
Reject reserved ids in versiondfile, tree, branch and repository
65
1563.2.15 by Robert Collins
remove the weavestore assumptions about the number and nature of files it manages.
66
    def copy_to(self, name, transport):
67
        """Copy this versioned file to name on transport."""
68
        raise NotImplementedError(self.copy_to)
1863.1.1 by John Arbash Meinel
Allow Versioned files to do caching if explicitly asked, and implement for Knit
69
1563.2.1 by Robert Collins
Merge in a variation of the versionedfile api from versioned-file.
70
    def versions(self):
71
        """Return a unsorted list of versions."""
72
        raise NotImplementedError(self.versions)
73
3287.6.5 by Robert Collins
Deprecate VersionedFile.has_ghost.
74
    @deprecated_method(one_four)
1594.2.8 by Robert Collins
add ghost aware apis to knits.
75
    def has_ghost(self, version_id):
76
        """Returns whether version is present as a ghost."""
77
        raise NotImplementedError(self.has_ghost)
78
1563.2.1 by Robert Collins
Merge in a variation of the versionedfile api from versioned-file.
79
    def has_version(self, version_id):
80
        """Returns whether version is present."""
81
        raise NotImplementedError(self.has_version)
82
2520.4.140 by Aaron Bentley
Use matching blocks from mpdiff for knit delta creation
83
    def add_lines(self, version_id, parents, lines, parent_texts=None,
2805.6.7 by Robert Collins
Review feedback.
84
        left_matching_blocks=None, nostore_sha=None, random_id=False,
85
        check_content=True):
1563.2.1 by Robert Collins
Merge in a variation of the versionedfile api from versioned-file.
86
        """Add a single text on top of the versioned file.
87
88
        Must raise RevisionAlreadyPresent if the new version is
89
        already present in file history.
90
91
        Must raise RevisionNotPresent if any of the given parents are
1594.2.21 by Robert Collins
Teach versioned files to prevent mutation after finishing.
92
        not present in file history.
2805.6.3 by Robert Collins
* The ``VersionedFile`` interface no longer protects against misuse when
93
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
2805.6.7 by Robert Collins
Review feedback.
100
            correctly is expensive and extremely unlikely to catch bugs so it
101
            is not done at runtime unless check_content is True.)
1596.2.32 by Robert Collins
Reduce re-extraction of texts during weave to knit joins by providing a memoisation facility.
102
        :param parent_texts: An optional dictionary containing the opaque 
2805.6.3 by Robert Collins
* The ``VersionedFile`` interface no longer protects against misuse when
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.
2520.4.148 by Aaron Bentley
Updates from review
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.
2794.1.1 by Robert Collins
Allow knits to be instructed not to add a text based on a sha, for commit.
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.
2805.6.4 by Robert Collins
Don't check for existing versions when adding texts with random revision ids.
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
116
            anyway.
2805.6.7 by Robert Collins
Review feedback.
117
        :param check_content: If True, the lines supplied are verified to be
118
            bytestrings that are correctly formed lines.
2776.1.1 by Robert Collins
* The ``add_lines`` methods on ``VersionedFile`` implementations has changed
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.
1594.2.21 by Robert Collins
Teach versioned files to prevent mutation after finishing.
122
        """
1594.2.23 by Robert Collins
Test versioned file storage handling of clean/dirty status for accessed versioned files.
123
        self._check_write_ok()
2520.4.140 by Aaron Bentley
Use matching blocks from mpdiff for knit delta creation
124
        return self._add_lines(version_id, parents, lines, parent_texts,
2805.6.7 by Robert Collins
Review feedback.
125
            left_matching_blocks, nostore_sha, random_id, check_content)
1594.2.21 by Robert Collins
Teach versioned files to prevent mutation after finishing.
126
2520.4.140 by Aaron Bentley
Use matching blocks from mpdiff for knit delta creation
127
    def _add_lines(self, version_id, parents, lines, parent_texts,
2805.6.7 by Robert Collins
Review feedback.
128
        left_matching_blocks, nostore_sha, random_id, check_content):
1594.2.21 by Robert Collins
Teach versioned files to prevent mutation after finishing.
129
        """Helper to do the class specific add_lines."""
1563.2.4 by Robert Collins
First cut at including the knit implementation of versioned_file.
130
        raise NotImplementedError(self.add_lines)
1563.2.1 by Robert Collins
Merge in a variation of the versionedfile api from versioned-file.
131
1596.2.32 by Robert Collins
Reduce re-extraction of texts during weave to knit joins by providing a memoisation facility.
132
    def add_lines_with_ghosts(self, version_id, parents, lines,
2805.6.7 by Robert Collins
Review feedback.
133
        parent_texts=None, nostore_sha=None, random_id=False,
3287.5.2 by Robert Collins
Deprecate VersionedFile.get_parents, breaking pulling from a ghost containing knit or pack repository to weaves, which improves correctness and allows simplification of core code.
134
        check_content=True, left_matching_blocks=None):
1596.2.32 by Robert Collins
Reduce re-extraction of texts during weave to knit joins by providing a memoisation facility.
135
        """Add lines to the versioned file, allowing ghosts to be present.
136
        
2794.1.1 by Robert Collins
Allow knits to be instructed not to add a text based on a sha, for commit.
137
        This takes the same parameters as add_lines and returns the same.
1596.2.32 by Robert Collins
Reduce re-extraction of texts during weave to knit joins by providing a memoisation facility.
138
        """
1594.2.23 by Robert Collins
Test versioned file storage handling of clean/dirty status for accessed versioned files.
139
        self._check_write_ok()
1596.2.32 by Robert Collins
Reduce re-extraction of texts during weave to knit joins by providing a memoisation facility.
140
        return self._add_lines_with_ghosts(version_id, parents, lines,
3287.5.2 by Robert Collins
Deprecate VersionedFile.get_parents, breaking pulling from a ghost containing knit or pack repository to weaves, which improves correctness and allows simplification of core code.
141
            parent_texts, nostore_sha, random_id, check_content, left_matching_blocks)
1594.2.21 by Robert Collins
Teach versioned files to prevent mutation after finishing.
142
2794.1.1 by Robert Collins
Allow knits to be instructed not to add a text based on a sha, for commit.
143
    def _add_lines_with_ghosts(self, version_id, parents, lines, parent_texts,
3287.5.2 by Robert Collins
Deprecate VersionedFile.get_parents, breaking pulling from a ghost containing knit or pack repository to weaves, which improves correctness and allows simplification of core code.
144
        nostore_sha, random_id, check_content, left_matching_blocks):
1594.2.21 by Robert Collins
Teach versioned files to prevent mutation after finishing.
145
        """Helper to do class specific add_lines_with_ghosts."""
1594.2.8 by Robert Collins
add ghost aware apis to knits.
146
        raise NotImplementedError(self.add_lines_with_ghosts)
147
1563.2.19 by Robert Collins
stub out a check for knits.
148
    def check(self, progress_bar=None):
149
        """Check the versioned file for integrity."""
150
        raise NotImplementedError(self.check)
151
1666.1.6 by Robert Collins
Make knit the default format.
152
    def _check_lines_not_unicode(self, lines):
153
        """Check that lines being added to a versioned file are not unicode."""
154
        for line in lines:
155
            if line.__class__ is not str:
156
                raise errors.BzrBadParameterUnicode("lines")
157
158
    def _check_lines_are_lines(self, lines):
159
        """Check that the lines really are full lines without inline EOL."""
160
        for line in lines:
161
            if '\n' in line[:-1]:
162
                raise errors.BzrBadParameterContainsNewline("lines")
163
1594.2.23 by Robert Collins
Test versioned file storage handling of clean/dirty status for accessed versioned files.
164
    def _check_write_ok(self):
1594.2.21 by Robert Collins
Teach versioned files to prevent mutation after finishing.
165
        """Is the versioned file marked as 'finished' ? Raise if it is."""
166
        if self.finished:
167
            raise errors.OutSideTransaction()
1594.2.23 by Robert Collins
Test versioned file storage handling of clean/dirty status for accessed versioned files.
168
        if self._access_mode != 'w':
169
            raise errors.ReadOnlyObjectDirtiedError(self)
1594.2.21 by Robert Collins
Teach versioned files to prevent mutation after finishing.
170
1863.1.1 by John Arbash Meinel
Allow Versioned files to do caching if explicitly asked, and implement for Knit
171
    def enable_cache(self):
172
        """Tell this versioned file that it should cache any data it reads.
173
        
174
        This is advisory, implementations do not have to support caching.
175
        """
176
        pass
177
    
1563.2.7 by Robert Collins
add versioned file clear_cache entry.
178
    def clear_cache(self):
1863.1.1 by John Arbash Meinel
Allow Versioned files to do caching if explicitly asked, and implement for Knit
179
        """Remove any data cached in the versioned file object.
180
181
        This only needs to be supported if caches are supported
182
        """
183
        pass
1563.2.7 by Robert Collins
add versioned file clear_cache entry.
184
1563.2.5 by Robert Collins
Remove unused transaction references from knit.py and the versionedfile interface.
185
    def clone_text(self, new_version_id, old_version_id, parents):
1563.2.1 by Robert Collins
Merge in a variation of the versionedfile api from versioned-file.
186
        """Add an identical text to old_version_id as new_version_id.
187
188
        Must raise RevisionNotPresent if the old version or any of the
189
        parents are not present in file history.
190
191
        Must raise RevisionAlreadyPresent if the new version is
192
        already present in file history."""
1594.2.24 by Robert Collins
Make use of the transaction finalisation warning support to implement in-knit caching.
193
        self._check_write_ok()
194
        return self._clone_text(new_version_id, old_version_id, parents)
195
196
    def _clone_text(self, new_version_id, old_version_id, parents):
197
        """Helper function to do the _clone_text work."""
1563.2.1 by Robert Collins
Merge in a variation of the versionedfile api from versioned-file.
198
        raise NotImplementedError(self.clone_text)
199
2535.3.1 by Andrew Bennetts
Add get_format_signature to VersionedFile
200
    def get_format_signature(self):
201
        """Get a text description of the data encoding in this file.
202
        
2831.7.1 by Ian Clatworthy
versionedfile.py code cleanups
203
        :since: 0.90
2535.3.1 by Andrew Bennetts
Add get_format_signature to VersionedFile
204
        """
205
        raise NotImplementedError(self.get_format_signature)
206
2520.4.41 by Aaron Bentley
Accelerate mpdiff generation
207
    def make_mpdiffs(self, version_ids):
2831.7.1 by Ian Clatworthy
versionedfile.py code cleanups
208
        """Create multiparent diffs for specified versions."""
2520.4.41 by Aaron Bentley
Accelerate mpdiff generation
209
        knit_versions = set()
3287.5.2 by Robert Collins
Deprecate VersionedFile.get_parents, breaking pulling from a ghost containing knit or pack repository to weaves, which improves correctness and allows simplification of core code.
210
        knit_versions.update(version_ids)
211
        parent_map = self.get_parent_map(version_ids)
2520.4.41 by Aaron Bentley
Accelerate mpdiff generation
212
        for version_id in version_ids:
3287.5.2 by Robert Collins
Deprecate VersionedFile.get_parents, breaking pulling from a ghost containing knit or pack repository to weaves, which improves correctness and allows simplification of core code.
213
            try:
214
                knit_versions.update(parent_map[version_id])
215
            except KeyError:
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())
2520.4.90 by Aaron Bentley
Handle \r terminated lines in Weaves properly
219
        lines = dict(zip(knit_versions,
220
            self._get_lf_split_line_list(knit_versions)))
2520.4.41 by Aaron Bentley
Accelerate mpdiff generation
221
        diffs = []
222
        for version_id in version_ids:
223
            target = lines[version_id]
3287.5.2 by Robert Collins
Deprecate VersionedFile.get_parents, breaking pulling from a ghost containing knit or pack repository to weaves, which improves correctness and allows simplification of core code.
224
            try:
225
                parents = [lines[p] for p in parent_map[version_id] if p in
226
                    knit_versions]
227
            except KeyError:
228
                raise RevisionNotPresent(version_id, self)
2520.4.48 by Aaron Bentley
Support getting blocks from knit deltas with no final EOL
229
            if len(parents) > 0:
230
                left_parent_blocks = self._extract_blocks(version_id,
231
                                                          parents[0], target)
232
            else:
233
                left_parent_blocks = None
2520.4.41 by Aaron Bentley
Accelerate mpdiff generation
234
            diffs.append(multiparent.MultiParent.from_lines(target, parents,
235
                         left_parent_blocks))
236
        return diffs
237
2520.4.48 by Aaron Bentley
Support getting blocks from knit deltas with no final EOL
238
    def _extract_blocks(self, version_id, source, target):
2520.4.41 by Aaron Bentley
Accelerate mpdiff generation
239
        return None
2520.4.3 by Aaron Bentley
Implement plain strategy for extracting and installing multiparent diffs
240
2520.4.61 by Aaron Bentley
Do bulk insertion of records
241
    def add_mpdiffs(self, records):
2831.7.1 by Ian Clatworthy
versionedfile.py code cleanups
242
        """Add mpdiffs to this VersionedFile.
2520.4.126 by Aaron Bentley
Add more docs
243
244
        Records should be iterables of version, parents, expected_sha1,
2831.7.1 by Ian Clatworthy
versionedfile.py code cleanups
245
        mpdiff. mpdiff should be a MultiParent instance.
2520.4.126 by Aaron Bentley
Add more docs
246
        """
2831.7.1 by Ian Clatworthy
versionedfile.py code cleanups
247
        # Does this need to call self._check_write_ok()? (IanC 20070919)
2520.4.61 by Aaron Bentley
Do bulk insertion of records
248
        vf_parents = {}
2520.4.141 by Aaron Bentley
More batch operations adding mpdiffs
249
        mpvf = multiparent.MultiMemoryVersionedFile()
250
        versions = []
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()
2520.4.142 by Aaron Bentley
Clean up installation of inventory records
255
        for version, parent_ids, expected_sha1, mpdiff in records:
2520.4.141 by Aaron Bentley
More batch operations adding mpdiffs
256
            needed_parents.update(p for p in parent_ids
257
                                  if not mpvf.has_version(p))
3287.5.2 by Robert Collins
Deprecate VersionedFile.get_parents, breaking pulling from a ghost containing knit or pack repository to weaves, which improves correctness and allows simplification of core code.
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)):
2520.4.141 by Aaron Bentley
More batch operations adding mpdiffs
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:
2520.4.140 by Aaron Bentley
Use matching blocks from mpdiff for knit delta creation
265
                left_matching_blocks = list(mpdiff.get_matching_blocks(0,
2520.4.141 by Aaron Bentley
More batch operations adding mpdiffs
266
                    mpvf.get_diff(parent_ids[0]).num_lines()))
2520.4.140 by Aaron Bentley
Use matching blocks from mpdiff for knit delta creation
267
            else:
268
                left_matching_blocks = None
3287.5.2 by Robert Collins
Deprecate VersionedFile.get_parents, breaking pulling from a ghost containing knit or pack repository to weaves, which improves correctness and allows simplification of core code.
269
            try:
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)
2520.4.61 by Aaron Bentley
Do bulk insertion of records
279
            vf_parents[version] = version_text
2520.4.142 by Aaron Bentley
Clean up installation of inventory records
280
        for (version, parent_ids, expected_sha1, mpdiff), sha1 in\
281
             zip(records, self.get_sha1s(versions)):
282
            if expected_sha1 != sha1:
2520.4.71 by Aaron Bentley
Update test to accept VersionedFileInvalidChecksum instead of TestamentMismatch
283
                raise errors.VersionedFileInvalidChecksum(version)
2520.4.3 by Aaron Bentley
Implement plain strategy for extracting and installing multiparent diffs
284
1666.1.6 by Robert Collins
Make knit the default format.
285
    def get_sha1(self, version_id):
286
        """Get the stored sha1 sum for the given revision.
287
        
2831.7.1 by Ian Clatworthy
versionedfile.py code cleanups
288
        :param version_id: The name of the version to lookup
1666.1.6 by Robert Collins
Make knit the default format.
289
        """
290
        raise NotImplementedError(self.get_sha1)
291
2520.4.89 by Aaron Bentley
Add get_sha1s to weaves
292
    def get_sha1s(self, version_ids):
293
        """Get the stored sha1 sums for the given revisions.
294
295
        :param version_ids: The names of the versions to lookup
296
        :return: a list of sha1s in order according to the version_ids
297
        """
2831.7.1 by Ian Clatworthy
versionedfile.py code cleanups
298
        raise NotImplementedError(self.get_sha1s)
2520.4.89 by Aaron Bentley
Add get_sha1s to weaves
299
1563.2.15 by Robert Collins
remove the weavestore assumptions about the number and nature of files it manages.
300
    def get_suffixes(self):
301
        """Return the file suffixes associated with this versioned file."""
302
        raise NotImplementedError(self.get_suffixes)
303
    
1563.2.1 by Robert Collins
Merge in a variation of the versionedfile api from versioned-file.
304
    def get_text(self, version_id):
305
        """Return version contents as a text string.
306
307
        Raises RevisionNotPresent if version is not present in
308
        file history.
309
        """
310
        return ''.join(self.get_lines(version_id))
311
    get_string = get_text
312
1756.2.1 by Aaron Bentley
Implement get_texts
313
    def get_texts(self, version_ids):
314
        """Return the texts of listed versions as a list of strings.
315
316
        Raises RevisionNotPresent if version is not present in
317
        file history.
318
        """
319
        return [''.join(self.get_lines(v)) for v in version_ids]
320
1563.2.1 by Robert Collins
Merge in a variation of the versionedfile api from versioned-file.
321
    def get_lines(self, version_id):
322
        """Return version contents as a sequence of lines.
323
324
        Raises RevisionNotPresent if version is not present in
325
        file history.
326
        """
327
        raise NotImplementedError(self.get_lines)
328
2520.4.90 by Aaron Bentley
Handle \r terminated lines in Weaves properly
329
    def _get_lf_split_line_list(self, version_ids):
330
        return [StringIO(t).readlines() for t in self.get_texts(version_ids)]
2520.4.3 by Aaron Bentley
Implement plain strategy for extracting and installing multiparent diffs
331
2530.1.1 by Aaron Bentley
Make topological sorting optional for get_ancestry
332
    def get_ancestry(self, version_ids, topo_sorted=True):
1563.2.1 by Robert Collins
Merge in a variation of the versionedfile api from versioned-file.
333
        """Return a list of all ancestors of given version(s). This
334
        will not include the null revision.
335
2490.2.32 by Aaron Bentley
Merge of not-sorting-ancestry branch
336
        This list will not be topologically sorted if topo_sorted=False is
337
        passed.
2530.1.1 by Aaron Bentley
Make topological sorting optional for get_ancestry
338
1563.2.1 by Robert Collins
Merge in a variation of the versionedfile api from versioned-file.
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)
344
        
1594.2.8 by Robert Collins
add ghost aware apis to knits.
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.
348
349
        Must raise RevisionNotPresent if any of the given versions are
350
        not present in file history.
351
        
352
        Ghosts that are known about will be included in ancestry list,
353
        but are not explicitly marked.
354
        """
355
        raise NotImplementedError(self.get_ancestry_with_ghosts)
356
        
1684.3.1 by Robert Collins
Fix versioned file joins with empty targets.
357
    def get_graph(self, version_ids=None):
358
        """Return a graph from the versioned file. 
1594.2.8 by Robert Collins
add ghost aware apis to knits.
359
        
360
        Ghosts are not listed or referenced in the graph.
1684.3.1 by Robert Collins
Fix versioned file joins with empty targets.
361
        :param version_ids: Versions to select.
1759.2.1 by Jelmer Vernooij
Fix some types (found using aspell).
362
                            None means retrieve all versions.
1594.2.8 by Robert Collins
add ghost aware apis to knits.
363
        """
2592.3.43 by Robert Collins
A knit iter_parents API.
364
        if version_ids is None:
365
            return dict(self.iter_parents(self.versions()))
1563.2.13 by Robert Collins
InterVersionedFile implemented.
366
        result = {}
2858.2.1 by Martin Pool
Remove most calls to safe_file_id and safe_revision_id.
367
        pending = set(version_ids)
2592.3.43 by Robert Collins
A knit iter_parents API.
368
        while pending:
369
            this_iteration = pending
370
            pending = set()
371
            for version, parents in self.iter_parents(this_iteration):
1684.3.1 by Robert Collins
Fix versioned file joins with empty targets.
372
                result[version] = parents
2652.1.1 by John Arbash Meinel
Avoid set.difference_update(other) because it is slow when other is big.
373
                for parent in parents:
374
                    if parent in result:
375
                        continue
376
                    pending.add(parent)
1563.2.13 by Robert Collins
InterVersionedFile implemented.
377
        return result
1563.2.1 by Robert Collins
Merge in a variation of the versionedfile api from versioned-file.
378
3287.6.7 by Robert Collins
* ``VersionedFile.get_graph_with_ghosts`` is deprecated, with no
379
    @deprecated_method(one_four)
1594.2.8 by Robert Collins
add ghost aware apis to knits.
380
    def get_graph_with_ghosts(self):
381
        """Return a graph for the entire versioned file.
382
        
383
        Ghosts are referenced in parents list but are not
384
        explicitly listed.
385
        """
386
        raise NotImplementedError(self.get_graph_with_ghosts)
387
3287.5.1 by Robert Collins
Add VersionedFile.get_parent_map.
388
    def get_parent_map(self, version_ids):
389
        """Get a map of the parents of version_ids.
390
391
        :param version_ids: The version ids to look up parents for.
392
        :return: A mapping from version id to parents.
393
        """
394
        raise NotImplementedError(self.get_parent_map)
395
3287.5.4 by Robert Collins
Bump the deprecation to 1.4.
396
    @deprecated_method(one_four)
1563.2.1 by Robert Collins
Merge in a variation of the versionedfile api from versioned-file.
397
    def get_parents(self, version_id):
398
        """Return version names for parents of a version.
399
400
        Must raise RevisionNotPresent if version is not present in
401
        file history.
402
        """
3287.5.1 by Robert Collins
Add VersionedFile.get_parent_map.
403
        try:
404
            all = self.get_parent_map([version_id])[version_id]
405
        except KeyError:
406
            raise errors.RevisionNotPresent(version_id, self)
407
        result = []
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)
412
        return result
1563.2.1 by Robert Collins
Merge in a variation of the versionedfile api from versioned-file.
413
1594.2.8 by Robert Collins
add ghost aware apis to knits.
414
    def get_parents_with_ghosts(self, version_id):
415
        """Return version names for parents of version_id.
416
417
        Will raise RevisionNotPresent if version_id is not present
418
        in the history.
419
420
        Ghosts that are known about will be included in the parent list,
421
        but are not explicitly marked.
422
        """
3287.5.1 by Robert Collins
Add VersionedFile.get_parent_map.
423
        try:
424
            return list(self.get_parent_map([version_id])[version_id])
425
        except KeyError:
426
            raise errors.RevisionNotPresent(version_id, self)
1594.2.8 by Robert Collins
add ghost aware apis to knits.
427
1563.2.1 by Robert Collins
Merge in a variation of the versionedfile api from versioned-file.
428
    def annotate_iter(self, version_id):
429
        """Yield list of (version-id, line) pairs for the specified
430
        version.
431
2831.7.1 by Ian Clatworthy
versionedfile.py code cleanups
432
        Must raise RevisionNotPresent if the given version is
1563.2.1 by Robert Collins
Merge in a variation of the versionedfile api from versioned-file.
433
        not present in file history.
434
        """
435
        raise NotImplementedError(self.annotate_iter)
436
437
    def annotate(self, version_id):
438
        return list(self.annotate_iter(version_id))
439
1563.2.31 by Robert Collins
Convert Knit repositories to use knits.
440
    def join(self, other, pb=None, msg=None, version_ids=None,
441
             ignore_missing=False):
1563.2.1 by Robert Collins
Merge in a variation of the versionedfile api from versioned-file.
442
        """Integrate versions from other into this versioned file.
443
444
        If version_ids is None all versions from other should be
445
        incorporated into this versioned file.
446
447
        Must raise RevisionNotPresent if any of the specified versions
2831.7.1 by Ian Clatworthy
versionedfile.py code cleanups
448
        are not present in the other file's history unless ignore_missing
449
        is supplied in which case they are silently skipped.
1563.2.31 by Robert Collins
Convert Knit repositories to use knits.
450
        """
1594.2.23 by Robert Collins
Test versioned file storage handling of clean/dirty status for accessed versioned files.
451
        self._check_write_ok()
1563.2.31 by Robert Collins
Convert Knit repositories to use knits.
452
        return InterVersionedFile.get(other, self).join(
453
            pb,
454
            msg,
455
            version_ids,
456
            ignore_missing)
1563.2.1 by Robert Collins
Merge in a variation of the versionedfile api from versioned-file.
457
2975.3.2 by Robert Collins
Review feedback - document the API change and improve readability in pack's _do_copy_nodes.
458
    def iter_lines_added_or_present_in_versions(self, version_ids=None,
2039.1.1 by Aaron Bentley
Clean up progress properly when interrupted during fetch (#54000)
459
                                                pb=None):
1594.2.6 by Robert Collins
Introduce a api specifically for looking at lines in some versions of the inventory, for fileid_involved.
460
        """Iterate over the lines in the versioned file from version_ids.
461
2975.3.2 by Robert Collins
Review feedback - document the API change and improve readability in pack's _do_copy_nodes.
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).
465
466
        Ordering of results is in whatever order is most suitable for the
467
        underlying storage format.
1594.2.6 by Robert Collins
Introduce a api specifically for looking at lines in some versions of the inventory, for fileid_involved.
468
2039.1.1 by Aaron Bentley
Clean up progress properly when interrupted during fetch (#54000)
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
471
        is an iterator).
472
1594.2.6 by Robert Collins
Introduce a api specifically for looking at lines in some versions of the inventory, for fileid_involved.
473
        NOTES: Lines are normalised: they will all have \n terminators.
474
               Lines are returned in arbitrary order.
2975.3.2 by Robert Collins
Review feedback - document the API change and improve readability in pack's _do_copy_nodes.
475
476
        :return: An iterator over (line, version_id).
1594.2.6 by Robert Collins
Introduce a api specifically for looking at lines in some versions of the inventory, for fileid_involved.
477
        """
478
        raise NotImplementedError(self.iter_lines_added_or_present_in_versions)
479
2592.3.43 by Robert Collins
A knit iter_parents API.
480
    def iter_parents(self, version_ids):
481
        """Iterate through the parents for many version ids.
482
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.
488
        """
3287.5.2 by Robert Collins
Deprecate VersionedFile.get_parents, breaking pulling from a ghost containing knit or pack repository to weaves, which improves correctness and allows simplification of core code.
489
        return self.get_parent_map(version_ids).iteritems()
2592.3.43 by Robert Collins
A knit iter_parents API.
490
1594.2.21 by Robert Collins
Teach versioned files to prevent mutation after finishing.
491
    def transaction_finished(self):
492
        """The transaction that this file was opened in has finished.
493
494
        This records self.finished = True and should cause all mutating
495
        operations to error.
496
        """
497
        self.finished = True
498
1551.6.15 by Aaron Bentley
Moved plan_merge into Weave
499
    def plan_merge(self, ver_a, ver_b):
1563.2.1 by Robert Collins
Merge in a variation of the versionedfile api from versioned-file.
500
        """Return pseudo-annotation indicating how the two versions merge.
501
502
        This is computed between versions a and b and their common
503
        base.
504
505
        Weave lines present in none of them are skipped entirely.
1664.2.2 by Aaron Bentley
Added legend for plan-merge output
506
507
        Legend:
508
        killed-base Dead in base revision
509
        killed-both Killed in each revision
510
        killed-a    Killed in a
511
        killed-b    Killed in b
512
        unchanged   Alive in both a and b (possibly created in both)
513
        new-a       Created in a
514
        new-b       Created in b
1664.2.5 by Aaron Bentley
Update plan-merge legend
515
        ghost-a     Killed in a, unborn in b    
516
        ghost-b     Killed in b, unborn in a
1664.2.2 by Aaron Bentley
Added legend for plan-merge output
517
        irrelevant  Not in either revision
1563.2.1 by Robert Collins
Merge in a variation of the versionedfile api from versioned-file.
518
        """
1551.6.15 by Aaron Bentley
Moved plan_merge into Weave
519
        raise NotImplementedError(VersionedFile.plan_merge)
520
        
1996.3.7 by John Arbash Meinel
lazy import versionedfile, late-load bzrlib.merge
521
    def weave_merge(self, plan, a_marker=TextMerge.A_MARKER,
1551.6.14 by Aaron Bentley
Tweaks from merge review
522
                    b_marker=TextMerge.B_MARKER):
1551.6.12 by Aaron Bentley
Indicate conflicts from merge_lines, insead of guessing
523
        return PlanWeaveMerge(plan, a_marker, b_marker).merge_lines()[0]
1551.6.10 by Aaron Bentley
Renamed WeaveMerge to PlanMerge, added plan method, created planless WeaveMerge
524
1664.2.7 by Aaron Bentley
Merge bzr.dev
525
3062.1.9 by Aaron Bentley
Move PlanMerge into merge and _PlanMergeVersionedFile into versionedfile
526
class _PlanMergeVersionedFile(object):
527
    """A VersionedFile for uncommitted and committed texts.
528
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.
533
    """
534
535
    def __init__(self, file_id, fallback_versionedfiles=None):
536
        """Constuctor
537
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.
542
        """
543
        self._file_id = file_id
544
        if fallback_versionedfiles is None:
545
            self.fallback_versionedfiles = []
546
        else:
547
            self.fallback_versionedfiles = fallback_versionedfiles
548
        self._parents = {}
549
        self._lines = {}
550
3062.2.3 by Aaron Bentley
Sync up with bzr.dev API changes
551
    def plan_merge(self, ver_a, ver_b, base=None):
3062.1.13 by Aaron Bentley
Make _PlanMerge an implementation detail of _PlanMergeVersionedFile
552
        """See VersionedFile.plan_merge"""
3144.3.7 by Aaron Bentley
Update from review
553
        from bzrlib.merge import _PlanMerge
3062.2.3 by Aaron Bentley
Sync up with bzr.dev API changes
554
        if base is None:
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)
559
3144.3.1 by Aaron Bentley
Implement LCA merge, with problematic conflict markers
560
    def plan_lca_merge(self, ver_a, ver_b, base=None):
3144.3.7 by Aaron Bentley
Update from review
561
        from bzrlib.merge import _PlanLCAMerge
3144.3.1 by Aaron Bentley
Implement LCA merge, with problematic conflict markers
562
        graph = self._get_graph()
563
        new_plan = _PlanLCAMerge(ver_a, ver_b, self, graph).plan_merge()
564
        if base is None:
565
            return new_plan
566
        old_plan = _PlanLCAMerge(ver_a, base, self, graph).plan_merge()
567
        return _PlanLCAMerge._subtract_plans(list(old_plan), list(new_plan))
3062.1.13 by Aaron Bentley
Make _PlanMerge an implementation detail of _PlanMergeVersionedFile
568
3062.1.9 by Aaron Bentley
Move PlanMerge into merge and _PlanMergeVersionedFile into versionedfile
569
    def add_lines(self, version_id, parents, lines):
570
        """See VersionedFile.add_lines
571
572
        Lines are added locally, not fallback versionedfiles.  Also, ghosts are
573
        permitted.  Only reserved ids are permitted.
574
        """
575
        if not revision.is_reserved_id(version_id):
576
            raise ValueError('Only reserved ids may be used')
577
        if parents is None:
578
            raise ValueError('Parents may not be None')
579
        if lines is None:
580
            raise ValueError('Lines may not be None')
3287.5.2 by Robert Collins
Deprecate VersionedFile.get_parents, breaking pulling from a ghost containing knit or pack repository to weaves, which improves correctness and allows simplification of core code.
581
        self._parents[version_id] = tuple(parents)
3062.1.9 by Aaron Bentley
Move PlanMerge into merge and _PlanMergeVersionedFile into versionedfile
582
        self._lines[version_id] = lines
583
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:
588
            return lines
589
        for versionedfile in self.fallback_versionedfiles:
590
            try:
591
                return versionedfile.get_lines(version_id)
592
            except errors.RevisionNotPresent:
593
                continue
594
        else:
595
            raise errors.RevisionNotPresent(version_id, self._file_id)
596
3062.1.14 by Aaron Bentley
Use topo_sorted=False with get_ancestry
597
    def get_ancestry(self, version_id, topo_sorted=False):
3062.1.9 by Aaron Bentley
Move PlanMerge into merge and _PlanMergeVersionedFile into versionedfile
598
        """See VersionedFile.get_ancestry.
599
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.
604
605
        Also note that the results of this version are never topologically
606
        sorted, and are a set.
607
        """
3062.1.14 by Aaron Bentley
Use topo_sorted=False with get_ancestry
608
        if topo_sorted:
609
            raise ValueError('This implementation does not provide sorting')
3062.1.9 by Aaron Bentley
Move PlanMerge into merge and _PlanMergeVersionedFile into versionedfile
610
        parents = self._parents.get(version_id)
611
        if parents is None:
612
            for vf in self.fallback_versionedfiles:
613
                try:
3062.1.14 by Aaron Bentley
Use topo_sorted=False with get_ancestry
614
                    return vf.get_ancestry(version_id, topo_sorted=False)
3062.1.9 by Aaron Bentley
Move PlanMerge into merge and _PlanMergeVersionedFile into versionedfile
615
                except errors.RevisionNotPresent:
616
                    continue
617
            else:
618
                raise errors.RevisionNotPresent(version_id, self._file_id)
619
        ancestry = set([version_id])
620
        for parent in parents:
3062.1.14 by Aaron Bentley
Use topo_sorted=False with get_ancestry
621
            ancestry.update(self.get_ancestry(parent, topo_sorted=False))
3062.1.9 by Aaron Bentley
Move PlanMerge into merge and _PlanMergeVersionedFile into versionedfile
622
        return ancestry
623
3287.5.2 by Robert Collins
Deprecate VersionedFile.get_parents, breaking pulling from a ghost containing knit or pack repository to weaves, which improves correctness and allows simplification of core code.
624
    def get_parent_map(self, version_ids):
625
        """See VersionedFile.get_parent_map"""
626
        result = {}
627
        pending = set(version_ids)
628
        for key in version_ids:
629
            try:
630
                result[key] = self._parents[key]
631
            except KeyError:
632
                pass
633
        pending = pending - set(result.keys())
3062.1.9 by Aaron Bentley
Move PlanMerge into merge and _PlanMergeVersionedFile into versionedfile
634
        for versionedfile in self.fallback_versionedfiles:
3287.5.2 by Robert Collins
Deprecate VersionedFile.get_parents, breaking pulling from a ghost containing knit or pack repository to weaves, which improves correctness and allows simplification of core code.
635
            parents = versionedfile.get_parent_map(pending)
636
            result.update(parents)
637
            pending = pending - set(parents.keys())
638
            if not pending:
639
                return result
640
        return result
3062.1.9 by Aaron Bentley
Move PlanMerge into merge and _PlanMergeVersionedFile into versionedfile
641
3144.3.1 by Aaron Bentley
Implement LCA merge, with problematic conflict markers
642
    def _get_graph(self):
3144.3.7 by Aaron Bentley
Update from review
643
        from bzrlib.graph import (
644
            DictParentsProvider,
645
            Graph,
646
            _StackedParentsProvider,
647
            )
648
        from bzrlib.repofmt.knitrepo import _KnitParentsProvider
3144.3.1 by Aaron Bentley
Implement LCA merge, with problematic conflict markers
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))
653
3062.1.9 by Aaron Bentley
Move PlanMerge into merge and _PlanMergeVersionedFile into versionedfile
654
1551.6.10 by Aaron Bentley
Renamed WeaveMerge to PlanMerge, added plan method, created planless WeaveMerge
655
class PlanWeaveMerge(TextMerge):
1551.6.13 by Aaron Bentley
Cleanup
656
    """Weave merge that takes a plan as its input.
657
    
1551.6.14 by Aaron Bentley
Tweaks from merge review
658
    This exists so that VersionedFile.plan_merge is implementable.
659
    Most callers will want to use WeaveMerge instead.
1551.6.13 by Aaron Bentley
Cleanup
660
    """
661
1551.6.14 by Aaron Bentley
Tweaks from merge review
662
    def __init__(self, plan, a_marker=TextMerge.A_MARKER,
663
                 b_marker=TextMerge.B_MARKER):
1551.6.10 by Aaron Bentley
Renamed WeaveMerge to PlanMerge, added plan method, created planless WeaveMerge
664
        TextMerge.__init__(self, a_marker, b_marker)
665
        self.plan = plan
666
1551.6.7 by Aaron Bentley
Implemented two-way merge, refactored weave merge
667
    def _merge_struct(self):
1563.2.1 by Robert Collins
Merge in a variation of the versionedfile api from versioned-file.
668
        lines_a = []
669
        lines_b = []
670
        ch_a = ch_b = False
1664.2.8 by Aaron Bentley
Fix WeaveMerge when plan doesn't end with unchanged lines
671
672
        def outstanding_struct():
673
            if not lines_a and not lines_b:
674
                return
675
            elif ch_a and not ch_b:
676
                # one-sided change:
677
                yield(lines_a,)
678
            elif ch_b and not ch_a:
679
                yield (lines_b,)
680
            elif lines_a == lines_b:
681
                yield(lines_a,)
682
            else:
683
                yield (lines_a, lines_b)
1551.6.13 by Aaron Bentley
Cleanup
684
       
1616.1.18 by Martin Pool
(weave-merge) don't treat killed-both lines as points of agreement;
685
        # We previously considered either 'unchanged' or 'killed-both' lines
686
        # to be possible places to resynchronize.  However, assuming agreement
1759.2.1 by Jelmer Vernooij
Fix some types (found using aspell).
687
        # on killed-both lines may be too aggressive. -- mbp 20060324
1551.6.7 by Aaron Bentley
Implemented two-way merge, refactored weave merge
688
        for state, line in self.plan:
1616.1.18 by Martin Pool
(weave-merge) don't treat killed-both lines as points of agreement;
689
            if state == 'unchanged':
1563.2.1 by Robert Collins
Merge in a variation of the versionedfile api from versioned-file.
690
                # resync and flush queued conflicts changes if any
1664.2.8 by Aaron Bentley
Fix WeaveMerge when plan doesn't end with unchanged lines
691
                for struct in outstanding_struct():
692
                    yield struct
1551.6.11 by Aaron Bentley
Switched TextMerge_lines to work on a list
693
                lines_a = []
694
                lines_b = []
1563.2.1 by Robert Collins
Merge in a variation of the versionedfile api from versioned-file.
695
                ch_a = ch_b = False
696
                
697
            if state == 'unchanged':
698
                if line:
1551.6.5 by Aaron Bentley
Got weave merge producing structural output
699
                    yield ([line],)
1563.2.1 by Robert Collins
Merge in a variation of the versionedfile api from versioned-file.
700
            elif state == 'killed-a':
701
                ch_a = True
702
                lines_b.append(line)
703
            elif state == 'killed-b':
704
                ch_b = True
705
                lines_a.append(line)
706
            elif state == 'new-a':
707
                ch_a = True
708
                lines_a.append(line)
709
            elif state == 'new-b':
710
                ch_b = True
711
                lines_b.append(line)
3144.3.2 by Aaron Bentley
Get conflict handling working
712
            elif state == 'conflicted-a':
713
                ch_b = ch_a = True
714
                lines_a.append(line)
715
            elif state == 'conflicted-b':
716
                ch_b = ch_a = True
717
                lines_b.append(line)
1563.2.1 by Robert Collins
Merge in a variation of the versionedfile api from versioned-file.
718
            else:
1551.6.6 by Aaron Bentley
Cleanup
719
                assert state in ('irrelevant', 'ghost-a', 'ghost-b', 
720
                                 'killed-base', 'killed-both'), state
1664.2.8 by Aaron Bentley
Fix WeaveMerge when plan doesn't end with unchanged lines
721
        for struct in outstanding_struct():
722
            yield struct
1563.2.12 by Robert Collins
Checkpointing: created InterObject to factor out common inter object worker code, added InterVersionedFile and tests to allow making join work between any versionedfile.
723
1664.2.14 by Aaron Bentley
spacing fix
724
1551.6.10 by Aaron Bentley
Renamed WeaveMerge to PlanMerge, added plan method, created planless WeaveMerge
725
class WeaveMerge(PlanWeaveMerge):
2831.7.1 by Ian Clatworthy
versionedfile.py code cleanups
726
    """Weave merge that takes a VersionedFile and two versions as its input."""
1551.6.13 by Aaron Bentley
Cleanup
727
1551.6.10 by Aaron Bentley
Renamed WeaveMerge to PlanMerge, added plan method, created planless WeaveMerge
728
    def __init__(self, versionedfile, ver_a, ver_b, 
1551.6.14 by Aaron Bentley
Tweaks from merge review
729
        a_marker=PlanWeaveMerge.A_MARKER, b_marker=PlanWeaveMerge.B_MARKER):
1551.6.15 by Aaron Bentley
Moved plan_merge into Weave
730
        plan = versionedfile.plan_merge(ver_a, ver_b)
1551.6.10 by Aaron Bentley
Renamed WeaveMerge to PlanMerge, added plan method, created planless WeaveMerge
731
        PlanWeaveMerge.__init__(self, plan, a_marker, b_marker)
732
733
1563.2.12 by Robert Collins
Checkpointing: created InterObject to factor out common inter object worker code, added InterVersionedFile and tests to allow making join work between any versionedfile.
734
class InterVersionedFile(InterObject):
2831.7.1 by Ian Clatworthy
versionedfile.py code cleanups
735
    """This class represents operations taking place between two VersionedFiles.
1563.2.12 by Robert Collins
Checkpointing: created InterObject to factor out common inter object worker code, added InterVersionedFile and tests to allow making join work between any versionedfile.
736
737
    Its instances have methods like join, and contain
738
    references to the source and target versionedfiles these operations can be 
739
    carried out on.
740
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).
744
    """
745
1910.2.15 by Aaron Bentley
Back out inter.get changes, make optimizers an ordered list
746
    _optimisers = []
1563.2.12 by Robert Collins
Checkpointing: created InterObject to factor out common inter object worker code, added InterVersionedFile and tests to allow making join work between any versionedfile.
747
    """The available optimised InterVersionedFile types."""
748
1563.2.31 by Robert Collins
Convert Knit repositories to use knits.
749
    def join(self, pb=None, msg=None, version_ids=None, ignore_missing=False):
1563.2.13 by Robert Collins
InterVersionedFile implemented.
750
        """Integrate versions from self.source into self.target.
751
752
        If version_ids is None all versions from source should be
753
        incorporated into this versioned file.
754
755
        Must raise RevisionNotPresent if any of the specified versions
2831.7.1 by Ian Clatworthy
versionedfile.py code cleanups
756
        are not present in the other file's history unless ignore_missing is 
757
        supplied in which case they are silently skipped.
1563.2.13 by Robert Collins
InterVersionedFile implemented.
758
        """
3316.2.1 by Robert Collins
* ``VersionedFile.create_empty`` is removed. This method presupposed a
759
        target = self.target
1684.3.2 by Robert Collins
Factor out version_ids-to-join selection in InterVersionedfile.
760
        version_ids = self._get_source_version_ids(version_ids, ignore_missing)
3287.6.1 by Robert Collins
* ``VersionedFile.get_graph`` is deprecated, with no replacement method.
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())
1563.2.37 by Robert Collins
Merge in nested progress bars
767
        pb = ui.ui_factory.nested_progress_bar()
1596.2.38 by Robert Collins
rollback from using deltas to using fulltexts - deltas need more work to be ready.
768
        parent_texts = {}
1563.2.37 by Robert Collins
Merge in nested progress bars
769
        try:
1596.2.28 by Robert Collins
more knit profile based tuning.
770
            # TODO for incremental cross-format work:
1596.2.27 by Robert Collins
Note potential improvements in knit adds.
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
1596.2.38 by Robert Collins
rollback from using deltas to using fulltexts - deltas need more work to be ready.
779
            # 
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))
2851.4.3 by Ian Clatworthy
fix up plain-to-annotated knit conversion
783
            total = len(order)
1563.2.37 by Robert Collins
Merge in nested progress bars
784
            for index, version in enumerate(order):
2851.4.3 by Ian Clatworthy
fix up plain-to-annotated knit conversion
785
                pb.update('Converting versioned data', index, total)
3316.2.1 by Robert Collins
* ``VersionedFile.create_empty`` is removed. This method presupposed a
786
                if version in target:
787
                    continue
2776.1.3 by Robert Collins
Missed bundles in the return value conversion of vf.add_lines.
788
                _, _, parent_text = target.add_lines(version,
3287.5.2 by Robert Collins
Deprecate VersionedFile.get_parents, breaking pulling from a ghost containing knit or pack repository to weaves, which improves correctness and allows simplification of core code.
789
                                               parent_map[version],
1596.2.38 by Robert Collins
rollback from using deltas to using fulltexts - deltas need more work to be ready.
790
                                               self.source.get_lines(version),
791
                                               parent_texts=parent_texts)
792
                parent_texts[version] = parent_text
3316.2.1 by Robert Collins
* ``VersionedFile.create_empty`` is removed. This method presupposed a
793
            return total
1563.2.37 by Robert Collins
Merge in nested progress bars
794
        finally:
795
            pb.finished()
1563.2.13 by Robert Collins
InterVersionedFile implemented.
796
1684.3.2 by Robert Collins
Factor out version_ids-to-join selection in InterVersionedfile.
797
    def _get_source_version_ids(self, version_ids, ignore_missing):
798
        """Determine the version ids to be used from self.source.
799
800
        :param version_ids: The caller-supplied version ids to check. (None 
1684.3.3 by Robert Collins
Add a special cased weaves to knit converter.
801
                            for all). If None is in version_ids, it is stripped.
1684.3.2 by Robert Collins
Factor out version_ids-to-join selection in InterVersionedfile.
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.
806
        """
807
        if version_ids is None:
1684.3.3 by Robert Collins
Add a special cased weaves to knit converter.
808
            # None cannot be in source.versions
1684.3.2 by Robert Collins
Factor out version_ids-to-join selection in InterVersionedfile.
809
            return set(self.source.versions())
810
        else:
811
            if ignore_missing:
812
                return set(self.source.versions()).intersection(set(version_ids))
813
            else:
814
                new_version_ids = set()
815
                for version in version_ids:
1684.3.3 by Robert Collins
Add a special cased weaves to knit converter.
816
                    if version is None:
817
                        continue
1684.3.2 by Robert Collins
Factor out version_ids-to-join selection in InterVersionedfile.
818
                    if not self.source.has_version(version):
819
                        raise errors.RevisionNotPresent(version, str(self.source))
820
                    else:
821
                        new_version_ids.add(version)
822
                return new_version_ids