/brz/remove-bazaar

To get this branch, use:
bzr branch http://gegoxaren.bato24.eu/bzr/brz/remove-bazaar

« back to all changes in this revision

Viewing changes to bzrlib/versionedfile.py

  • Committer: Andrew Bennetts
  • Date: 2007-10-05 02:18:53 UTC
  • mto: This revision was merged to the branch mainline in revision 2905.
  • Revision ID: andrew.bennetts@canonical.com-20071005021853-q410n3kcldnnp2ms
Revert bad change to bzrlib/progress.py

Show diffs side-by-side

added added

removed removed

Lines of Context:
 
1
# Copyright (C) 2005, 2006 Canonical Ltd
 
2
#
 
3
# Authors:
 
4
#   Johan Rydberg <jrydberg@gnu.org>
 
5
#
 
6
# This program is free software; you can redistribute it and/or modify
 
7
# it under the terms of the GNU General Public License as published by
 
8
# the Free Software Foundation; either version 2 of the License, or
 
9
# (at your option) any later version.
 
10
#
 
11
# This program is distributed in the hope that it will be useful,
 
12
# but WITHOUT ANY WARRANTY; without even the implied warranty of
 
13
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 
14
# GNU General Public License for more details.
 
15
#
 
16
# You should have received a copy of the GNU General Public License
 
17
# along with this program; if not, write to the Free Software
 
18
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 
19
 
 
20
"""Versioned text file storage api."""
 
21
 
 
22
from bzrlib.lazy_import import lazy_import
 
23
lazy_import(globals(), """
 
24
 
 
25
from bzrlib import (
 
26
    errors,
 
27
    osutils,
 
28
    multiparent,
 
29
    tsort,
 
30
    revision,
 
31
    ui,
 
32
    )
 
33
from bzrlib.transport.memory import MemoryTransport
 
34
""")
 
35
 
 
36
from cStringIO import StringIO
 
37
 
 
38
from bzrlib.inter import InterObject
 
39
from bzrlib.textmerge import TextMerge
 
40
from bzrlib.trace import mutter
 
41
 
 
42
 
 
43
class VersionedFile(object):
 
44
    """Versioned text file storage.
 
45
    
 
46
    A versioned file manages versions of line-based text files,
 
47
    keeping track of the originating version for each line.
 
48
 
 
49
    To clients the "lines" of the file are represented as a list of
 
50
    strings. These strings will typically have terminal newline
 
51
    characters, but this is not required.  In particular files commonly
 
52
    do not have a newline at the end of the file.
 
53
 
 
54
    Texts are identified by a version-id string.
 
55
    """
 
56
 
 
57
    def __init__(self, access_mode):
 
58
        self.finished = False
 
59
        self._access_mode = access_mode
 
60
 
 
61
    @staticmethod
 
62
    def check_not_reserved_id(version_id):
 
63
        revision.check_not_reserved_id(version_id)
 
64
 
 
65
    def copy_to(self, name, transport):
 
66
        """Copy this versioned file to name on transport."""
 
67
        raise NotImplementedError(self.copy_to)
 
68
 
 
69
    def versions(self):
 
70
        """Return a unsorted list of versions."""
 
71
        raise NotImplementedError(self.versions)
 
72
 
 
73
    def has_ghost(self, version_id):
 
74
        """Returns whether version is present as a ghost."""
 
75
        raise NotImplementedError(self.has_ghost)
 
76
 
 
77
    def has_version(self, version_id):
 
78
        """Returns whether version is present."""
 
79
        raise NotImplementedError(self.has_version)
 
80
 
 
81
    def add_lines(self, version_id, parents, lines, parent_texts=None,
 
82
        left_matching_blocks=None, nostore_sha=None, random_id=False,
 
83
        check_content=True):
 
