~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
    )
33
from bzrlib.transport.memory import MemoryTransport
34
""")
35
2520.4.90 by Aaron Bentley
Handle \r terminated lines in Weaves properly
36
from cStringIO import StringIO
37
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.
38
from bzrlib.inter import InterObject
1551.6.7 by Aaron Bentley
Implemented two-way merge, refactored weave merge
39
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.
40
41
1563.2.1 by Robert Collins
Merge in a variation of the versionedfile api from versioned-file.
42
class VersionedFile(object):
43
    """Versioned text file storage.
44
    
45
    A versioned file manages versions of line-based text files,
46
    keeping track of the originating version for each line.
47
48
    To clients the "lines" of the file are represented as a list of
49
    strings. These strings will typically have terminal newline
50
    characters, but this is not required.  In particular files commonly
51
    do not have a newline at the end of the file.
52
53
    Texts are identified by a version-id string.
54
    """
55
1594.2.23 by Robert Collins
Test versioned file storage handling of clean/dirty status for accessed versioned files.
56
    def __init__(self, access_mode):
1594.2.21 by Robert Collins
Teach versioned files to prevent mutation after finishing.
57
        self.finished = False
1594.2.23 by Robert Collins
Test versioned file storage handling of clean/dirty status for accessed versioned files.
58
        self._access_mode = access_mode
1594.2.21 by Robert Collins
Teach versioned files to prevent mutation after finishing.
59
2229.2.1 by Aaron Bentley
Reject reserved ids in versiondfile, tree, branch and repository
60
    @staticmethod
2229.2.3 by Aaron Bentley
change reserved_id to is_reserved_id, add check_not_reserved for DRY
61
    def check_not_reserved_id(version_id):
62
        revision.check_not_reserved_id(version_id)
2229.2.1 by Aaron Bentley
Reject reserved ids in versiondfile, tree, branch and repository
63
1563.2.15 by Robert Collins
remove the weavestore assumptions about the number and nature of files it manages.
64
    def copy_to(self, name, transport):
65
        """Copy this versioned file to name on transport."""
66
        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
67
1563.2.1 by Robert Collins
Merge in a variation of the versionedfile api from versioned-file.
68
    def versions(self):
69
        """Return a unsorted list of versions."""
70
        raise NotImplementedError(self.versions)
71
1594.2.8 by Robert Collins
add ghost aware apis to knits.
72
    def has_ghost(self, version_id):
73
        """Returns whether version is present as a ghost."""
74
        raise NotImplementedError(self.has_ghost)
75
1563.2.1 by Robert Collins
Merge in a variation of the versionedfile api from versioned-file.
76
    def has_version(self, version_id):
77
        """Returns whether version is present."""
78
        raise NotImplementedError(self.has_version)
79
2520.4.140 by Aaron Bentley
Use matching blocks from mpdiff for knit delta creation
80
    def add_lines(self, version_id, parents, lines, parent_texts=None,
2805.6.7 by Robert Collins
Review feedback.
81
        left_matching_blocks=None, nostore_sha=None, random_id=False,
82
        check_content=True):
1563.2.1 by Robert Collins
Merge in a variation of the versionedfile api from versioned-file.
83
        """Add a single text on top of the versioned file.
84
85
        Must raise RevisionAlreadyPresent if the new version is
86
        already present in file history.
87
88
        Must raise RevisionNotPresent if any of the given parents are
1594.2.21 by Robert Collins
Teach versioned files to prevent mutation after finishing.
89
        not present in file history.
2805.6.3 by Robert Collins
* The ``VersionedFile`` interface no longer protects against misuse when
90
91
        :param lines: A list of lines. Each line must be a bytestring. And all
92
            of them except the last must be terminated with \n and contain no
93
            other \n's. The last line may either contain no \n's or a single
94
            terminated \n. If the lines list does meet this constraint the add
95
            routine may error or may succeed - but you will be unable to read
