1
# Copyright (C) 2005, 2006 Canonical Ltd
4
# Johan Rydberg <jrydberg@gnu.org>
6
# This program is free software; you can redistribute it and/or modify
7
# it under the terms of the GNU General Public License as published by
8
# the Free Software Foundation; either version 2 of the License, or
9
# (at your option) any later version.
11
# This program is distributed in the hope that it will be useful,
12
# but WITHOUT ANY WARRANTY; without even the implied warranty of
13
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14
# GNU General Public License for more details.
16
# You should have received a copy of the GNU General Public License
17
# along with this program; if not, write to the Free Software
18
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
20
"""Versioned text file storage api."""
22
from bzrlib.lazy_import import lazy_import
23
lazy_import(globals(), """
33
from bzrlib.transport.memory import MemoryTransport
36
from cStringIO import StringIO
38
from bzrlib.inter import InterObject
39
from bzrlib.textmerge import TextMerge
42
class VersionedFile(object):
43
"""Versioned text file storage.
45
A versioned file manages versions of line-based text files,
46
keeping track of the originating version for each line.
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.
53
Texts are identified by a version-id string.
56
def __init__(self, access_mode):
58
self._access_mode = access_mode
61
def check_not_reserved_id(version_id):
62
revision.check_not_reserved_id(version_id)
64
def copy_to(self, name, transport):
65
"""Copy this versioned file to name on transport."""
66
raise NotImplementedError(self.copy_to)
69
"""Return a unsorted list of versions."""
70
raise NotImplementedError(self.versions)
72
def has_ghost(self, version_id):
73
"""Returns whether version is present as a ghost."""
74
raise NotImplementedError(self.has_ghost)
76
def has_version(self, version_id):
77
"""Returns whether version is present."""
78
raise NotImplementedError(self.has_version)
80
def add_delta(self, version_id, parents, delta_parent, sha1, noeol, delta):
81
"""Add a text to the versioned file via a pregenerated delta.
83
:param version_id: The version id being added.
84
:param parents: The parents of the version_id.
85
:param delta_parent: The parent this delta was created against.
86
:param sha1: The sha1 of the full text.
87
:param delta: The delta instructions. See get_delta for details.
89
version_id = osutils.safe_revision_id(version_id)
90
parents = [osutils.safe_revision_id(v) for v in parents]
91
self._check_write_ok()
92
if self.has_version(version_id):
93
raise errors.RevisionAlreadyPresent(version_id, self)
94
return self._add_delta(version_id, parents, delta_parent, sha1, noeol, delta)
96
def _add_delta(self, version_id, parents, delta_parent, sha1, noeol, delta):
97
"""Class specific routine to add a delta.
99
This generic version simply applies the delta to the delta_parent and
102
# strip annotation from delta
104
for start, stop, delta_len, delta_lines in delta:
105
new_delta.append((start, stop, delta_len, [text for origin, text in delta_lines]))
106
if delta_parent is not None:
107
parent_full = self.get_lines(delta_parent)
110
new_full = self._apply_delta(parent_full, new_delta)
111
# its impossible to have noeol on an empty file
112
if noeol and new_full[-1][-1] == '\n':
113
new_full[-1] = new_full[-1][:-1]
114
self.add_lines(version_id, parents, new_full)
116
def add_lines(self, version_id, parents, lines, parent_texts=None,
117
left_matching_blocks=None):
118
"""Add a single text on top of the versioned file.
120
Must raise RevisionAlreadyPresent if the new version is
121
already present in file history.
123
Must raise RevisionNotPresent if any of the given parents are
124
not present in file history.
125
:param parent_texts: An optional dictionary containing the opaque
126
representations of some or all of the parents of
127
version_id to allow delta optimisations.
128
VERY IMPORTANT: the texts must be those returned
129
by add_lines or data corruption can be caused.
130
:param left_matching_blocks: a hint about which areas are common
131
between the text and its left-hand-parent. The format is
132
the SequenceMatcher.get_matching_blocks format.
133
:return: An opaque representation of the inserted version which can be
134
provided back to future add_lines calls in the parent_texts
137
version_id = osutils.safe_revision_id(version_id)
138
parents = [osutils.safe_revision_id(v) for v in parents]
139
self._check_write_ok()
140
return self._add_lines(version_id, parents, lines, parent_texts,
141
left_matching_blocks)
143
def _add_lines(self, version_id, parents, lines, parent_texts,
144
left_matching_blocks):
145
"""Helper to do the class specific add_lines."""
146
raise NotImplementedError(self.add_lines)
148
def add_lines_with_ghosts(self, version_id, parents, lines,
150
"""Add lines to the versioned file, allowing ghosts to be present.
152
This takes the same parameters as add_lines.
154
version_id = osutils.safe_revision_id(version_id)
155
parents = [osutils.safe_revision_id(v) for v in parents]
156
self._check_write_ok()
157
return self._add_lines_with_ghosts(version_id, parents, lines,
160
def _add_lines_with_ghosts(self, version_id, parents, lines, parent_texts):
161
"""Helper to do class specific add_lines_with_ghosts."""
162
raise NotImplementedError(self.add_lines_with_ghosts)
164
def check(self, progress_bar=None):
165
"""Check the versioned file for integrity."""
166
raise NotImplementedError(self.check)
168
def _check_lines_not_unicode(self, lines):
169
"""Check that lines being added to a versioned file are not unicode."""
171
if line.__class__ is not str:
172
raise errors.BzrBadParameterUnicode("lines")
174
def _check_lines_are_lines(self, lines):
175
"""Check that the lines really are full lines without inline EOL."""
177
if '\n' in line[:-1]:
178
raise errors.BzrBadParameterContainsNewline("lines")
180
def _check_write_ok(self):
181
"""Is the versioned file marked as 'finished' ? Raise if it is."""
183
raise errors.OutSideTransaction()
184
if self._access_mode != 'w':
185
raise errors.ReadOnlyObjectDirtiedError(self)
187
def enable_cache(self):
188
"""Tell this versioned file that it should cache any data it reads.
190
This is advisory, implementations do not have to support caching.
194
def clear_cache(self):
195
"""Remove any data cached in the versioned file object.
197
This only needs to be supported if caches are supported
201
def clone_text(self, new_version_id, old_version_id, parents):
202
"""Add an identical text to old_version_id as new_version_id.
204
Must raise RevisionNotPresent if the old version or any of the
205
parents are not present in file history.
207
Must raise RevisionAlreadyPresent if the new version is
208
already present in file history."""
209
new_version_id = osutils.safe_revision_id(new_version_id)
210
old_version_id = osutils.safe_revision_id(old_version_id)
211
self._check_write_ok()
212
return self._clone_text(new_version_id, old_version_id, parents)
214
def _clone_text(self, new_version_id, old_version_id, parents):
215
"""Helper function to do the _clone_text work."""
216
raise NotImplementedError(self.clone_text)
218
def create_empty(self, name, transport, mode=None):
219
"""Create a new versioned file of this exact type.
221
:param name: the file name
222
:param transport: the transport
223
:param mode: optional file mode.
225
raise NotImplementedError(self.create_empty)
227
def fix_parents(self, version_id, new_parents):
228
"""Fix the parents list for version.
230
This is done by appending a new version to the index
231
with identical data except for the parents list.
232
the parents list must be a superset of the current
235
version_id = osutils.safe_revision_id(version_id)
236
new_parents = [osutils.safe_revision_id(p) for p in new_parents]
237
self._check_write_ok()
238
return self._fix_parents(version_id, new_parents)
240
def _fix_parents(self, version_id, new_parents):
241
"""Helper for fix_parents."""
242
raise NotImplementedError(self.fix_parents)
244
def get_delta(self, version):
245
"""Get a delta for constructing version from some other version.
247
:return: (delta_parent, sha1, noeol, delta)
248
Where delta_parent is a version id or None to indicate no parent.
250
raise NotImplementedError(self.get_delta)
252
def get_deltas(self, version_ids):
253
"""Get multiple deltas at once for constructing versions.
255
:return: dict(version_id:(delta_parent, sha1, noeol, delta))
256
Where delta_parent is a version id or None to indicate no parent, and
257
version_id is the version_id created by that delta.
260
for version_id in version_ids:
261
result[version_id] = self.get_delta(version_id)
264
def get_format_signature(self):
265
"""Get a text description of the data encoding in this file.
269
raise NotImplementedError(self.get_format_signature)
271
def make_mpdiffs(self, version_ids):
272
"""Create multiparent diffs for specified versions"""
273
knit_versions = set()
274
for version_id in version_ids:
275
knit_versions.add(version_id)
276
knit_versions.update(self.get_parents(version_id))
277
lines = dict(zip(knit_versions,
278
self._get_lf_split_line_list(knit_versions)))
280
for version_id in version_ids:
281
target = lines[version_id]
282
parents = [lines[p] for p in self.get_parents(version_id)]
284
left_parent_blocks = self._extract_blocks(version_id,
287
left_parent_blocks = None
288
diffs.append(multiparent.MultiParent.from_lines(target, parents,
292
def _extract_blocks(self, version_id, source, target):
295
def add_mpdiffs(self, records):
296
"""Add mpdiffs to this versionedfile
298
Records should be iterables of version, parents, expected_sha1,
299
mpdiff. mpdiff should be a MultiParent instance.
302
mpvf = multiparent.MultiMemoryVersionedFile()
304
for version, parent_ids, expected_sha1, mpdiff in records:
305
versions.append(version)
306
mpvf.add_diff(mpdiff, version, parent_ids)
307
needed_parents = set()
308
for version, parent_ids, expected_sha1, mpdiff in records:
309
needed_parents.update(p for p in parent_ids
310
if not mpvf.has_version(p))
311
for parent_id, lines in zip(needed_parents,
312
self._get_lf_split_line_list(needed_parents)):
313
mpvf.add_version(lines, parent_id, [])
314
for (version, parent_ids, expected_sha1, mpdiff), lines in\
315
zip(records, mpvf.get_line_list(versions)):
316
if len(parent_ids) == 1:
317
left_matching_blocks = list(mpdiff.get_matching_blocks(0,
318
mpvf.get_diff(parent_ids[0]).num_lines()))
320
left_matching_blocks = None
321
version_text = self.add_lines(version, parent_ids, lines,
322
vf_parents, left_matching_blocks=left_matching_blocks)
323
vf_parents[version] = version_text
324
for (version, parent_ids, expected_sha1, mpdiff), sha1 in\
325
zip(records, self.get_sha1s(versions)):
326
if expected_sha1 != sha1:
327
raise errors.VersionedFileInvalidChecksum(version)
329
def get_sha1(self, version_id):
330
"""Get the stored sha1 sum for the given revision.
332
:param name: The name of the version to lookup
334
raise NotImplementedError(self.get_sha1)
336
def get_sha1s(self, version_ids):
337
"""Get the stored sha1 sums for the given revisions.
339
:param version_ids: The names of the versions to lookup
340
:return: a list of sha1s in order according to the version_ids
342
raise NotImplementedError(self.get_sha1)
344
def get_suffixes(self):
345
"""Return the file suffixes associated with this versioned file."""
346
raise NotImplementedError(self.get_suffixes)
348
def get_text(self, version_id):
349
"""Return version contents as a text string.
351
Raises RevisionNotPresent if version is not present in
354
return ''.join(self.get_lines(version_id))
355
get_string = get_text
357
def get_texts(self, version_ids):
358
"""Return the texts of listed versions as a list of strings.
360
Raises RevisionNotPresent if version is not present in
363
return [''.join(self.get_lines(v)) for v in version_ids]
365
def get_lines(self, version_id):
366
"""Return version contents as a sequence of lines.
368
Raises RevisionNotPresent if version is not present in
371
raise NotImplementedError(self.get_lines)
373
def _get_lf_split_line_list(self, version_ids):
374
return [StringIO(t).readlines() for t in self.get_texts(version_ids)]
376
def get_ancestry(self, version_ids, topo_sorted=True):
377
"""Return a list of all ancestors of given version(s). This
378
will not include the null revision.
380
This list will not be topologically sorted if topo_sorted=False is
383
Must raise RevisionNotPresent if any of the given versions are
384
not present in file history."""
385
if isinstance(version_ids, basestring):
386
version_ids = [version_ids]
387
raise NotImplementedError(self.get_ancestry)
389
def get_ancestry_with_ghosts(self, version_ids):
390
"""Return a list of all ancestors of given version(s). This
391
will not include the null revision.
393
Must raise RevisionNotPresent if any of the given versions are
394
not present in file history.
396
Ghosts that are known about will be included in ancestry list,
397
but are not explicitly marked.
399
raise NotImplementedError(self.get_ancestry_with_ghosts)
401
def get_graph(self, version_ids=None):
402
"""Return a graph from the versioned file.
404
Ghosts are not listed or referenced in the graph.
405
:param version_ids: Versions to select.
406
None means retrieve all versions.
408
if version_ids is None:
409
return dict(self.iter_parents(self.versions()))
411
pending = set(osutils.safe_revision_id(v) for v in version_ids)
413
this_iteration = pending
415
for version, parents in self.iter_parents(this_iteration):
416
result[version] = parents
417
for parent in parents:
423
def get_graph_with_ghosts(self):
424
"""Return a graph for the entire versioned file.
426
Ghosts are referenced in parents list but are not
429
raise NotImplementedError(self.get_graph_with_ghosts)
431
def get_parents(self, version_id):
432
"""Return version names for parents of a version.
434
Must raise RevisionNotPresent if version is not present in
437
raise NotImplementedError(self.get_parents)
439
def get_parents_with_ghosts(self, version_id):
440
"""Return version names for parents of version_id.
442
Will raise RevisionNotPresent if version_id is not present
445
Ghosts that are known about will be included in the parent list,
446
but are not explicitly marked.
448
raise NotImplementedError(self.get_parents_with_ghosts)
450
def annotate_iter(self, version_id):
451
"""Yield list of (version-id, line) pairs for the specified
454
Must raise RevisionNotPresent if any of the given versions are
455
not present in file history.
457
raise NotImplementedError(self.annotate_iter)
459
def annotate(self, version_id):
460
return list(self.annotate_iter(version_id))
462
def _apply_delta(self, lines, delta):
463
"""Apply delta to lines."""
466
for start, end, count, delta_lines in delta:
467
lines[offset+start:offset+end] = delta_lines
468
offset = offset + (start - end) + count
471
def join(self, other, pb=None, msg=None, version_ids=None,
472
ignore_missing=False):
473
"""Integrate versions from other into this versioned file.
475
If version_ids is None all versions from other should be
476
incorporated into this versioned file.
478
Must raise RevisionNotPresent if any of the specified versions
479
are not present in the other files history unless ignore_missing
480
is supplied when they are silently skipped.
482
self._check_write_ok()
483
return InterVersionedFile.get(other, self).join(
489
def iter_lines_added_or_present_in_versions(self, version_ids=None,
491
"""Iterate over the lines in the versioned file from version_ids.
493
This may return lines from other versions, and does not return the
494
specific version marker at this point. The api may be changed
495
during development to include the version that the versioned file
496
thinks is relevant, but given that such hints are just guesses,
497
its better not to have it if we don't need it.
499
If a progress bar is supplied, it may be used to indicate progress.
500
The caller is responsible for cleaning up progress bars (because this
503
NOTES: Lines are normalised: they will all have \n terminators.
504
Lines are returned in arbitrary order.
506
raise NotImplementedError(self.iter_lines_added_or_present_in_versions)
508
def iter_parents(self, version_ids):
509
"""Iterate through the parents for many version ids.
511
:param version_ids: An iterable yielding version_ids.
512
:return: An iterator that yields (version_id, parents). Requested
513
version_ids not present in the versioned file are simply skipped.
514
The order is undefined, allowing for different optimisations in
515
the underlying implementation.
517
for version_id in version_ids:
519
yield version_id, tuple(self.get_parents(version_id))
520
except errors.RevisionNotPresent:
523
def transaction_finished(self):
524
"""The transaction that this file was opened in has finished.
526
This records self.finished = True and should cause all mutating
531
def plan_merge(self, ver_a, ver_b):
532
"""Return pseudo-annotation indicating how the two versions merge.
534
This is computed between versions a and b and their common
537
Weave lines present in none of them are skipped entirely.
540
killed-base Dead in base revision
541
killed-both Killed in each revision
544
unchanged Alive in both a and b (possibly created in both)
547
ghost-a Killed in a, unborn in b
548
ghost-b Killed in b, unborn in a
549
irrelevant Not in either revision
551
raise NotImplementedError(VersionedFile.plan_merge)
553
def weave_merge(self, plan, a_marker=TextMerge.A_MARKER,
554
b_marker=TextMerge.B_MARKER):
555
return PlanWeaveMerge(plan, a_marker, b_marker).merge_lines()[0]
558
class PlanWeaveMerge(TextMerge):
559
"""Weave merge that takes a plan as its input.
561
This exists so that VersionedFile.plan_merge is implementable.
562
Most callers will want to use WeaveMerge instead.
565
def __init__(self, plan, a_marker=TextMerge.A_MARKER,
566
b_marker=TextMerge.B_MARKER):
567
TextMerge.__init__(self, a_marker, b_marker)
570
def _merge_struct(self):
575
def outstanding_struct():
576
if not lines_a and not lines_b:
578
elif ch_a and not ch_b:
581
elif ch_b and not ch_a:
583
elif lines_a == lines_b:
586
yield (lines_a, lines_b)
588
# We previously considered either 'unchanged' or 'killed-both' lines
589
# to be possible places to resynchronize. However, assuming agreement
590
# on killed-both lines may be too aggressive. -- mbp 20060324
591
for state, line in self.plan:
592
if state == 'unchanged':
593
# resync and flush queued conflicts changes if any
594
for struct in outstanding_struct():
600
if state == 'unchanged':
603
elif state == 'killed-a':
606
elif state == 'killed-b':
609
elif state == 'new-a':
612
elif state == 'new-b':
616
assert state in ('irrelevant', 'ghost-a', 'ghost-b',
617
'killed-base', 'killed-both'), state
618
for struct in outstanding_struct():
622
class WeaveMerge(PlanWeaveMerge):
623
"""Weave merge that takes a VersionedFile and two versions as its input"""
625
def __init__(self, versionedfile, ver_a, ver_b,
626
a_marker=PlanWeaveMerge.A_MARKER, b_marker=PlanWeaveMerge.B_MARKER):
627
plan = versionedfile.plan_merge(ver_a, ver_b)
628
PlanWeaveMerge.__init__(self, plan, a_marker, b_marker)
631
class InterVersionedFile(InterObject):
632
"""This class represents operations taking place between two versionedfiles..
634
Its instances have methods like join, and contain
635
references to the source and target versionedfiles these operations can be
638
Often we will provide convenience methods on 'versionedfile' which carry out
639
operations with another versionedfile - they will always forward to
640
InterVersionedFile.get(other).method_name(parameters).
644
"""The available optimised InterVersionedFile types."""
646
def join(self, pb=None, msg=None, version_ids=None, ignore_missing=False):
647
"""Integrate versions from self.source into self.target.
649
If version_ids is None all versions from source should be
650
incorporated into this versioned file.
652
Must raise RevisionNotPresent if any of the specified versions
653
are not present in the other files history unless ignore_missing is
654
supplied when they are silently skipped.
657
# - if the target is empty, just add all the versions from
658
# source to target, otherwise:
659
# - make a temporary versioned file of type target
660
# - insert the source content into it one at a time
662
if not self.target.versions():
665
# Make a new target-format versioned file.
666
temp_source = self.target.create_empty("temp", MemoryTransport())
668
version_ids = self._get_source_version_ids(version_ids, ignore_missing)
669
graph = self.source.get_graph(version_ids)
670
order = tsort.topo_sort(graph.items())
671
pb = ui.ui_factory.nested_progress_bar()
674
# TODO for incremental cross-format work:
675
# make a versioned file with the following content:
676
# all revisions we have been asked to join
677
# all their ancestors that are *not* in target already.
678
# the immediate parents of the above two sets, with
679
# empty parent lists - these versions are in target already
680
# and the incorrect version data will be ignored.
681
# TODO: for all ancestors that are present in target already,
682
# check them for consistent data, this requires moving sha1 from
684
# TODO: remove parent texts when they are not relevant any more for
685
# memory pressure reduction. RBC 20060313
686
# pb.update('Converting versioned data', 0, len(order))
687
# deltas = self.source.get_deltas(order)
688
for index, version in enumerate(order):
689
pb.update('Converting versioned data', index, len(order))
690
parent_text = target.add_lines(version,
691
self.source.get_parents(version),
692
self.source.get_lines(version),
693
parent_texts=parent_texts)
694
parent_texts[version] = parent_text
695
#delta_parent, sha1, noeol, delta = deltas[version]
696
#target.add_delta(version,
697
# self.source.get_parents(version),
702
#target.get_lines(version)
704
# this should hit the native code path for target
705
if target is not self.target:
706
return self.target.join(temp_source,
714
def _get_source_version_ids(self, version_ids, ignore_missing):
715
"""Determine the version ids to be used from self.source.
717
:param version_ids: The caller-supplied version ids to check. (None
718
for all). If None is in version_ids, it is stripped.
719
:param ignore_missing: if True, remove missing ids from the version
720
list. If False, raise RevisionNotPresent on
721
a missing version id.
722
:return: A set of version ids.
724
if version_ids is None:
725
# None cannot be in source.versions
726
return set(self.source.versions())
728
version_ids = [osutils.safe_revision_id(v) for v in version_ids]
730
return set(self.source.versions()).intersection(set(version_ids))
732
new_version_ids = set()
733
for version in version_ids:
736
if not self.source.has_version(version):
737
raise errors.RevisionNotPresent(version, str(self.source))
739
new_version_ids.add(version)
740
return new_version_ids