84
        """Add a single text on top of the versioned file.
 
85
 
 
86
        Must raise RevisionAlreadyPresent if the new version is
 
87
        already present in file history.
 
88
 
 
89
        Must raise RevisionNotPresent if any of the given parents are
 
90
        not present in file history.
 
91
 
 
92
        :param lines: A list of lines. Each line must be a bytestring. And all
 
93
            of them except the last must be terminated with \n and contain no
 
94
            other \n's. The last line may either contain no \n's or a single
 
95
            terminated \n. If the lines list does meet this constraint the add
 
96
            routine may error or may succeed - but you will be unable to read
 
97
            the data back accurately. (Checking the lines have been split
 
98
            correctly is expensive and extremely unlikely to catch bugs so it
 
99
            is not done at runtime unless check_content is True.)
 
100
        :param parent_texts: An optional dictionary containing the opaque 
 
101
            representations of some or all of the parents of version_id to
 
102
            allow delta optimisations.  VERY IMPORTANT: the texts must be those
 
103
            returned by add_lines or data corruption can be caused.
 
104
        :param left_matching_blocks: a hint about which areas are common
 
105
            between the text and its left-hand-parent.  The format is
 
106
            the SequenceMatcher.get_matching_blocks format.
 
107
        :param nostore_sha: Raise ExistingContent and do not add the lines to
 
108
            the versioned file if the digest of the lines matches this.
 
109
        :param random_id: If True a random id has been selected rather than
 
110
            an id determined by some deterministic process such as a converter
 
111
            from a foreign VCS. When True the backend may choose not to check
 
112
            for uniqueness of the resulting key within the versioned file, so
 
113
            this should only be done when the result is expected to be unique
 
114
            anyway.
 
115
        :param check_content: If True, the lines supplied are verified to be
 
116
            bytestrings that are correctly formed lines.
 
117
        :return: The text sha1, the number of bytes in the text, and an opaque
 
118
                 representation of the inserted version which can be provided
 
119
                 back to future add_lines calls in the parent_texts dictionary.
 
120
        """
 
121
        version_id = osutils.safe_revision_id(version_id)
 
122
        parents = [osutils.safe_revision_id(v) for v in parents]
 
123
        self._check_write_ok()
 
124
        return self._add_lines(version_id, parents, lines, parent_texts,
 
125
            left_matching_blocks, nostore_sha, random_id, check_content)
 
126
 
 
127
    def _add_lines(self, version_id, parents, lines, parent_texts,
 
128
        left_matching_blocks, nostore_sha, random_id, check_content):
 
129
        """Helper to do the class specific add_lines."""
 
130
        raise NotImplementedError(self.add_lines)
 
131
 
 
132
    def add_lines_with_ghosts(self, version_id, parents, lines,
 
133
        parent_texts=None, nostore_sha=None, random_id=False,
 
134
        check_content=True):
 
135
        """Add lines to the versioned file, allowing ghosts to be present.
 
136
        
 
137
        This takes the same parameters as add_lines and returns the same.
 
138
        """
 
139
        version_id = osutils.safe_revision_id(version_id)
 
140
        parents = [osutils.safe_revision_id(v) for v in parents]
 
141
        self._check_write_ok()
 
142
        return self._add_lines_with_ghosts(version_id, parents, lines,
 
143
            parent_texts, nostore_sha, random_id, check_content)
 
144
 
 
145
    def _add_lines_with_ghosts(self, version_id, parents, lines, parent_texts,
 
146
        nostore_sha, random_id, check_content):
 
147
        """Helper to do class specific add_lines_with_ghosts."""
 
148
        raise NotImplementedError(self.add_lines_with_ghosts)
 
149
 
 
150
    def check(self, progress_bar=None):
 
151
        """Check the versioned file for integrity."""
 
152
        raise NotImplementedError(self.check)
 
153
 
 
154
    def _check_lines_not_unicode(self, lines):
 
155
        """Check that lines being added to a versioned file are not unicode."""
 
156
        for line in lines:
 
157
            if line.__class__ is not str:
 
158
                raise errors.BzrBadParameterUnicode("lines")
 
159
 
 
160
    def _check_lines_are_lines(self, lines):
 
161
        """Check that the lines really are full lines without inline EOL."""
 
162
        for line in lines:
 
163
            if '\n' in line[:-1]:
 
164
                raise errors.BzrBadParameterContainsNewline("lines")
 
165
 
 
166
    def _check_write_ok(self):
 
167
        """Is the versioned file marked as 'finished' ? Raise if it is."""
 
168
        if self.finished:
 
169
            raise errors.OutSideTransaction()
 
170
        if self._access_mode != 'w':
 
171
            raise errors.ReadOnlyObjectDirtiedError(self)
 
172
 
 
173
    def enable_cache(self):
 