96
            the data back accurately. (Checking the lines have been split
2805.6.7 by Robert Collins
Review feedback.
97
            correctly is expensive and extremely unlikely to catch bugs so it
98
            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.
99
        :param parent_texts: An optional dictionary containing the opaque 
2805.6.3 by Robert Collins
* The ``VersionedFile`` interface no longer protects against misuse when
100
            representations of some or all of the parents of version_id to
101
            allow delta optimisations.  VERY IMPORTANT: the texts must be those
102
            returned by add_lines or data corruption can be caused.
2520.4.148 by Aaron Bentley
Updates from review
103
        :param left_matching_blocks: a hint about which areas are common
104
            between the text and its left-hand-parent.  The format is
105
            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.
106
        :param nostore_sha: Raise ExistingContent and do not add the lines to
107
            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.
108
        :param random_id: If True a random id has been selected rather than
109
            an id determined by some deterministic process such as a converter
110
            from a foreign VCS. When True the backend may choose not to check
111
            for uniqueness of the resulting key within the versioned file, so
112
            this should only be done when the result is expected to be unique
113
            anyway.
2805.6.7 by Robert Collins
Review feedback.
114
        :param check_content: If True, the lines supplied are verified to be
115
            bytestrings that are correctly formed lines.
2776.1.1 by Robert Collins
* The ``add_lines`` methods on ``VersionedFile`` implementations has changed
116
        :return: The text sha1, the number of bytes in the text, and an opaque
117
                 representation of the inserted version which can be provided
118
                 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.
119
        """
1594.2.23 by Robert Collins
Test versioned file storage handling of clean/dirty status for accessed versioned files.
120
        self._check_write_ok()
2520.4.140 by Aaron Bentley
Use matching blocks from mpdiff for knit delta creation
121
        return self._add_lines(version_id, parents, lines, parent_texts,
2805.6.7 by Robert Collins
Review feedback.
122
            left_matching_blocks, nostore_sha, random_id, check_content)
1594.2.21 by Robert Collins
Teach versioned files to prevent mutation after finishing.
123
2520.4.140 by Aaron Bentley
Use matching blocks from mpdiff for knit delta creation
124
    def _add_lines(self, 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
        """Helper to do the class specific add_lines."""
1563.2.4 by Robert Collins
First cut at including the knit implementation of versioned_file.
127
        raise NotImplementedError(self.add_lines)
1563.2.1 by Robert Collins
Merge in a variation of the versionedfile api from versioned-file.
128
1596.2.32 by Robert Collins
Reduce re-extraction of texts during weave to knit joins by providing a memoisation facility.
129
    def add_lines_with_ghosts(self, version_id, parents, lines,
2805.6.7 by Robert Collins
Review feedback.
130
        parent_texts=None, nostore_sha=None, random_id=False,
131
        check_content=True):
1596.2.32 by Robert Collins
Reduce re-extraction of texts during weave to knit joins by providing a memoisation facility.
132
        """Add lines to the versioned file, allowing ghosts to be present.
133
        
2794.1.1 by Robert Collins
Allow knits to be instructed not to add a text based on a sha, for commit.
134
        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.
135
        """
1594.2.23 by Robert Collins
Test versioned file storage handling of clean/dirty status for accessed versioned files.
136
        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.
137
        return self._add_lines_with_ghosts(version_id, parents, lines,
2805.6.7 by Robert Collins
Review feedback.
138
            parent_texts, nostore_sha, random_id, check_content)
1594.2.21 by Robert Collins
Teach versioned files to prevent mutation after finishing.
139
2794.1.1 by Robert Collins
Allow knits to be instructed not to add a text based on a sha, for commit.
140
    def _add_lines_with_ghosts(self, version_id, parents, lines, parent_texts,
2805.6.7 by Robert Collins
Review feedback.
141
        nostore_sha, random_id, check_content):
1594.2.21 by Robert Collins
Teach versioned files to prevent mutation after finishing.
142
        """Helper to do class specific add_lines_with_ghosts."""
1594.2.8 by Robert Collins
add ghost aware apis to knits.
143
        raise NotImplementedError(self.add_lines_with_ghosts)
144
1563.2.19 by Robert Collins
stub out a check for knits.
145
    def check(self, progress_bar=None):
146
        """Check the versioned file for integrity."""
147
        raise NotImplementedError(self.check)
148
1666.1.6 by Robert Collins
Make knit the default format.
149
    def _check_lines_not_unicode(self, lines):
150
        """Check that lines being added to a versioned file are not unicode."""
151
        for line in lines:
152
            if line.__class__ is not str:
153
                raise errors.BzrBadParameterUnicode("lines")
154
155
    def _check_lines_are_lines(self, lines):
156
        """Check that the lines really are full lines without inline EOL."""
157
        for line in lines:
158
            if '\n' in line[:-1]:
159
                raise errors.BzrBadParameterContainsNewline("lines")
160
1594.2.23 by Robert Collins
Test versioned file storage handling of clean/dirty status for accessed versioned files.
161
    def _check_write_ok(self):
1594.2.21 by Robert Collins
Teach versioned files to prevent mutation after finishing.
162
        """Is the versioned file marked as 'finished' ? Raise if it is."""
163
        if self.finished:
164
            raise errors.OutSideTransaction()
1594.2.23 by Robert Collins
Test versioned file storage handling of clean/dirty status for accessed versioned files.
165
        if self._access_mode != 'w':
166
            raise errors.ReadOnlyObjectDirtiedError(self)
1594.2.21 by Robert Collins
Teach versioned files to prevent mutation after finishing.
167
1863.1.1 by John Arbash Meinel
Allow Versioned files to do caching if explicitly asked, and implement for Knit
168
    def enable_cache(self):
169
        """Tell this versioned file that it should cache any data it reads.
170
        
171
        This is advisory, implementations do not have to support caching.
172
        """
173
        pass
174
    
1563.2.7 by Robert Collins
add versioned file clear_cache entry.
175
    def clear_cache(self):
1863.1.1 by John Arbash Meinel
Allow Versioned files to do caching if explicitly asked, and implement for Knit
176
        """Remove any data cached in the versioned file object.
177
178
        This only needs to be supported if caches are supported
179
        """
180
        pass
1563.2.7 by Robert Collins
add versioned file clear_cache entry.
181
1563.2.5 by Robert Collins
Remove unused transaction references from knit.py and the versionedfile interface.
182
    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.
183
        """Add an identical text to old_version_id as new_version_id.
184
185
        Must raise RevisionNotPresent if the old version or any of the
186
        parents are not present in file history.
187
188
        Must raise RevisionAlreadyPresent if the new version is
189
        already present in file history."""
1594.2.24 by Robert Collins
Make use of the transaction finalisation warning support to implement in-knit caching.
190
        self._check_write_ok()
191
        return self._clone_text(new_version_id, old_version_id, parents)
192
193
    def _clone_text(self, new_version_id, old_version_id, parents):
194
        """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.
195
        raise NotImplementedError(self.clone_text)
196
1563.2.13 by Robert Collins
InterVersionedFile implemented.
197
    def create_empty(self, name, transport, mode=None):
198
        """Create a new versioned file of this exact type.
199
200
        :param name: the file name
201
        :param transport: the transport
202
        :param mode: optional file mode.
203
        """
204
        raise NotImplementedError(self.create_empty)
205
2535.3.1 by Andrew Bennetts
Add get_format_signature to VersionedFile
206
    def get_format_signature(self):
207
        """Get a text description of the data encoding in this file.
208
        
2831.7.1 by Ian Clatworthy
versionedfile.py code cleanups
209
        :since: 0.90
2535.3.1 by Andrew Bennetts
Add get_format_signature to VersionedFile
210
        """
211
        raise NotImplementedError(self.get_format_signature)
212
2520.4.41 by Aaron Bentley
Accelerate mpdiff generation
213
    def make_mpdiffs(self, version_ids):
2831.7.1 by Ian Clatworthy
versionedfile.py code cleanups
214
        """Create multiparent diffs for specified versions."""
2520.4.41 by Aaron Bentley
Accelerate mpdiff generation
215
        knit_versions = set()
216
        for version_id in version_ids:
217
            knit_versions.add(version_id)
218
            knit_versions.update(self.get_parents(version_id))
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]
224
            parents = [lines[p] for p in self.get_parents(version_id)]
