/brz/remove-bazaar

To get this branch, use:
bzr branch http://gegoxaren.bato24.eu/bzr/brz/remove-bazaar
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
2229.2.1 by Aaron Bentley
Reject reserved ids in versiondfile, tree, branch and repository
58
    @staticmethod
2229.2.3 by Aaron Bentley
change reserved_id to is_reserved_id, add check_not_reserved for DRY
59
    def check_not_reserved_id(version_id):
60
        revision.check_not_reserved_id(version_id)
2229.2.1 by Aaron Bentley
Reject reserved ids in versiondfile, tree, branch and repository
61
1563.2.15 by Robert Collins
remove the weavestore assumptions about the number and nature of files it manages.
62
    def copy_to(self, name, transport):
63
        """Copy this versioned file to name on transport."""
64
        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
65
1563.2.1 by Robert Collins
Merge in a variation of the versionedfile api from versioned-file.
66
    def versions(self):
67
        """Return a unsorted list of versions."""
68
        raise NotImplementedError(self.versions)
69
3287.6.5 by Robert Collins
Deprecate VersionedFile.has_ghost.
70
    @deprecated_method(one_four)
1594.2.8 by Robert Collins
add ghost aware apis to knits.
71
    def has_ghost(self, version_id):
72
        """Returns whether version is present as a ghost."""
73
        raise NotImplementedError(self.has_ghost)
74
1563.2.1 by Robert Collins
Merge in a variation of the versionedfile api from versioned-file.
75
    def has_version(self, version_id):
76
        """Returns whether version is present."""
77
        raise NotImplementedError(self.has_version)
78
2520.4.140 by Aaron Bentley
Use matching blocks from mpdiff for knit delta creation
79
    def add_lines(self, version_id, parents, lines, parent_texts=None,
2805.6.7 by Robert Collins
Review feedback.
80
        left_matching_blocks=None, nostore_sha=None, random_id=False,
81
        check_content=True):
1563.2.1 by Robert Collins
Merge in a variation of the versionedfile api from versioned-file.
82
        """Add a single text on top of the versioned file.
83
84
        Must raise RevisionAlreadyPresent if the new version is
85
        already present in file history.
86
87
        Must raise RevisionNotPresent if any of the given parents are
1594.2.21 by Robert Collins
Teach versioned files to prevent mutation after finishing.
88
        not present in file history.
2805.6.3 by Robert Collins
* The ``VersionedFile`` interface no longer protects against misuse when
89
90
        :param lines: A list of lines. Each line must be a bytestring. And all
91
            of them except the last must be terminated with \n and contain no
92
            other \n's. The last line may either contain no \n's or a single
93
            terminated \n. If the lines list does meet this constraint the add
94
            routine may error or may succeed - but you will be unable to read
95
            the data back accurately. (Checking the lines have been split
2805.6.7 by Robert Collins
Review feedback.
96
            correctly is expensive and extremely unlikely to catch bugs so it
97
            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.
98
        :param parent_texts: An optional dictionary containing the opaque 
2805.6.3 by Robert Collins
* The ``VersionedFile`` interface no longer protects against misuse when
99
            representations of some or all of the parents of version_id to
100
            allow delta optimisations.  VERY IMPORTANT: the texts must be those
101
            returned by add_lines or data corruption can be caused.
2520.4.148 by Aaron Bentley
Updates from review
102
        :param left_matching_blocks: a hint about which areas are common
103
            between the text and its left-hand-parent.  The format is
104
            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.
105
        :param nostore_sha: Raise ExistingContent and do not add the lines to
106
            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.
107
        :param random_id: If True a random id has been selected rather than
108
            an id determined by some deterministic process such as a converter
109
            from a foreign VCS. When True the backend may choose not to check
110
            for uniqueness of the resulting key within the versioned file, so
111
            this should only be done when the result is expected to be unique
112
            anyway.
2805.6.7 by Robert Collins
Review feedback.
113
        :param check_content: If True, the lines supplied are verified to be
114
            bytestrings that are correctly formed lines.
2776.1.1 by Robert Collins
* The ``add_lines`` methods on ``VersionedFile`` implementations has changed
115
        :return: The text sha1, the number of bytes in the text, and an opaque
116
                 representation of the inserted version which can be provided
117
                 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.
118
        """
1594.2.23 by Robert Collins
Test versioned file storage handling of clean/dirty status for accessed versioned files.
119
        self._check_write_ok()
2520.4.140 by Aaron Bentley
Use matching blocks from mpdiff for knit delta creation
120
        return self._add_lines(version_id, parents, lines, parent_texts,
2805.6.7 by Robert Collins
Review feedback.
121
            left_matching_blocks, nostore_sha, random_id, check_content)
1594.2.21 by Robert Collins
Teach versioned files to prevent mutation after finishing.
122
2520.4.140 by Aaron Bentley
Use matching blocks from mpdiff for knit delta creation
123
    def _add_lines(self, version_id, parents, lines, parent_texts,
2805.6.7 by Robert Collins
Review feedback.
124
        left_matching_blocks, nostore_sha, random_id, check_content):
1594.2.21 by Robert Collins
Teach versioned files to prevent mutation after finishing.
125
        """Helper to do the class specific add_lines."""
1563.2.4 by Robert Collins
First cut at including the knit implementation of versioned_file.
126
        raise NotImplementedError(self.add_lines)
1563.2.1 by Robert Collins
Merge in a variation of the versionedfile api from versioned-file.
127
1596.2.32 by Robert Collins
Reduce re-extraction of texts during weave to knit joins by providing a memoisation facility.
128
    def add_lines_with_ghosts(self, version_id, parents, lines,
2805.6.7 by Robert Collins
Review feedback.
129
        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.
130
        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.
131
        """Add lines to the versioned file, allowing ghosts to be present.
132
        
2794.1.1 by Robert Collins
Allow knits to be instructed not to add a text based on a sha, for commit.
133
        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.
134
        """
1594.2.23 by Robert Collins
Test versioned file storage handling of clean/dirty status for accessed versioned files.
135
        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.
136
        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.
137
            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.
138
2794.1.1 by Robert Collins
Allow knits to be instructed not to add a text based on a sha, for commit.
139
    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.
140
        nostore_sha, random_id, check_content, left_matching_blocks):