174
        """Tell this versioned file that it should cache any data it reads.
 
175
        
 
176
        This is advisory, implementations do not have to support caching.
 
177
        """
 
178
        pass
 
179
    
 
180
    def clear_cache(self):
 
181
        """Remove any data cached in the versioned file object.
 
182
 
 
183
        This only needs to be supported if caches are supported
 
184
        """
 
185
        pass
 
186
 
 
187
    def clone_text(self, new_version_id, old_version_id, parents):
 
188
        """Add an identical text to old_version_id as new_version_id.
 
189
 
 
190
        Must raise RevisionNotPresent if the old version or any of the
 
191
        parents are not present in file history.
 
192
 
 
193
        Must raise RevisionAlreadyPresent if the new version is
 
194
        already present in file history."""
 
195
        new_version_id = osutils.safe_revision_id(new_version_id)
 
196
        old_version_id = osutils.safe_revision_id(old_version_id)
 
197
        parents = [osutils.safe_revision_id(v) for v in parents]
 
198
        self._check_write_ok()
 
199
        return self._clone_text(new_version_id, old_version_id, parents)
 
200
 
 
201
    def _clone_text(self, new_version_id, old_version_id, parents):
 
202
        """Helper function to do the _clone_text work."""
 
203
        raise NotImplementedError(self.clone_text)
 
204
 
 
205
    def create_empty(self, name, transport, mode=None):
 
206
        """Create a new versioned file of this exact type.
 
207
 
 
208
        :param name: the file name
 
209
        :param transport: the transport
 
210
        :param mode: optional file mode.
 
211
        """
 
212
        raise NotImplementedError(self.create_empty)
 
213
 
 
214
    def get_format_signature(self):
 
215
        """Get a text description of the data encoding in this file.
 
216
        
 
217
        :since: 0.90
 
218
        """
 
219
        raise NotImplementedError(self.get_format_signature)
 
220
 
 
221
    def make_mpdiffs(self, version_ids):
 
222
        """Create multiparent diffs for specified versions."""
 
223
        knit_versions = set()
 
224
        for version_id in version_ids:
 
225
            knit_versions.add(version_id)
 
226
            knit_versions.update(self.get_parents(version_id))
 
227
        lines = dict(zip(knit_versions,
 
228
            self._get_lf_split_line_list(knit_versions)))
 
229
        diffs = []
 
230
        for version_id in version_ids:
 
231
            target = lines[version_id]
 
232
            parents = [lines[p] for p in self.get_parents(version_id)]
 
233
            if len(parents) > 0:
 
234
                left_parent_blocks = self._extract_blocks(version_id,
 
235
                                                          parents[0], target)
 
236
            else:
 
237
                left_parent_blocks = None
 
238
            diffs.append(multiparent.MultiParent.from_lines(target, parents,
 
239
                         left_parent_blocks))
 
240
        return diffs
 
241
 
 
242
    def _extract_blocks(self, version_id, source, target):
 
243
        return None
 
244
 
 
245
    def add_mpdiffs(self, records):
 
246
        """Add mpdiffs to this VersionedFile.
 
247
 
 
248
        Records should be iterables of version, parents, expected_sha1,
 
249
        mpdiff. mpdiff should be a MultiParent instance.
 
250
        """
 
251
        # Does this need to call self._check_write_ok()? (IanC 20070919)
 
252
        vf_parents = {}
 
253
        mpvf = multiparent.MultiMemoryVersionedFile()
 
254
        versions = []
 
255
        for version, parent_ids, expected_sha1, mpdiff in records:
 
256
            versions.append(version)
 
257
            mpvf.add_diff(mpdiff, version, parent_ids)
 
258
        needed_parents = set()
 
259
        for version, parent_ids, expected_sha1, mpdiff in records:
 
260
            needed_parents.update(p for p in parent_ids
 
261
                                  if not mpvf.has_version(p))
 
262
        for parent_id, lines in zip(needed_parents,
 
263
                                 self._get_lf_split_line_list(needed_parents)):
 
264
            mpvf.add_version(lines, parent_id, [])
 
265
        for (version, parent_ids, expected_sha1, mpdiff), lines in\
 
266
            zip(records, mpvf.get_line_list(versions)):
 
267
            if len(parent_ids) == 1:
 
268
                left_matching_blocks = list(mpdiff.get_matching_blocks(0,
 
269
                    mpvf.get_diff(parent_ids[0]).num_lines()))
 