2520.4.48 by Aaron Bentley
Support getting blocks from knit deltas with no final EOL
225
            if len(parents) > 0:
226
                left_parent_blocks = self._extract_blocks(version_id,
227
                                                          parents[0], target)
228
            else:
229
                left_parent_blocks = None
2520.4.41 by Aaron Bentley
Accelerate mpdiff generation
230
            diffs.append(multiparent.MultiParent.from_lines(target, parents,
231
                         left_parent_blocks))
232
        return diffs
233
2520.4.48 by Aaron Bentley
Support getting blocks from knit deltas with no final EOL
234
    def _extract_blocks(self, version_id, source, target):
2520.4.41 by Aaron Bentley
Accelerate mpdiff generation
235
        return None
2520.4.3 by Aaron Bentley
Implement plain strategy for extracting and installing multiparent diffs
236
2520.4.61 by Aaron Bentley
Do bulk insertion of records
237
    def add_mpdiffs(self, records):
2831.7.1 by Ian Clatworthy
versionedfile.py code cleanups
238
        """Add mpdiffs to this VersionedFile.
2520.4.126 by Aaron Bentley
Add more docs
239
240
        Records should be iterables of version, parents, expected_sha1,
2831.7.1 by Ian Clatworthy
versionedfile.py code cleanups
241
        mpdiff. mpdiff should be a MultiParent instance.
2520.4.126 by Aaron Bentley
Add more docs
242
        """
2831.7.1 by Ian Clatworthy
versionedfile.py code cleanups
243
        # Does this need to call self._check_write_ok()? (IanC 20070919)
2520.4.61 by Aaron Bentley
Do bulk insertion of records
244
        vf_parents = {}
2520.4.141 by Aaron Bentley
More batch operations adding mpdiffs
245
        mpvf = multiparent.MultiMemoryVersionedFile()
246
        versions = []
247
        for version, parent_ids, expected_sha1, mpdiff in records:
248
            versions.append(version)
249
            mpvf.add_diff(mpdiff, version, parent_ids)
250
        needed_parents = set()
2520.4.142 by Aaron Bentley
Clean up installation of inventory records
251
        for version, parent_ids, expected_sha1, mpdiff in records:
2520.4.141 by Aaron Bentley
More batch operations adding mpdiffs
252
            needed_parents.update(p for p in parent_ids
253
                                  if not mpvf.has_version(p))
254
        for parent_id, lines in zip(needed_parents,
255
                                 self._get_lf_split_line_list(needed_parents)):
256
            mpvf.add_version(lines, parent_id, [])
257
        for (version, parent_ids, expected_sha1, mpdiff), lines in\
258
            zip(records, mpvf.get_line_list(versions)):