1594.2.21 by Robert Collins
Teach versioned files to prevent mutation after finishing.
141
        """Helper to do class specific add_lines_with_ghosts."""
1594.2.8 by Robert Collins
add ghost aware apis to knits.
142
        raise NotImplementedError(self.add_lines_with_ghosts)
143
1563.2.19 by Robert Collins
stub out a check for knits.
144
    def check(self, progress_bar=None):
145
        """Check the versioned file for integrity."""
146
        raise NotImplementedError(self.check)
147
1666.1.6 by Robert Collins
Make knit the default format.
148
    def _check_lines_not_unicode(self, lines):
149
        """Check that lines being added to a versioned file are not unicode."""
150
        for line in lines:
151
            if line.__class__ is not str:
152
                raise errors.BzrBadParameterUnicode("lines")
153
154
    def _check_lines_are_lines(self, lines):
155
        """Check that the lines really are full lines without inline EOL."""
156
        for line in lines:
157
            if '\n' in line[:-1]:
158
                raise errors.BzrBadParameterContainsNewline("lines")
159
1863.1.1 by John Arbash Meinel
Allow Versioned files to do caching if explicitly asked, and implement for Knit
160
    def enable_cache(self):
161
        """Tell this versioned file that it should cache any data it reads.
162
        
163
        This is advisory, implementations do not have to support caching.
164
        """
165
        pass
166
    
1563.2.7 by Robert Collins
add versioned file clear_cache entry.
167
    def clear_cache(self):
1863.1.1 by John Arbash Meinel
Allow Versioned files to do caching if explicitly asked, and implement for Knit
168
        """Remove any data cached in the versioned file object.
169
170
        This only needs to be supported if caches are supported
171
        """
172
        pass
1563.2.7 by Robert Collins
add versioned file clear_cache entry.
173
1563.2.5 by Robert Collins
Remove unused transaction references from knit.py and the versionedfile interface.
174
    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.
175
        """Add an identical text to old_version_id as new_version_id.
176
177
        Must raise RevisionNotPresent if the old version or any of the
178
        parents are not present in file history.
179
180
        Must raise RevisionAlreadyPresent if the new version is
181
        already present in file history."""
1594.2.24 by Robert Collins
Make use of the transaction finalisation warning support to implement in-knit caching.
182
        self._check_write_ok()
183
        return self._clone_text(new_version_id, old_version_id, parents)
184
185
    def _clone_text(self, new_version_id, old_version_id, parents):
186
        """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.
187
        raise NotImplementedError(self.clone_text)
188
2535.3.1 by Andrew Bennetts
Add get_format_signature to VersionedFile
189
    def get_format_signature(self):
190
        """Get a text description of the data encoding in this file.
191
        
2831.7.1 by Ian Clatworthy
versionedfile.py code cleanups
192
        :since: 0.90
2535.3.1 by Andrew Bennetts
Add get_format_signature to VersionedFile
193
        """
194
        raise NotImplementedError(self.get_format_signature)
195
2520.4.41 by Aaron Bentley
Accelerate mpdiff generation
196
    def make_mpdiffs(self, version_ids):
2831.7.1 by Ian Clatworthy
versionedfile.py code cleanups
197
        """Create multiparent diffs for specified versions."""
2520.4.41 by Aaron Bentley
Accelerate mpdiff generation
198
        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.
199
        knit_versions.update(version_ids)
200
        parent_map = self.get_parent_map(version_ids)
2520.4.41 by Aaron Bentley
Accelerate mpdiff generation
201
        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.
202
            try:
203
                knit_versions.update(parent_map[version_id])
204
            except KeyError:
205
                raise RevisionNotPresent(version_id, self)
206
        # We need to filter out ghosts, because we can't diff against them.
207
        knit_versions = set(self.get_parent_map(knit_versions).keys())
2520.4.90 by Aaron Bentley
Handle \r terminated lines in Weaves properly
208
        lines = dict(zip(knit_versions,
209
            self._get_lf_split_line_list(knit_versions)))
2520.4.41 by Aaron Bentley
Accelerate mpdiff generation
210
        diffs = []
211
        for version_id in version_ids:
212
            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.
213
            try:
214
                parents = [lines[p] for p in parent_map[version_id] if p in
215
                    knit_versions]
216
            except KeyError:
217
                raise RevisionNotPresent(version_id, self)
2520.4.48 by Aaron Bentley
Support getting blocks from knit deltas with no final EOL
218
            if len(parents) > 0:
219
                left_parent_blocks = self._extract_blocks(version_id,
220
                                                          parents[0], target)
221
            else:
222
                left_parent_blocks = None
2520.4.41 by Aaron Bentley
Accelerate mpdiff generation
223
            diffs.append(multiparent.MultiParent.from_lines(target, parents,
224
                         left_parent_blocks))
225
        return diffs
226
2520.4.48 by Aaron Bentley
Support getting blocks from knit deltas with no final EOL
227
    def _extract_blocks(self, version_id, source, target):
2520.4.41 by Aaron Bentley
Accelerate mpdiff generation
228
        return None
2520.4.3 by Aaron Bentley
Implement plain strategy for extracting and installing multiparent diffs
229
2520.4.61 by Aaron Bentley
Do bulk insertion of records
230
    def add_mpdiffs(self, records):
2831.7.1 by Ian Clatworthy
versionedfile.py code cleanups
231
        """Add mpdiffs to this VersionedFile.