270
            else:
 
271
                left_matching_blocks = None
 
272
            _, _, version_text = self.add_lines(version, parent_ids, lines,
 
273
                vf_parents, left_matching_blocks=left_matching_blocks)
 
274
            vf_parents[version] = version_text
 
275
        for (version, parent_ids, expected_sha1, mpdiff), sha1 in\
 
276
             zip(records, self.get_sha1s(versions)):
 
277
            if expected_sha1 != sha1:
 
278
                raise errors.VersionedFileInvalidChecksum(version)
 
279
 
 
280
    def get_sha1(self, version_id):
 
281
        """Get the stored sha1 sum for the given revision.
 
282
        
 
283
        :param version_id: The name of the version to lookup
 
284
        """
 
285
        raise NotImplementedError(self.get_sha1)
 
286
 
 
287
    def get_sha1s(self, version_ids):
 
288
        """Get the stored sha1 sums for the given revisions.
 
289
 
 
290
        :param version_ids: The names of the versions to lookup
 
291
        :return: a list of sha1s in order according to the version_ids
 
292
        """
 
293
        raise NotImplementedError(self.get_sha1s)
 
294
 
 
295
    def get_suffixes(self):
 
296
        """Return the file suffixes associated with this versioned file."""
 
297
        raise NotImplementedError(self.get_suffixes)
 
298
    
 
299
    def get_text(self, version_id):
 
300
        """Return version contents as a text string.
 
301
 
 
302
        Raises RevisionNotPresent if version is not present in
 
303
        file history.
 
304
        """
 
305
        return ''.join(self.get_lines(version_id))
 
306
    get_string = get_text
 
307
 
 
308
    def get_texts(self, version_ids):
 
309
        """Return the texts of listed versions as a list of strings.
 
310
 
 
311
        Raises RevisionNotPresent if version is not present in
 
312
        file history.
 
313
        """
 
314
        return [''.join(self.get_lines(v)) for v in version_ids]
 
315
 
 
316
    def get_lines(self, version_id):
 
317
        """Return version contents as a sequence of lines.
 
318
 
 
319
        Raises RevisionNotPresent if version is not present in
 
320
        file history.
 
321
        """
 
322
        raise NotImplementedError(self.get_lines)
 
323
 
 
324
    def _get_lf_split_line_list(self, version_ids):
 
325
        return [StringIO(t).readlines() for t in self.get_texts(version_ids)]
 
326
 
 
327
    def get_ancestry(self, version_ids, topo_sorted=True):
 
328
        """Return a list of all ancestors of given version(s). This
 
329
        will not include the null revision.
 
330
 
 
331
        This list will not be topologically sorted if topo_sorted=False is
 
332
        passed.
 
333
 
 
334
        Must raise RevisionNotPresent if any of the given versions are
 
335
        not present in file history."""
 
336
        if isinstance(version_ids, basestring):
 
337
            version_ids = [version_ids]
 
338
        raise NotImplementedError(self.get_ancestry)
 
339
        
 
340
    def get_ancestry_with_ghosts(self, version_ids):
 
341
        """Return a list of all ancestors of given version(s). This
 
342
        will not include the null revision.
 
343
 
 
344
        Must raise RevisionNotPresent if any of the given versions are
 
345
        not present in file history.
 
346
        
 
347
        Ghosts that are known about will be included in ancestry list,
 
348
        but are not explicitly marked.
 
349
        """
 
350
        raise NotImplementedError(self.get_ancestry_with_ghosts)
 
351
        
 
352
    def get_graph(self, version_ids=None):
 
353
        """Return a graph from the versioned file. 
 
354
        
 
355
        Ghosts are not listed or referenced in the graph.
 
356
        :param version_ids: Versions to select.
 
357
                            None means retrieve all versions.
 
358
        """
 
359
        if version_ids is None:
 
360
            return dict(self.iter_parents(self.versions()))
 
361
        result = {}
 
362
        pending = set(osutils.safe_revision_id(v) for v in version_ids)
 
363
        while pending:
 
364
            this_iteration = pending
 
365
            pending = set()
 
366
            for version, parents in self.iter_parents(this_iteration):
 
367
                result[version] = parents
 
368
                for parent in parents:
 
369
                    if parent in result:
 
370
                        continue
 