259
            if len(parent_ids) == 1:
2520.4.140 by Aaron Bentley
Use matching blocks from mpdiff for knit delta creation
260
                left_matching_blocks = list(mpdiff.get_matching_blocks(0,
2520.4.141 by Aaron Bentley
More batch operations adding mpdiffs
261
                    mpvf.get_diff(parent_ids[0]).num_lines()))
2520.4.140 by Aaron Bentley
Use matching blocks from mpdiff for knit delta creation
262
            else:
263
                left_matching_blocks = None
2776.1.3 by Robert Collins
Missed bundles in the return value conversion of vf.add_lines.
264
            _, _, version_text = self.add_lines(version, parent_ids, lines,
2520.4.151 by Aaron Bentley
Style fixes from review
265
                vf_parents, left_matching_blocks=left_matching_blocks)
2520.4.61 by Aaron Bentley
Do bulk insertion of records
266
            vf_parents[version] = version_text
2520.4.142 by Aaron Bentley
Clean up installation of inventory records
267
        for (version, parent_ids, expected_sha1, mpdiff), sha1 in\
268
             zip(records, self.get_sha1s(versions)):
269
            if expected_sha1 != sha1:
2520.4.71 by Aaron Bentley
Update test to accept VersionedFileInvalidChecksum instead of TestamentMismatch
270
                raise errors.VersionedFileInvalidChecksum(version)
2520.4.3 by Aaron Bentley
Implement plain strategy for extracting and installing multiparent diffs
271
1666.1.6 by Robert Collins
Make knit the default format.
272
    def get_sha1(self, version_id):
273
        """Get the stored sha1 sum for the given revision.
274
        
2831.7.1 by Ian Clatworthy
versionedfile.py code cleanups
275
        :param version_id: The name of the version to lookup
1666.1.6 by Robert Collins
Make knit the default format.
276
        """
277
        raise NotImplementedError(self.get_sha1)
278
2520.4.89 by Aaron Bentley
Add get_sha1s to weaves
279
    def get_sha1s(self, version_ids):
280
        """Get the stored sha1 sums for the given revisions.
281
282
        :param version_ids: The names of the versions to lookup
283
        :return: a list of sha1s in order according to the version_ids
284
        """
2831.7.1 by Ian Clatworthy
versionedfile.py code cleanups
285
        raise NotImplementedError(self.get_sha1s)
2520.4.89 by Aaron Bentley
Add get_sha1s to weaves
286
1563.2.15 by Robert Collins
remove the weavestore assumptions about the number and nature of files it manages.
287
    def get_suffixes(self):
288
        """Return the file suffixes associated with this versioned file."""
289
        raise NotImplementedError(self.get_suffixes)
290
    
1563.2.1 by Robert Collins
Merge in a variation of the versionedfile api from versioned-file.
291
    def get_text(self, version_id):
292
        """Return version contents as a text string.
293
294
        Raises RevisionNotPresent if version is not present in
295
        file history.
296
        """
297
        return ''.join(self.get_lines(version_id))
298
    get_string = get_text
299
1756.2.1 by Aaron Bentley
Implement get_texts
300
    def get_texts(self, version_ids):
301
        """Return the texts of listed versions as a list of strings.
302
303
        Raises RevisionNotPresent if version is not present in
304
        file history.
305
        """
306
        return [''.join(self.get_lines(v)) for v in version_ids]
307
1563.2.1 by Robert Collins
Merge in a variation of the versionedfile api from versioned-file.
308
    def get_lines(self, version_id):
309
        """Return version contents as a sequence of lines.
310
311
        Raises RevisionNotPresent if version is not present in
312
        file history.
313
        """
314
        raise NotImplementedError(self.get_lines)
315
2520.4.90 by Aaron Bentley
Handle \r terminated lines in Weaves properly
316
    def _get_lf_split_line_list(self, version_ids):
317
        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
318
2530.1.1 by Aaron Bentley
Make topological sorting optional for get_ancestry
319
    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.
320
        """Return a list of all ancestors of given version(s). This
321
        will not include the null revision.
322
2490.2.32 by Aaron Bentley
Merge of not-sorting-ancestry branch
323
        This list will not be topologically sorted if topo_sorted=False is
324
        passed.
2530.1.1 by Aaron Bentley
Make topological sorting optional for get_ancestry
325
1563.2.1 by Robert Collins
Merge in a variation of the versionedfile api from versioned-file.
326
        Must raise RevisionNotPresent if any of the given versions are
327
        not present in file history."""
328
        if isinstance(version_ids, basestring):
329
            version_ids = [version_ids]
330
        raise NotImplementedError(self.get_ancestry)
331
        
1594.2.8 by Robert Collins
add ghost aware apis to knits.
332
    def get_ancestry_with_ghosts(self, version_ids):
333
        """Return a list of all ancestors of given version(s). This
334
        will not include the null revision.
335
336
        Must raise RevisionNotPresent if any of the given versions are
337
        not present in file history.
338
        
339
        Ghosts that are known about will be included in ancestry list,
340
        but are not explicitly marked.
341
        """