2520.4.126 by Aaron Bentley
Add more docs
232
233
        Records should be iterables of version, parents, expected_sha1,
2831.7.1 by Ian Clatworthy
versionedfile.py code cleanups
234
        mpdiff. mpdiff should be a MultiParent instance.
2520.4.126 by Aaron Bentley
Add more docs
235
        """
2831.7.1 by Ian Clatworthy
versionedfile.py code cleanups
236
        # Does this need to call self._check_write_ok()? (IanC 20070919)
2520.4.61 by Aaron Bentley
Do bulk insertion of records
237
        vf_parents = {}
2520.4.141 by Aaron Bentley
More batch operations adding mpdiffs
238
        mpvf = multiparent.MultiMemoryVersionedFile()
239
        versions = []
240
        for version, parent_ids, expected_sha1, mpdiff in records:
241
            versions.append(version)
242
            mpvf.add_diff(mpdiff, version, parent_ids)
243
        needed_parents = set()
2520.4.142 by Aaron Bentley
Clean up installation of inventory records
244
        for version, parent_ids, expected_sha1, mpdiff in records:
2520.4.141 by Aaron Bentley
More batch operations adding mpdiffs
245
            needed_parents.update(p for p in parent_ids
246
                                  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.
247
        present_parents = set(self.get_parent_map(needed_parents).keys())
248
        for parent_id, lines in zip(present_parents,
249
                                 self._get_lf_split_line_list(present_parents)):
2520.4.141 by Aaron Bentley
More batch operations adding mpdiffs
250
            mpvf.add_version(lines, parent_id, [])
251
        for (version, parent_ids, expected_sha1, mpdiff), lines in\
252
            zip(records, mpvf.get_line_list(versions)):
253
            if len(parent_ids) == 1:
2520.4.140 by Aaron Bentley
Use matching blocks from mpdiff for knit delta creation
254
                left_matching_blocks = list(mpdiff.get_matching_blocks(0,
2520.4.141 by Aaron Bentley
More batch operations adding mpdiffs
255
                    mpvf.get_diff(parent_ids[0]).num_lines()))
2520.4.140 by Aaron Bentley
Use matching blocks from mpdiff for knit delta creation
256
            else:
257
                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.
258
            try:
259
                _, _, version_text = self.add_lines_with_ghosts(version,
260
                    parent_ids, lines, vf_parents,
261
                    left_matching_blocks=left_matching_blocks)
262
            except NotImplementedError:
263
                # The vf can't handle ghosts, so add lines normally, which will
264
                # (reasonably) fail if there are ghosts in the data.
265
                _, _, version_text = self.add_lines(version,
266
                    parent_ids, lines, vf_parents,
267
                    left_matching_blocks=left_matching_blocks)
2520.4.61 by Aaron Bentley
Do bulk insertion of records
268
            vf_parents[version] = version_text
2520.4.142 by Aaron Bentley
Clean up installation of inventory records
269
        for (version, parent_ids, expected_sha1, mpdiff), sha1 in\
270
             zip(records, self.get_sha1s(versions)):
271
            if expected_sha1 != sha1:
2520.4.71 by Aaron Bentley
Update test to accept VersionedFileInvalidChecksum instead of TestamentMismatch
272
                raise errors.VersionedFileInvalidChecksum(version)
2520.4.3 by Aaron Bentley
Implement plain strategy for extracting and installing multiparent diffs
273
1666.1.6 by Robert Collins
Make knit the default format.
274
    def get_sha1(self, version_id):
275
        """Get the stored sha1 sum for the given revision.
276
        
2831.7.1 by Ian Clatworthy
versionedfile.py code cleanups
277
        :param version_id: The name of the version to lookup
1666.1.6 by Robert Collins
Make knit the default format.
278
        """
279
        raise NotImplementedError(self.get_sha1)
280
2520.4.89 by Aaron Bentley
Add get_sha1s to weaves
281
    def get_sha1s(self, version_ids):
282
        """Get the stored sha1 sums for the given revisions.
283
284
        :param version_ids: The names of the versions to lookup
285
        :return: a list of sha1s in order according to the version_ids
286
        """
2831.7.1 by Ian Clatworthy
versionedfile.py code cleanups
287
        raise NotImplementedError(self.get_sha1s)
2520.4.89 by Aaron Bentley
Add get_sha1s to weaves
288
1563.2.1 by Robert Collins
Merge in a variation of the versionedfile api from versioned-file.
289
    def get_text(self, version_id):
290
        """Return version contents as a text string.
291
292
        Raises RevisionNotPresent if version is not present in
293
        file history.
294
        """
295
        return ''.join(self.get_lines(version_id))
296
    get_string = get_text
297
1756.2.1 by Aaron Bentley
Implement get_texts
298
    def get_texts(self, version_ids):
299
        """Return the texts of listed versions as a list of strings.
300
301
        Raises RevisionNotPresent if version is not present in
302
        file history.
303
        """
304
        return [''.join(self.get_lines(v)) for v in version_ids]
305
1563.2.1 by Robert Collins
Merge in a variation of the versionedfile api from versioned-file.
306
    def get_lines(self, version_id):
307
        """Return version contents as a sequence of lines.
308
309
        Raises RevisionNotPresent if version is not present in
310
        file history.
311
        """
312
        raise NotImplementedError(self.get_lines)
313
2520.4.90 by Aaron Bentley
Handle \r terminated lines in Weaves properly
314
    def _get_lf_split_line_list(self, version_ids):
315
        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
316
2530.1.1 by Aaron Bentley
Make topological sorting optional for get_ancestry
317
    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.
318
        """Return a list of all ancestors of given version(s). This
319
        will not include the null revision.
320
2490.2.32 by Aaron Bentley
Merge of not-sorting-ancestry branch
321
        This list will not be topologically sorted if topo_sorted=False is
322
        passed.