371
                    pending.add(parent)
 
372
        return result
 
373
 
 
374
    def get_graph_with_ghosts(self):
 
375
        """Return a graph for the entire versioned file.
 
376
        
 
377
        Ghosts are referenced in parents list but are not
 
378
        explicitly listed.
 
379
        """
 
380
        raise NotImplementedError(self.get_graph_with_ghosts)
 
381
 
 
382
    def get_parents(self, version_id):
 
383
        """Return version names for parents of a version.
 
384
 
 
385
        Must raise RevisionNotPresent if version is not present in
 
386
        file history.
 
387
        """
 
388
        raise NotImplementedError(self.get_parents)
 
389
 
 
390
    def get_parents_with_ghosts(self, version_id):
 
391
        """Return version names for parents of version_id.
 
392
 
 
393
        Will raise RevisionNotPresent if version_id is not present
 
394
        in the history.
 
395
 
 
396
        Ghosts that are known about will be included in the parent list,
 
397
        but are not explicitly marked.
 
398
        """
 
399
        raise NotImplementedError(self.get_parents_with_ghosts)
 
400
 
 
401
    def annotate_iter(self, version_id):
 
402
        """Yield list of (version-id, line) pairs for the specified
 
403
        version.
 
404
 
 
405
        Must raise RevisionNotPresent if the given version is
 
406
        not present in file history.
 
407
        """
 
408
        raise NotImplementedError(self.annotate_iter)
 
409
 
 
410
    def annotate(self, version_id):
 
411
        return list(self.annotate_iter(version_id))
 
412
 
 
413
    def join(self, other, pb=None, msg=None, version_ids=None,
 
414
             ignore_missing=False):
 
415
        """Integrate versions from other into this versioned file.
 
416
 
 
417
        If version_ids is None all versions from other should be
 
418
        incorporated into this versioned file.
 
419
 
 
420
        Must raise RevisionNotPresent if any of the specified versions
 
421
        are not present in the other file's history unless ignore_missing
 
422
        is supplied in which case they are silently skipped.
 
423
        """
 
424
        self._check_write_ok()
 
425
        return InterVersionedFile.get(other, self).join(
 
426
            pb,
 
427
            msg,
 
428
            version_ids,
 
429
            ignore_missing)
 
430
 
 
431
    def iter_lines_added_or_present_in_versions(self, version_ids=None, 
 
432
                                                pb=None):
 
433
        """Iterate over the lines in the versioned file from version_ids.
 
434
 
 
435
        This may return lines from other versions, and does not return the
 
436
        specific version marker at this point. The api may be changed
 
437
        during development to include the version that the versioned file
 
438
        thinks is relevant, but given that such hints are just guesses,
 
439
        its better not to have it if we don't need it.
 
440
 
 
441
        If a progress bar is supplied, it may be used to indicate progress.
 
442
        The caller is responsible for cleaning up progress bars (because this
 
443
        is an iterator).
 
444
 
 
445
        NOTES: Lines are normalised: they will all have \n terminators.
 
446
               Lines are returned in arbitrary order.
 
447
        """
 
448
        raise NotImplementedError(self.iter_lines_added_or_present_in_versions)
 
449
 
 
450
    def iter_parents(self, version_ids):
 
451
        """Iterate through the parents for many version ids.
 
452
 
 
453
        :param version_ids: An iterable yielding version_ids.
 
454
        :return: An iterator that yields (version_id, parents). Requested 
 
455
            version_ids not present in the versioned file are simply skipped.
 
456
            The order is undefined, allowing for different optimisations in
 
457
            the underlying implementation.
 
458
        """
 
459
        for version_id in version_ids:
 
460
            try:
 
461
                yield version_id, tuple(self.get_parents(version_id))
 
462
            except errors.RevisionNotPresent:
 
463
                pass
 
464
 
 
465
    def transaction_finished(self):
 
466
        """The transaction that this file was opened in has finished.
 
467
 
 
468
        This records self.finished = True and should cause all mutating
 
469
        operations to error.
 
470
        """
 
471
        self.finished = True
 
472
 
 
473
    def plan_merge(self, ver_a, ver_b):
 