342
        raise NotImplementedError(self.get_ancestry_with_ghosts)
343
        
1684.3.1 by Robert Collins
Fix versioned file joins with empty targets.
344
    def get_graph(self, version_ids=None):
345
        """Return a graph from the versioned file. 
1594.2.8 by Robert Collins
add ghost aware apis to knits.
346
        
347
        Ghosts are not listed or referenced in the graph.
1684.3.1 by Robert Collins
Fix versioned file joins with empty targets.
348
        :param version_ids: Versions to select.
1759.2.1 by Jelmer Vernooij
Fix some types (found using aspell).
349
                            None means retrieve all versions.
1594.2.8 by Robert Collins
add ghost aware apis to knits.
350
        """
2592.3.43 by Robert Collins
A knit iter_parents API.
351
        if version_ids is None:
352
            return dict(self.iter_parents(self.versions()))
1563.2.13 by Robert Collins
InterVersionedFile implemented.
353
        result = {}
2858.2.1 by Martin Pool
Remove most calls to safe_file_id and safe_revision_id.
354
        pending = set(version_ids)
2592.3.43 by Robert Collins
A knit iter_parents API.
355
        while pending:
356
            this_iteration = pending
357
            pending = set()
358
            for version, parents in self.iter_parents(this_iteration):
1684.3.1 by Robert Collins
Fix versioned file joins with empty targets.
359
                result[version] = parents
2652.1.1 by John Arbash Meinel
Avoid set.difference_update(other) because it is slow when other is big.
360
                for parent in parents:
361
                    if parent in result:
362
                        continue
363
                    pending.add(parent)
1563.2.13 by Robert Collins
InterVersionedFile implemented.
364
        return result
1563.2.1 by Robert Collins
Merge in a variation of the versionedfile api from versioned-file.
365
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
1563.2.1 by Robert Collins
Merge in a variation of the versionedfile api from versioned-file.
374
    def get_parents(self, version_id):
375
        """Return version names for parents of a version.
376
377
        Must raise RevisionNotPresent if version is not present in
378
        file history.
379
        """
380
        raise NotImplementedError(self.get_parents)
381
1594.2.8 by Robert Collins
add ghost aware apis to knits.
382
    def get_parents_with_ghosts(self, version_id):
383
        """Return version names for parents of version_id.
384
385
        Will raise RevisionNotPresent if version_id is not present
386
        in the history.
387
388
        Ghosts that are known about will be included in the parent list,
389
        but are not explicitly marked.
390
        """
391
        raise NotImplementedError(self.get_parents_with_ghosts)
392
1563.2.1 by Robert Collins
Merge in a variation of the versionedfile api from versioned-file.
393
    def annotate_iter(self, version_id):
394
        """Yield list of (version-id, line) pairs for the specified
395
        version.
396
2831.7.1 by Ian Clatworthy
versionedfile.py code cleanups
397
        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.
398
        not present in file history.
399
        """
400
        raise NotImplementedError(self.annotate_iter)
401
402
    def annotate(self, version_id):
403
        return list(self.annotate_iter(version_id))
404
1563.2.31 by Robert Collins
Convert Knit repositories to use knits.
405
    def join(self, other, pb=None, msg=None, version_ids=None,
406
             ignore_missing=False):
1563.2.1 by Robert Collins
Merge in a variation of the versionedfile api from versioned-file.
407
        """Integrate versions from other into this versioned file.
408
409
        If version_ids is None all versions from other should be
410
        incorporated into this versioned file.
411
412
        Must raise RevisionNotPresent if any of the specified versions
2831.7.1 by Ian Clatworthy
versionedfile.py code cleanups
413
        are not present in the other file's history unless ignore_missing
414
        is supplied in which case they are silently skipped.
1563.2.31 by Robert Collins
Convert Knit repositories to use knits.
415
        """
1594.2.23 by Robert Collins
Test versioned file storage handling of clean/dirty status for accessed versioned files.
416
        self._check_write_ok()
1563.2.31 by Robert Collins
Convert Knit repositories to use knits.
417
        return InterVersionedFile.get(other, self).join(
418
            pb,
419
            msg,
420
            version_ids,
421
            ignore_missing)