2530.1.1 by Aaron Bentley
Make topological sorting optional for get_ancestry
323
1563.2.1 by Robert Collins
Merge in a variation of the versionedfile api from versioned-file.
324
        Must raise RevisionNotPresent if any of the given versions are
325
        not present in file history."""
326
        if isinstance(version_ids, basestring):
327
            version_ids = [version_ids]
328
        raise NotImplementedError(self.get_ancestry)
329
        
1594.2.8 by Robert Collins
add ghost aware apis to knits.
330
    def get_ancestry_with_ghosts(self, version_ids):
331
        """Return a list of all ancestors of given version(s). This
332
        will not include the null revision.
333
334
        Must raise RevisionNotPresent if any of the given versions are
335
        not present in file history.
336
        
337
        Ghosts that are known about will be included in ancestry list,
338
        but are not explicitly marked.
339
        """
340
        raise NotImplementedError(self.get_ancestry_with_ghosts)
3316.2.7 by Robert Collins
Actually deprecated VersionedFile.get_graph.
341
    
342
    @deprecated_method(one_four)
1684.3.1 by Robert Collins
Fix versioned file joins with empty targets.
343
    def get_graph(self, version_ids=None):
344
        """Return a graph from the versioned file. 
1594.2.8 by Robert Collins
add ghost aware apis to knits.
345
        
346
        Ghosts are not listed or referenced in the graph.
1684.3.1 by Robert Collins
Fix versioned file joins with empty targets.
347
        :param version_ids: Versions to select.
1759.2.1 by Jelmer Vernooij
Fix some types (found using aspell).
348
                            None means retrieve all versions.
1594.2.8 by Robert Collins
add ghost aware apis to knits.
349
        """
2592.3.43 by Robert Collins
A knit iter_parents API.
350
        if version_ids is None:
351
            return dict(self.iter_parents(self.versions()))
1563.2.13 by Robert Collins
InterVersionedFile implemented.
352
        result = {}
2858.2.1 by Martin Pool
Remove most calls to safe_file_id and safe_revision_id.
353
        pending = set(version_ids)
2592.3.43 by Robert Collins
A knit iter_parents API.
354
        while pending:
355
            this_iteration = pending
356
            pending = set()
357
            for version, parents in self.iter_parents(this_iteration):
1684.3.1 by Robert Collins
Fix versioned file joins with empty targets.
358
                result[version] = parents
2652.1.1 by John Arbash Meinel
Avoid set.difference_update(other) because it is slow when other is big.
359
                for parent in parents:
360
                    if parent in result:
361
                        continue
362
                    pending.add(parent)
1563.2.13 by Robert Collins
InterVersionedFile implemented.
363
        return result
1563.2.1 by Robert Collins
Merge in a variation of the versionedfile api from versioned-file.
364
3287.6.7 by Robert Collins
* ``VersionedFile.get_graph_with_ghosts`` is deprecated, with no
365
    @deprecated_method(one_four)
1594.2.8 by Robert Collins
add ghost aware apis to knits.
366
    def get_graph_with_ghosts(self):
367
        """Return a graph for the entire versioned file.
368
        
369
        Ghosts are referenced in parents list but are not
370
        explicitly listed.
371
        """
372
        raise NotImplementedError(self.get_graph_with_ghosts)
373
3287.5.1 by Robert Collins
Add VersionedFile.get_parent_map.
374
    def get_parent_map(self, version_ids):
375
        """Get a map of the parents of version_ids.
376
377
        :param version_ids: The version ids to look up parents for.
378
        :return: A mapping from version id to parents.
379
        """
380
        raise NotImplementedError(self.get_parent_map)
381
3287.5.4 by Robert Collins
Bump the deprecation to 1.4.
382
    @deprecated_method(one_four)
1563.2.1 by Robert Collins
Merge in a variation of the versionedfile api from versioned-file.
383
    def get_parents(self, version_id):
384
        """Return version names for parents of a version.
385
386
        Must raise RevisionNotPresent if version is not present in
387
        file history.
388
        """
3287.5.1 by Robert Collins
Add VersionedFile.get_parent_map.
389
        try:
390
            all = self.get_parent_map([version_id])[version_id]
391
        except KeyError:
392
            raise errors.RevisionNotPresent(version_id, self)
393
        result = []
394
        parent_parents = self.get_parent_map(all)
395
        for version_id in all:
396
            if version_id in parent_parents:
397
                result.append(version_id)
398
        return result
1563.2.1 by Robert Collins
Merge in a variation of the versionedfile api from versioned-file.
399
1594.2.8 by Robert Collins
add ghost aware apis to knits.
400
    def get_parents_with_ghosts(self, version_id):
401
        """Return version names for parents of version_id.
402
403
        Will raise RevisionNotPresent if version_id is not present
404
        in the history.
405
406
        Ghosts that are known about will be included in the parent list,
407
        but are not explicitly marked.
408
        """
3287.5.1 by Robert Collins
Add VersionedFile.get_parent_map.
409
        try:
410
            return list(self.get_parent_map([version_id])[version_id])
411
        except KeyError:
412
            raise errors.RevisionNotPresent(version_id, self)
1594.2.8 by Robert Collins
add ghost aware apis to knits.
413
1563.2.1 by Robert Collins
Merge in a variation of the versionedfile api from versioned-file.
414
    def annotate_iter(self, version_id):
415
        """Yield list of (version-id, line) pairs for the specified
416
        version.
417
2831.7.1 by Ian Clatworthy
versionedfile.py code cleanups
418
        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.
419
        not present in file history.
420
        """
421
        raise NotImplementedError(self.annotate_iter)
422
423
    def annotate(self, version_id):
424
        return list(self.annotate_iter(version_id))
425
1563.2.31 by Robert Collins
Convert Knit repositories to use knits.
426
    def join(self, other, pb=None, msg=None, version_ids=None,
427
             ignore_missing=False):
1563.2.1 by Robert Collins
Merge in a variation of the versionedfile api from versioned-file.
428
        """Integrate versions from other into this versioned file.