474
        """Return pseudo-annotation indicating how the two versions merge.
 
475
 
 
476
        This is computed between versions a and b and their common
 
477
        base.
 
478
 
 
479
        Weave lines present in none of them are skipped entirely.
 
480
 
 
481
        Legend:
 
482
        killed-base Dead in base revision
 
483
        killed-both Killed in each revision
 
484
        killed-a    Killed in a
 
485
        killed-b    Killed in b
 
486
        unchanged   Alive in both a and b (possibly created in both)
 
487
        new-a       Created in a
 
488
        new-b       Created in b
 
489
        ghost-a     Killed in a, unborn in b    
 
490
        ghost-b     Killed in b, unborn in a
 
491
        irrelevant  Not in either revision
 
492
        """
 
493
        raise NotImplementedError(VersionedFile.plan_merge)
 
494
        
 
495
    def weave_merge(self, plan, a_marker=TextMerge.A_MARKER,
 
496
                    b_marker=TextMerge.B_MARKER):
 
497
        return PlanWeaveMerge(plan, a_marker, b_marker).merge_lines()[0]
 
498
 
 
499
 
 
500
class PlanWeaveMerge(TextMerge):
 
501
    """Weave merge that takes a plan as its input.
 
502
    
 
503
    This exists so that VersionedFile.plan_merge is implementable.
 
504
    Most callers will want to use WeaveMerge instead.
 
505
    """
 
506
 
 
507
    def __init__(self, plan, a_marker=TextMerge.A_MARKER,
 
508
                 b_marker=TextMerge.B_MARKER):
 
509
        TextMerge.__init__(self, a_marker, b_marker)
 
510
        self.plan = plan
 
511
 
 
512
    def _merge_struct(self):
 
513
        lines_a = []
 
514
        lines_b = []
 
515
        ch_a = ch_b = False
 
516
 
 
517
        def outstanding_struct():
 
518
            if not lines_a and not lines_b:
 
519
                return
 
520
            elif ch_a and not ch_b:
 
521
                # one-sided change:
 
522
                yield(lines_a,)
 
523
            elif ch_b and not ch_a:
 
524
                yield (lines_b,)
 
525
            elif lines_a == lines_b:
 
526
                yield(lines_a,)
 
527
            else:
 
528
                yield (lines_a, lines_b)
 
529
       
 
530
        # We previously considered either 'unchanged' or 'killed-both' lines
 
531
        # to be possible places to resynchronize.  However, assuming agreement
 
532
        # on killed-both lines may be too aggressive. -- mbp 20060324
 
533
        for state, line in self.plan:
 
534
            if state == 'unchanged':
 
535
                # resync and flush queued conflicts changes if any
 
536
                for struct in outstanding_struct():
 
537
                    yield struct
 
538
                lines_a = []
 
539
                lines_b = []
 
540
                ch_a = ch_b = False
 
541
                
 
542
            if state == 'unchanged':
 
543
                if line:
 
544
                    yield ([line],)
 
545
            elif state == 'killed-a':
 
546
                ch_a = True
 
547
                lines_b.append(line)
 
548
            elif state == 'killed-b':
 
549
                ch_b = True
 
550
                lines_a.append(line)
 
551
            elif state == 'new-a':
 
552
                ch_a = True
 
553
                lines_a.append(line)
 
554
            elif state == 'new-b':
 
555
                ch_b = True
 
556
                lines_b.append(line)
 
557
            else:
 
558
                assert state in ('irrelevant', 'ghost-a', 'ghost-b', 
 
559
                                 'killed-base', 'killed-both'), state
 
560
        for struct in outstanding_struct():
 
561
            yield struct
 
562
 
 
563
 
 
564
class WeaveMerge(PlanWeaveMerge):
 
565
    """Weave merge that takes a VersionedFile and two versions as its input."""
 
566
 
 
567
    def __init__(self, versionedfile, ver_a, ver_b, 
 
568
        a_marker=PlanWeaveMerge.A_MARKER, b_marker=PlanWeaveMerge.B_MARKER):
 
569
        plan = versionedfile.plan_merge(ver_a, ver_b)
 
570
        PlanWeaveMerge.__init__(self, plan, a_marker, b_marker)
 
571
 
 
572
 
 
573
class InterVersionedFile(InterObject):
 