1563.2.1 by Robert Collins
Merge in a variation of the versionedfile api from versioned-file.
422
2039.1.1 by Aaron Bentley
Clean up progress properly when interrupted during fetch (#54000)
423
    def iter_lines_added_or_present_in_versions(self, version_ids=None, 
424
                                                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.
425
        """Iterate over the lines in the versioned file from version_ids.
426
427
        This may return lines from other versions, and does not return the
428
        specific version marker at this point. The api may be changed
429
        during development to include the version that the versioned file
430
        thinks is relevant, but given that such hints are just guesses,
1759.2.2 by Jelmer Vernooij
Revert some of my spelling fixes and fix some typos after review by Aaron.
431
        its better not to have it if we don't need it.
1594.2.6 by Robert Collins
Introduce a api specifically for looking at lines in some versions of the inventory, for fileid_involved.
432
2039.1.1 by Aaron Bentley
Clean up progress properly when interrupted during fetch (#54000)
433
        If a progress bar is supplied, it may be used to indicate progress.
434
        The caller is responsible for cleaning up progress bars (because this
435
        is an iterator).
436
1594.2.6 by Robert Collins
Introduce a api specifically for looking at lines in some versions of the inventory, for fileid_involved.
437
        NOTES: Lines are normalised: they will all have \n terminators.
438
               Lines are returned in arbitrary order.
439
        """
440
        raise NotImplementedError(self.iter_lines_added_or_present_in_versions)
441
2592.3.43 by Robert Collins
A knit iter_parents API.
442
    def iter_parents(self, version_ids):
443
        """Iterate through the parents for many version ids.
444
445
        :param version_ids: An iterable yielding version_ids.
446
        :return: An iterator that yields (version_id, parents). Requested 
447
            version_ids not present in the versioned file are simply skipped.
448
            The order is undefined, allowing for different optimisations in
449
            the underlying implementation.
450
        """
451
        for version_id in version_ids:
452
            try:
453
                yield version_id, tuple(self.get_parents(version_id))
454
            except errors.RevisionNotPresent:
455
                pass
456
1594.2.21 by Robert Collins
Teach versioned files to prevent mutation after finishing.
457
    def transaction_finished(self):
458
        """The transaction that this file was opened in has finished.
459
460
        This records self.finished = True and should cause all mutating
461
        operations to error.
462
        """
463
        self.finished = True
464
1551.6.15 by Aaron Bentley
Moved plan_merge into Weave
465
    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.
466
        """Return pseudo-annotation indicating how the two versions merge.
467
468
        This is computed between versions a and b and their common
469
        base.
470
471
        Weave lines present in none of them are skipped entirely.
1664.2.2 by Aaron Bentley
Added legend for plan-merge output
472
473
        Legend:
474
        killed-base Dead in base revision
475
        killed-both Killed in each revision
476
        killed-a    Killed in a
477
        killed-b    Killed in b
478
        unchanged   Alive in both a and b (possibly created in both)
479
        new-a       Created in a
480
        new-b       Created in b
1664.2.5 by Aaron Bentley
Update plan-merge legend
481
        ghost-a     Killed in a, unborn in b    
482
        ghost-b     Killed in b, unborn in a
1664.2.2 by Aaron Bentley
Added legend for plan-merge output
483
        irrelevant  Not in either revision
1563.2.1 by Robert Collins
Merge in a variation of the versionedfile api from versioned-file.
484
        """
1551.6.15 by Aaron Bentley
Moved plan_merge into Weave
485
        raise NotImplementedError(VersionedFile.plan_merge)
486
        
1996.3.7 by John Arbash Meinel
lazy import versionedfile, late-load bzrlib.merge
487
    def weave_merge(self, plan, a_marker=TextMerge.A_MARKER,
1551.6.14 by Aaron Bentley
Tweaks from merge review
488
                    b_marker=TextMerge.B_MARKER):
1551.6.12 by Aaron Bentley
Indicate conflicts from merge_lines, insead of guessing
489
        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
490
1664.2.7 by Aaron Bentley
Merge bzr.dev
491
1551.6.10 by Aaron Bentley
Renamed WeaveMerge to PlanMerge, added plan method, created planless WeaveMerge
492
class PlanWeaveMerge(TextMerge):
1551.6.13 by Aaron Bentley
Cleanup
493
    """Weave merge that takes a plan as its input.
494
    
1551.6.14 by Aaron Bentley
Tweaks from merge review
495
    This exists so that VersionedFile.plan_merge is implementable.
496
    Most callers will want to use WeaveMerge instead.
1551.6.13 by Aaron Bentley
Cleanup
497
    """
498
1551.6.14 by Aaron Bentley
Tweaks from merge review
499
    def __init__(self, plan, a_marker=TextMerge.A_MARKER,
500
                 b_marker=TextMerge.B_MARKER):
1551.6.10 by Aaron Bentley
Renamed WeaveMerge to PlanMerge, added plan method, created planless WeaveMerge
501
        TextMerge.__init__(self, a_marker, b_marker)
502
        self.plan = plan
503
1551.6.7 by Aaron Bentley
Implemented two-way merge, refactored weave merge
504
    def _merge_struct(self):
1563.2.1 by Robert Collins
Merge in a variation of the versionedfile api from versioned-file.
505
        lines_a = []
506
        lines_b = []
507
        ch_a = ch_b = False
1664.2.8 by Aaron Bentley
Fix WeaveMerge when plan doesn't end with unchanged lines
508
509
        def outstanding_struct():
510
            if not lines_a and not lines_b:
511
                return
512
            elif ch_a and not ch_b:
513
                # one-sided change:
514
                yield(lines_a,)
515
            elif ch_b and not ch_a:
516
                yield (lines_b,)
517
            elif lines_a == lines_b:
518
                yield(lines_a,)
519
            else:
520
                yield (lines_a, lines_b)
1551.6.13 by Aaron Bentley
Cleanup
521
       
1616.1.18 by Martin Pool
(weave-merge) don't treat killed-both lines as points of agreement;
522
        # We previously considered either 'unchanged' or 'killed-both' lines
523
        # to be possible places to resynchronize.  However, assuming agreement
1759.2.1 by Jelmer Vernooij
Fix some types (found using aspell).
524
        # on killed-both lines may be too aggressive. -- mbp 20060324
1551.6.7 by Aaron Bentley
Implemented two-way merge, refactored weave merge
525
        for state, line in self.plan:
1616.1.18 by Martin Pool
(weave-merge) don't treat killed-both lines as points of agreement;
526
            if state == 'unchanged':
1563.2.1 by Robert Collins
Merge in a variation of the versionedfile api from versioned-file.
527
                # resync and flush queued conflicts changes if any
1664.2.8 by Aaron Bentley
Fix WeaveMerge when plan doesn't end with unchanged lines
528
                for struct in outstanding_struct():
529
                    yield struct
1551.6.11 by Aaron Bentley
Switched TextMerge_lines to work on a list
530
                lines_a = []
531
                lines_b = []
1563.2.1 by Robert Collins
Merge in a variation of the versionedfile api from versioned-file.
532
                ch_a = ch_b = False
533
                
534
            if state == 'unchanged':
535
                if line:
1551.6.5 by Aaron Bentley
Got weave merge producing structural output
536
                    yield ([line],)
1563.2.1 by Robert Collins
Merge in a variation of the versionedfile api from versioned-file.
537
            elif state == 'killed-a':
538
                ch_a = True
539
                lines_b.append(line)
540
            elif state == 'killed-b':
541
                ch_b = True
542
                lines_a.append(line)
543
            elif state == 'new-a':
544
                ch_a = True
545
                lines_a.append(line)
546
            elif state == 'new-b':
547
                ch_b = True
548
                lines_b.append(line)
549
            else:
1551.6.6 by Aaron Bentley
Cleanup
550
                assert state in ('irrelevant', 'ghost-a', 'ghost-b', 
551
                                 'killed-base', 'killed-both'), state
1664.2.8 by Aaron Bentley
Fix WeaveMerge when plan doesn't end with unchanged lines
552
        for struct in outstanding_struct():
553
            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.
554
1664.2.14 by Aaron Bentley
spacing fix
555
1551.6.10 by Aaron Bentley
Renamed WeaveMerge to PlanMerge, added plan method, created planless WeaveMerge
556
class WeaveMerge(PlanWeaveMerge):
2831.7.1 by Ian Clatworthy
versionedfile.py code cleanups
557
    """Weave merge that takes a VersionedFile and two versions as its input."""
1551.6.13 by Aaron Bentley
Cleanup
558
1551.6.10 by Aaron Bentley
Renamed WeaveMerge to PlanMerge, added plan method, created planless WeaveMerge
559
    def __init__(self, versionedfile, ver_a, ver_b, 
1551.6.14 by Aaron Bentley
Tweaks from merge review
560
        a_marker=PlanWeaveMerge.A_MARKER, b_marker=PlanWeaveMerge.B_MARKER):
1551.6.15 by Aaron Bentley
Moved plan_merge into Weave
561
        plan = versionedfile.plan_merge(ver_a, ver_b)
1551.6.10 by Aaron Bentley
Renamed WeaveMerge to PlanMerge, added plan method, created planless WeaveMerge
562
        PlanWeaveMerge.__init__(self, plan, a_marker, b_marker)
563
564
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.
565
class InterVersionedFile(InterObject):
2831.7.1 by Ian Clatworthy
versionedfile.py code cleanups
566
    """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.
567
568
    Its instances have methods like join, and contain
569
    references to the source and target versionedfiles these operations can be 
570
    carried out on.
571
572
    Often we will provide convenience methods on 'versionedfile' which carry out
573
    operations with another versionedfile - they will always forward to
574
    InterVersionedFile.get(other).method_name(parameters).
575
    """
576
1910.2.15 by Aaron Bentley
Back out inter.get changes, make optimizers an ordered list
577
    _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.
578
    """The available optimised InterVersionedFile types."""
579
1563.2.31 by Robert Collins
Convert Knit repositories to use knits.
580
    def join(self, pb=None, msg=None, version_ids=None, ignore_missing=False):
1563.2.13 by Robert Collins
InterVersionedFile implemented.
581
        """Integrate versions from self.source into self.target.
582
583
        If version_ids is None all versions from source should be
584
        incorporated into this versioned file.
585
586
        Must raise RevisionNotPresent if any of the specified versions
2831.7.1 by Ian Clatworthy
versionedfile.py code cleanups
587
        are not present in the other file's history unless ignore_missing is 
588
        supplied in which case they are silently skipped.
1563.2.13 by Robert Collins
InterVersionedFile implemented.
589
        """
590
        # the default join: 
1594.2.11 by Robert Collins
Setup fast-code paths for copying into empty weaves and weave->empty knit.
591
        # - if the target is empty, just add all the versions from 
592
        #   source to target, otherwise:
1563.2.13 by Robert Collins
InterVersionedFile implemented.
593
        # - make a temporary versioned file of type target
594
        # - insert the source content into it one at a time
595
        # - join them
1594.2.11 by Robert Collins
Setup fast-code paths for copying into empty weaves and weave->empty knit.
596
        if not self.target.versions():
597
            target = self.target
598
        else:
599
            # Make a new target-format versioned file. 
600
            temp_source = self.target.create_empty("temp", MemoryTransport())
601
            target = temp_source
1684.3.2 by Robert Collins
Factor out version_ids-to-join selection in InterVersionedfile.
602
        version_ids = self._get_source_version_ids(version_ids, ignore_missing)
1684.3.1 by Robert Collins
Fix versioned file joins with empty targets.
603
        graph = self.source.get_graph(version_ids)
1996.3.7 by John Arbash Meinel
lazy import versionedfile, late-load bzrlib.merge
604
        order = tsort.topo_sort(graph.items())
1563.2.37 by Robert Collins
Merge in nested progress bars
605
        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.
606
        parent_texts = {}
1563.2.37 by Robert Collins
Merge in nested progress bars
607
        try:
1596.2.28 by Robert Collins
more knit profile based tuning.
608
            # TODO for incremental cross-format work:
1596.2.27 by Robert Collins
Note potential improvements in knit adds.
609
            # make a versioned file with the following content:
610
            # all revisions we have been asked to join
611
            # all their ancestors that are *not* in target already.
612
            # the immediate parents of the above two sets, with 
613
            # empty parent lists - these versions are in target already
614
            # and the incorrect version data will be ignored.
615
            # TODO: for all ancestors that are present in target already,
616
            # 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.
617
            # 
618
            # TODO: remove parent texts when they are not relevant any more for 
619
            # memory pressure reduction. RBC 20060313
620
            # pb.update('Converting versioned data', 0, len(order))
2851.4.3 by Ian Clatworthy
fix up plain-to-annotated knit conversion
621
            total = len(order)
1563.2.37 by Robert Collins
Merge in nested progress bars
622
            for index, version in enumerate(order):
2851.4.3 by Ian Clatworthy
fix up plain-to-annotated knit conversion
623
                pb.update('Converting versioned data', index, total)
2776.1.3 by Robert Collins
Missed bundles in the return value conversion of vf.add_lines.
624
                _, _, parent_text = target.add_lines(version,
1596.2.38 by Robert Collins
rollback from using deltas to using fulltexts - deltas need more work to be ready.
625
                                               self.source.get_parents(version),
626
                                               self.source.get_lines(version),
627
                                               parent_texts=parent_texts)
628
                parent_texts[version] = parent_text
1563.2.37 by Robert Collins
Merge in nested progress bars
629
            
630
            # this should hit the native code path for target
1594.2.11 by Robert Collins
Setup fast-code paths for copying into empty weaves and weave->empty knit.
631
            if target is not self.target:
632
                return self.target.join(temp_source,
633
                                        pb,
634
                                        msg,
635
                                        version_ids,
636
                                        ignore_missing)
2851.4.3 by Ian Clatworthy
fix up plain-to-annotated knit conversion
637
            else:
638
                return total
1563.2.37 by Robert Collins
Merge in nested progress bars
639
        finally:
640
            pb.finished()
1563.2.13 by Robert Collins
InterVersionedFile implemented.
641
1684.3.2 by Robert Collins
Factor out version_ids-to-join selection in InterVersionedfile.
642
    def _get_source_version_ids(self, version_ids, ignore_missing):
643
        """Determine the version ids to be used from self.source.
644
645
        :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.
646
                            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.
647
        :param ignore_missing: if True, remove missing ids from the version 
648
                               list. If False, raise RevisionNotPresent on
649
                               a missing version id.
650
        :return: A set of version ids.
651
        """
652
        if version_ids is None:
1684.3.3 by Robert Collins
Add a special cased weaves to knit converter.
653
            # None cannot be in source.versions
1684.3.2 by Robert Collins
Factor out version_ids-to-join selection in InterVersionedfile.
654
            return set(self.source.versions())
655
        else:
656
            if ignore_missing:
657
                return set(self.source.versions()).intersection(set(version_ids))
658
            else:
659
                new_version_ids = set()
660
                for version in version_ids:
1684.3.3 by Robert Collins
Add a special cased weaves to knit converter.
661
                    if version is None:
662
                        continue
1684.3.2 by Robert Collins
Factor out version_ids-to-join selection in InterVersionedfile.
663
                    if not self.source.has_version(version):
664
                        raise errors.RevisionNotPresent(version, str(self.source))
665
                    else:
666
                        new_version_ids.add(version)
667
                return new_version_ids