429
430
        If version_ids is None all versions from other should be
431
        incorporated into this versioned file.
432
433
        Must raise RevisionNotPresent if any of the specified versions
2831.7.1 by Ian Clatworthy
versionedfile.py code cleanups
434
        are not present in the other file's history unless ignore_missing
435
        is supplied in which case they are silently skipped.
1563.2.31 by Robert Collins
Convert Knit repositories to use knits.
436
        """
1594.2.23 by Robert Collins
Test versioned file storage handling of clean/dirty status for accessed versioned files.
437
        self._check_write_ok()
1563.2.31 by Robert Collins
Convert Knit repositories to use knits.
438
        return InterVersionedFile.get(other, self).join(
439
            pb,
440
            msg,
441
            version_ids,
442
            ignore_missing)
1563.2.1 by Robert Collins
Merge in a variation of the versionedfile api from versioned-file.
443
2975.3.2 by Robert Collins
Review feedback - document the API change and improve readability in pack's _do_copy_nodes.
444
    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)
445
                                                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.
446
        """Iterate over the lines in the versioned file from version_ids.
447
2975.3.2 by Robert Collins
Review feedback - document the API change and improve readability in pack's _do_copy_nodes.
448
        This may return lines from other versions. Each item the returned
449
        iterator yields is a tuple of a line and a text version that that line
450
        is present in (not introduced in).
451
452
        Ordering of results is in whatever order is most suitable for the
453
        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.