574
    """This class represents operations taking place between two VersionedFiles.
 
575
 
 
576
    Its instances have methods like join, and contain
 
577
    references to the source and target versionedfiles these operations can be 
 
578
    carried out on.
 
579
 
 
580
    Often we will provide convenience methods on 'versionedfile' which carry out
 
581
    operations with another versionedfile - they will always forward to
 
582
    InterVersionedFile.get(other).method_name(parameters).
 
583
    """
 
584
 
 
585
    _optimisers = []
 
586
    """The available optimised InterVersionedFile types."""
 
587
 
 
588
    def join(self, pb=None, msg=None, version_ids=None, ignore_missing=False):
 
589
        """Integrate versions from self.source into self.target.
 
590
 
 
591
        If version_ids is None all versions from source should be
 
592
        incorporated into this versioned file.
 
593
 
 
594
        Must raise RevisionNotPresent if any of the specified versions
 
595
        are not present in the other file's history unless ignore_missing is 
 
596
        supplied in which case they are silently skipped.
 
597
        """
 
598
        # the default join: 
 
599
        # - if the target is empty, just add all the versions from 
 
600
        #   source to target, otherwise:
 
601
        # - make a temporary versioned file of type target
 
602
        # - insert the source content into it one at a time
 
603
        # - join them
 
604
        if not self.target.versions():
 
605
            target = self.target
 
606
        else:
 
607
            # Make a new target-format versioned file. 
 
608
            temp_source = self.target.create_empty("temp", MemoryTransport())
 
609
            target = temp_source
 
610
        version_ids = self._get_source_version_ids(version_ids, ignore_missing)
 
611
        graph = self.source.get_graph(version_ids)
 
612
        order = tsort.topo_sort(graph.items())
 
613
        pb = ui.ui_factory.nested_progress_bar()
 
614
        parent_texts = {}
 
615
        try:
 
616
            # TODO for incremental cross-format work:
 
617
            # make a versioned file with the following content:
 
618
            # all revisions we have been asked to join
 
619
            # all their ancestors that are *not* in target already.
 
620
            # the immediate parents of the above two sets, with 
 
621
            # empty parent lists - these versions are in target already
 
622
            # and the incorrect version data will be ignored.
 
623
            # TODO: for all ancestors that are present in target already,
 
624
            # check them for consistent data, this requires moving sha1 from
 
625
            # 
 
626
            # TODO: remove parent texts when they are not relevant any more for 
 
627
            # memory pressure reduction. RBC 20060313
 
628
            # pb.update('Converting versioned data', 0, len(order))
 
629
            total = len(order)
 
630
            for index, version in enumerate(order):
 
631
                pb.update('Converting versioned data', index, total)
 
632
                _, _, parent_text = target.add_lines(version,
 
633
                                               self.source.get_parents(version),
 
634
                                               self.source.get_lines(version),
 
635
                                               parent_texts=parent_texts)
 
636
                parent_texts[version] = parent_text
 
637
            
 
638
            # this should hit the native code path for target
 
639
            if target is not self.target:
 
640
                return self.target.join(temp_source,
 
641
                                        pb,
 
642
                                        msg,
 
643
                                        version_ids,
 
644
                                        ignore_missing)
 
645
            else:
 
646
                return total
 
647
        finally:
 
648
            pb.finished()
 
649
 
 
650
    def _get_source_version_ids(self, version_ids, ignore_missing):
 
651
        """Determine the version ids to be used from self.source.
 
652
 
 
653
        :param version_ids: The caller-supplied version ids to check. (None 
 
654
                            for all). If None is in version_ids, it is stripped.
 
655
        :param ignore_missing: if True, remove missing ids from the version 
 
656
                               list. If False, raise RevisionNotPresent on
 
657
                               a missing version id.
 
658
        :return: A set of version ids.
 
659
        """
 
660
        if version_ids is None:
 
661
            # None cannot be in source.versions
 
662
            return set(self.source.versions())
 
663
        else:
 
664
            version_ids = [osutils.safe_revision_id(v) for v in version_ids]
 
665
            if ignore_missing:
 
666
                return set(self.source.versions()).intersection(set(version_ids))
 
667
            else:
 
668
                new_version_ids = set()
 
669
                for version in version_ids:
 
670
                    if version is None:
 
671
                        continue
 
672
                    if not self.source.has_version(version):
 
673
                        raise errors.RevisionNotPresent(version, str(self.source))
 
674
                    else:
 
675
                        new_version_ids.add(version)
 
676
                return new_version_ids