454
2039.1.1 by Aaron Bentley
Clean up progress properly when interrupted during fetch (#54000)
455
        If a progress bar is supplied, it may be used to indicate progress.
456
        The caller is responsible for cleaning up progress bars (because this
457
        is an iterator).
458
1594.2.6 by Robert Collins
Introduce a api specifically for looking at lines in some versions of the inventory, for fileid_involved.
459
        NOTES: Lines are normalised: they will all have \n terminators.
460
               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.
461
462
        :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.
463
        """
464
        raise NotImplementedError(self.iter_lines_added_or_present_in_versions)
465
2592.3.43 by Robert Collins
A knit iter_parents API.
466
    def iter_parents(self, version_ids):
467
        """Iterate through the parents for many version ids.
468
469
        :param version_ids: An iterable yielding version_ids.
470
        :return: An iterator that yields (version_id, parents). Requested 
471
            version_ids not present in the versioned file are simply skipped.
472
            The order is undefined, allowing for different optimisations in
473
            the underlying implementation.
474
        """
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.
475
        return self.get_parent_map(version_ids).iteritems()
2592.3.43 by Robert Collins
A knit iter_parents API.
476
1551.6.15 by Aaron Bentley
Moved plan_merge into Weave
477
    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.
478
        """Return pseudo-annotation indicating how the two versions merge.
479
480
        This is computed between versions a and b and their common
481
        base.
482
483
        Weave lines present in none of them are skipped entirely.
1664.2.2 by Aaron Bentley
Added legend for plan-merge output
484
485
        Legend:
486
        killed-base Dead in base revision
487
        killed-both Killed in each revision
488
        killed-a    Killed in a
489
        killed-b    Killed in b
490
        unchanged   Alive in both a and b (possibly created in both)
491
        new-a       Created in a
492
        new-b       Created in b
1664.2.5 by Aaron Bentley
Update plan-merge legend
493
        ghost-a     Killed in a, unborn in b    
494
        ghost-b     Killed in b, unborn in a
1664.2.2 by Aaron Bentley
Added legend for plan-merge output
495
        irrelevant  Not in either revision
1563.2.1 by Robert Collins
Merge in a variation of the versionedfile api from versioned-file.
496
        """
1551.6.15 by Aaron Bentley
Moved plan_merge into Weave
497
        raise NotImplementedError(VersionedFile.plan_merge)
498
        
1996.3.7 by John Arbash Meinel
lazy import versionedfile, late-load bzrlib.merge
499
    def weave_merge(self, plan, a_marker=TextMerge.A_MARKER,
1551.6.14 by Aaron Bentley
Tweaks from merge review
500
                    b_marker=TextMerge.B_MARKER):
1551.6.12 by Aaron Bentley
Indicate conflicts from merge_lines, insead of guessing
501
        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
502
1664.2.7 by Aaron Bentley
Merge bzr.dev
503
3062.1.9 by Aaron Bentley
Move PlanMerge into merge and _PlanMergeVersionedFile into versionedfile
504
class _PlanMergeVersionedFile(object):
505
    """A VersionedFile for uncommitted and committed texts.
506
507
    It is intended to allow merges to be planned with working tree texts.
508
    It implements only the small part of the VersionedFile interface used by
509
    PlanMerge.  It falls back to multiple versionedfiles for data not stored in
510
    _PlanMergeVersionedFile itself.
511
    """
512
513
    def __init__(self, file_id, fallback_versionedfiles=None):
514
        """Constuctor
515
516
        :param file_id: Used when raising exceptions.
517
        :param fallback_versionedfiles: If supplied, the set of fallbacks to
518
            use.  Otherwise, _PlanMergeVersionedFile.fallback_versionedfiles
519
            can be appended to later.
520
        """
521
        self._file_id = file_id
522
        if fallback_versionedfiles is None:
523
            self.fallback_versionedfiles = []
524
        else:
525
            self.fallback_versionedfiles = fallback_versionedfiles
526
        self._parents = {}
527
        self._lines = {}
528
3062.2.3 by Aaron Bentley
Sync up with bzr.dev API changes
529
    def plan_merge(self, ver_a, ver_b, base=None):
3062.1.13 by Aaron Bentley
Make _PlanMerge an implementation detail of _PlanMergeVersionedFile
530
        """See VersionedFile.plan_merge"""
3144.3.7 by Aaron Bentley
Update from review
531
        from bzrlib.merge import _PlanMerge
3062.2.3 by Aaron Bentley
Sync up with bzr.dev API changes
532
        if base is None:
533
            return _PlanMerge(ver_a, ver_b, self).plan_merge()
534
        old_plan = list(_PlanMerge(ver_a, base, self).plan_merge())
535
        new_plan = list(_PlanMerge(ver_a, ver_b, self).plan_merge())
536
        return _PlanMerge._subtract_plans(old_plan, new_plan)
537
3144.3.1 by Aaron Bentley
Implement LCA merge, with problematic conflict markers
538
    def plan_lca_merge(self, ver_a, ver_b, base=None):
3144.3.7 by Aaron Bentley
Update from review
539
        from bzrlib.merge import _PlanLCAMerge
3144.3.1 by Aaron Bentley
Implement LCA merge, with problematic conflict markers
540
        graph = self._get_graph()
541
        new_plan = _PlanLCAMerge(ver_a, ver_b, self, graph).plan_merge()
542
        if base is None:
543
            return new_plan
544
        old_plan = _PlanLCAMerge(ver_a, base, self, graph).plan_merge()
545
        return _PlanLCAMerge._subtract_plans(list(old_plan), list(new_plan))
3062.1.13 by Aaron Bentley
Make _PlanMerge an implementation detail of _PlanMergeVersionedFile
546
3062.1.9 by Aaron Bentley
Move PlanMerge into merge and _PlanMergeVersionedFile into versionedfile
547
    def add_lines(self, version_id, parents, lines):
548
        """See VersionedFile.add_lines
549
550
        Lines are added locally, not fallback versionedfiles.  Also, ghosts are
551
        permitted.  Only reserved ids are permitted.
552
        """
553
        if not revision.is_reserved_id(version_id):
554
            raise ValueError('Only reserved ids may be used')
555
        if parents is None:
556
            raise ValueError('Parents may not be None')
557
        if lines is None:
558
            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.
559
        self._parents[version_id] = tuple(parents)
3062.1.9 by Aaron Bentley
Move PlanMerge into merge and _PlanMergeVersionedFile into versionedfile
560
        self._lines[version_id] = lines
561
562
    def get_lines(self, version_id):
563
        """See VersionedFile.get_ancestry"""
564
        lines = self._lines.get(version_id)
565
        if lines is not None:
566
            return lines
567
        for versionedfile in self.fallback_versionedfiles:
568
            try:
569
                return versionedfile.get_lines(version_id)
570
            except errors.RevisionNotPresent:
571
                continue
572
        else:
573
            raise errors.RevisionNotPresent(version_id, self._file_id)
574
3062.1.14 by Aaron Bentley
Use topo_sorted=False with get_ancestry
575
    def get_ancestry(self, version_id, topo_sorted=False):
3062.1.9 by Aaron Bentley
Move PlanMerge into merge and _PlanMergeVersionedFile into versionedfile
576
        """See VersionedFile.get_ancestry.
577
578
        Note that this implementation assumes that if a VersionedFile can
579
        answer get_ancestry at all, it can give an authoritative answer.  In
580
        fact, ghosts can invalidate this assumption.  But it's good enough
581
        99% of the time, and far cheaper/simpler.
582
583
        Also note that the results of this version are never topologically
584
        sorted, and are a set.
585
        """
3062.1.14 by Aaron Bentley
Use topo_sorted=False with get_ancestry
586
        if topo_sorted:
587
            raise ValueError('This implementation does not provide sorting')
3062.1.9 by Aaron Bentley
Move PlanMerge into merge and _PlanMergeVersionedFile into versionedfile
588
        parents = self._parents.get(version_id)
589
        if parents is None:
590
            for vf in self.fallback_versionedfiles:
591
                try:
3062.1.14 by Aaron Bentley
Use topo_sorted=False with get_ancestry
592
                    return vf.get_ancestry(version_id, topo_sorted=False)
3062.1.9 by Aaron Bentley
Move PlanMerge into merge and _PlanMergeVersionedFile into versionedfile
593
                except errors.RevisionNotPresent:
594
                    continue
595
            else:
596
                raise errors.RevisionNotPresent(version_id, self._file_id)
597
        ancestry = set([version_id])
598
        for parent in parents:
3062.1.14 by Aaron Bentley
Use topo_sorted=False with get_ancestry
599
            ancestry.update(self.get_ancestry(parent, topo_sorted=False))
3062.1.9 by Aaron Bentley
Move PlanMerge into merge and _PlanMergeVersionedFile into versionedfile
600
        return ancestry
601
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.
602
    def get_parent_map(self, version_ids):
603
        """See VersionedFile.get_parent_map"""
604
        result = {}
605
        pending = set(version_ids)
606
        for key in version_ids:
607
            try:
608
                result[key] = self._parents[key]
609
            except KeyError:
610
                pass
611
        pending = pending - set(result.keys())
3062.1.9 by Aaron Bentley
Move PlanMerge into merge and _PlanMergeVersionedFile into versionedfile
612
        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.
613
            parents = versionedfile.get_parent_map(pending)
614
            result.update(parents)
615
            pending = pending - set(parents.keys())
616
            if not pending:
617
                return result
618
        return result
3062.1.9 by Aaron Bentley
Move PlanMerge into merge and _PlanMergeVersionedFile into versionedfile
619
3144.3.1 by Aaron Bentley
Implement LCA merge, with problematic conflict markers
620
    def _get_graph(self):
3144.3.7 by Aaron Bentley
Update from review
621
        from bzrlib.graph import (
622
            DictParentsProvider,
623
            Graph,
624
            _StackedParentsProvider,
625
            )
626
        from bzrlib.repofmt.knitrepo import _KnitParentsProvider
3144.3.1 by Aaron Bentley
Implement LCA merge, with problematic conflict markers
627
        parent_providers = [DictParentsProvider(self._parents)]
628
        for vf in self.fallback_versionedfiles:
629
            parent_providers.append(_KnitParentsProvider(vf))
630
        return Graph(_StackedParentsProvider(parent_providers))
631
3062.1.9 by Aaron Bentley
Move PlanMerge into merge and _PlanMergeVersionedFile into versionedfile
632
1551.6.10 by Aaron Bentley
Renamed WeaveMerge to PlanMerge, added plan method, created planless WeaveMerge
633
class PlanWeaveMerge(TextMerge):
1551.6.13 by Aaron Bentley
Cleanup
634
    """Weave merge that takes a plan as its input.
635
    
1551.6.14 by Aaron Bentley
Tweaks from merge review
636
    This exists so that VersionedFile.plan_merge is implementable.
637
    Most callers will want to use WeaveMerge instead.
1551.6.13 by Aaron Bentley
Cleanup
638
    """
639
1551.6.14 by Aaron Bentley
Tweaks from merge review
640
    def __init__(self, plan, a_marker=TextMerge.A_MARKER,
641
                 b_marker=TextMerge.B_MARKER):
1551.6.10 by Aaron Bentley
Renamed WeaveMerge to PlanMerge, added plan method, created planless WeaveMerge
642
        TextMerge.__init__(self, a_marker, b_marker)
643
        self.plan = plan
644
1551.6.7 by Aaron Bentley
Implemented two-way merge, refactored weave merge
645
    def _merge_struct(self):
1563.2.1 by Robert Collins
Merge in a variation of the versionedfile api from versioned-file.
646
        lines_a = []
647
        lines_b = []
648
        ch_a = ch_b = False
1664.2.8 by Aaron Bentley
Fix WeaveMerge when plan doesn't end with unchanged lines
649
650
        def outstanding_struct():
651
            if not lines_a and not lines_b:
652
                return
653
            elif ch_a and not ch_b:
654
                # one-sided change:
655
                yield(lines_a,)
656
            elif ch_b and not ch_a:
657
                yield (lines_b,)
658
            elif lines_a == lines_b:
659
                yield(lines_a,)
660
            else:
661
                yield (lines_a, lines_b)
1551.6.13 by Aaron Bentley
Cleanup
662
       
1616.1.18 by Martin Pool
(weave-merge) don't treat killed-both lines as points of agreement;
663
        # We previously considered either 'unchanged' or 'killed-both' lines
664
        # to be possible places to resynchronize.  However, assuming agreement
1759.2.1 by Jelmer Vernooij
Fix some types (found using aspell).
665
        # on killed-both lines may be too aggressive. -- mbp 20060324
1551.6.7 by Aaron Bentley
Implemented two-way merge, refactored weave merge
666
        for state, line in self.plan:
1616.1.18 by Martin Pool
(weave-merge) don't treat killed-both lines as points of agreement;
667
            if state == 'unchanged':
1563.2.1 by Robert Collins
Merge in a variation of the versionedfile api from versioned-file.
668
                # resync and flush queued conflicts changes if any
1664.2.8 by Aaron Bentley
Fix WeaveMerge when plan doesn't end with unchanged lines
669
                for struct in outstanding_struct():
670
                    yield struct
1551.6.11 by Aaron Bentley
Switched TextMerge_lines to work on a list
671
                lines_a = []
672
                lines_b = []
1563.2.1 by Robert Collins
Merge in a variation of the versionedfile api from versioned-file.
673
                ch_a = ch_b = False
674
                
675
            if state == 'unchanged':
676
                if line:
1551.6.5 by Aaron Bentley
Got weave merge producing structural output
677
                    yield ([line],)
1563.2.1 by Robert Collins
Merge in a variation of the versionedfile api from versioned-file.
678
            elif state == 'killed-a':
679
                ch_a = True
680
                lines_b.append(line)
681
            elif state == 'killed-b':
682
                ch_b = True
683
                lines_a.append(line)
684
            elif state == 'new-a':
685
                ch_a = True
686
                lines_a.append(line)
687
            elif state == 'new-b':
688
                ch_b = True
689
                lines_b.append(line)
3144.3.2 by Aaron Bentley
Get conflict handling working
690
            elif state == 'conflicted-a':
691
                ch_b = ch_a = True
692
                lines_a.append(line)
693
            elif state == 'conflicted-b':
694
                ch_b = ch_a = True
695
                lines_b.append(line)
1563.2.1 by Robert Collins
Merge in a variation of the versionedfile api from versioned-file.
696
            else:
1551.6.6 by Aaron Bentley
Cleanup
697
                assert state in ('irrelevant', 'ghost-a', 'ghost-b', 
698
                                 'killed-base', 'killed-both'), state
1664.2.8 by Aaron Bentley
Fix WeaveMerge when plan doesn't end with unchanged lines
699
        for struct in outstanding_struct():
700
            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.
701
1664.2.14 by Aaron Bentley
spacing fix
702
1551.6.10 by Aaron Bentley
Renamed WeaveMerge to PlanMerge, added plan method, created planless WeaveMerge
703
class WeaveMerge(PlanWeaveMerge):
2831.7.1 by Ian Clatworthy
versionedfile.py code cleanups
704
    """Weave merge that takes a VersionedFile and two versions as its input."""
1551.6.13 by Aaron Bentley
Cleanup
705
1551.6.10 by Aaron Bentley
Renamed WeaveMerge to PlanMerge, added plan method, created planless WeaveMerge
706
    def __init__(self, versionedfile, ver_a, ver_b, 
1551.6.14 by Aaron Bentley
Tweaks from merge review
707
        a_marker=PlanWeaveMerge.A_MARKER, b_marker=PlanWeaveMerge.B_MARKER):
1551.6.15 by Aaron Bentley
Moved plan_merge into Weave
708
        plan = versionedfile.plan_merge(ver_a, ver_b)
1551.6.10 by Aaron Bentley
Renamed WeaveMerge to PlanMerge, added plan method, created planless WeaveMerge
709
        PlanWeaveMerge.__init__(self, plan, a_marker, b_marker)
710
711
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.
712
class InterVersionedFile(InterObject):
2831.7.1 by Ian Clatworthy
versionedfile.py code cleanups
713
    """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.
714
715
    Its instances have methods like join, and contain
716
    references to the source and target versionedfiles these operations can be 
717
    carried out on.
718
719
    Often we will provide convenience methods on 'versionedfile' which carry out
720
    operations with another versionedfile - they will always forward to
721
    InterVersionedFile.get(other).method_name(parameters).
722
    """
723
1910.2.15 by Aaron Bentley
Back out inter.get changes, make optimizers an ordered list
724
    _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.
725
    """The available optimised InterVersionedFile types."""
726
1563.2.31 by Robert Collins
Convert Knit repositories to use knits.
727
    def join(self, pb=None, msg=None, version_ids=None, ignore_missing=False):
1563.2.13 by Robert Collins
InterVersionedFile implemented.
728
        """Integrate versions from self.source into self.target.
729
730
        If version_ids is None all versions from source should be
731
        incorporated into this versioned file.
732
733
        Must raise RevisionNotPresent if any of the specified versions
2831.7.1 by Ian Clatworthy
versionedfile.py code cleanups
734
        are not present in the other file's history unless ignore_missing is 
735
        supplied in which case they are silently skipped.
1563.2.13 by Robert Collins
InterVersionedFile implemented.
736
        """
3316.2.1 by Robert Collins
* ``VersionedFile.create_empty`` is removed. This method presupposed a
737
        target = self.target
1684.3.2 by Robert Collins
Factor out version_ids-to-join selection in InterVersionedfile.
738
        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.
739
        graph = Graph(self.source)
740
        search = graph._make_breadth_first_searcher(version_ids)
741
        transitive_ids = set()
742
        map(transitive_ids.update, list(search))
743
        parent_map = self.source.get_parent_map(transitive_ids)
744
        order = tsort.topo_sort(parent_map.items())
1563.2.37 by Robert Collins
Merge in nested progress bars
745
        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.
746
        parent_texts = {}
1563.2.37 by Robert Collins
Merge in nested progress bars
747
        try:
1596.2.28 by Robert Collins
more knit profile based tuning.
748
            # TODO for incremental cross-format work:
1596.2.27 by Robert Collins
Note potential improvements in knit adds.
749
            # make a versioned file with the following content:
750
            # all revisions we have been asked to join
751
            # all their ancestors that are *not* in target already.
752
            # the immediate parents of the above two sets, with 
753
            # empty parent lists - these versions are in target already
754
            # and the incorrect version data will be ignored.
755
            # TODO: for all ancestors that are present in target already,
756
            # 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.
757
            # 
758
            # TODO: remove parent texts when they are not relevant any more for 
759
            # memory pressure reduction. RBC 20060313
760
            # pb.update('Converting versioned data', 0, len(order))
2851.4.3 by Ian Clatworthy
fix up plain-to-annotated knit conversion
761
            total = len(order)
1563.2.37 by Robert Collins
Merge in nested progress bars
762
            for index, version in enumerate(order):
2851.4.3 by Ian Clatworthy
fix up plain-to-annotated knit conversion
763
                pb.update('Converting versioned data', index, total)
3316.2.1 by Robert Collins
* ``VersionedFile.create_empty`` is removed. This method presupposed a
764
                if version in target:
765
                    continue
2776.1.3 by Robert Collins
Missed bundles in the return value conversion of vf.add_lines.
766
                _, _, 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.
767
                                               parent_map[version],
1596.2.38 by Robert Collins
rollback from using deltas to using fulltexts - deltas need more work to be ready.
768
                                               self.source.get_lines(version),
769
                                               parent_texts=parent_texts)
770
                parent_texts[version] = parent_text
3316.2.1 by Robert Collins
* ``VersionedFile.create_empty`` is removed. This method presupposed a
771
            return total
1563.2.37 by Robert Collins
Merge in nested progress bars
772
        finally:
773
            pb.finished()
1563.2.13 by Robert Collins
InterVersionedFile implemented.
774
1684.3.2 by Robert Collins
Factor out version_ids-to-join selection in InterVersionedfile.
775
    def _get_source_version_ids(self, version_ids, ignore_missing):
776
        """Determine the version ids to be used from self.source.
777
778
        :param version_ids: The caller-supplied version ids to check. (None 
1684.3.3 by Robert Collins
Add a special cased weaves to knit converter.
779
                            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.
780
        :param ignore_missing: if True, remove missing ids from the version 
781
                               list. If False, raise RevisionNotPresent on
782
                               a missing version id.
783
        :return: A set of version ids.
784
        """
785
        if version_ids is None:
1684.3.3 by Robert Collins
Add a special cased weaves to knit converter.
786
            # None cannot be in source.versions
1684.3.2 by Robert Collins
Factor out version_ids-to-join selection in InterVersionedfile.
787
            return set(self.source.versions())
788
        else:
789
            if ignore_missing:
790
                return set(self.source.versions()).intersection(set(version_ids))
791
            else:
792
                new_version_ids = set()
793
                for version in version_ids:
1684.3.3 by Robert Collins
Add a special cased weaves to knit converter.
794
                    if version is None:
795
                        continue
1684.3.2 by Robert Collins
Factor out version_ids-to-join selection in InterVersionedfile.
796
                    if not self.source.has_version(version):
797
                        raise errors.RevisionNotPresent(version, str(self.source))
798
                    else:
799
                        new_version_ids.add(version)
800
                return new_version_ids