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
40
from bzrlib.trace import mutter
43
class VersionedFile(object):
44
"""Versioned text file storage.
46
A versioned file manages versions of line-based text files,
47
keeping track of the originating version for each line.
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.
54
Texts are identified by a version-id string.
57
def __init__(self, access_mode):
59
self._access_mode = access_mode
62
def check_not_reserved_id(version_id):
63
revision.check_not_reserved_id(version_id)
65
def copy_to(self, name, transport):
66
"""Copy this versioned file to name on transport."""
67
raise NotImplementedError(self.copy_to)
70
"""Return a unsorted list of versions."""
71
raise NotImplementedError(self.versions)
73
def has_ghost(self, version_id):
74
"""Returns whether version is present as a ghost."""
75
raise NotImplementedError(self.has_ghost)
77
def has_version(self, version_id):
78
"""Returns whether version is present."""
79
raise NotImplementedError(self.has_version)
81
def add_lines(self, version_id, parents, lines, parent_texts=None,
82
left_matching_blocks=None, nostore_sha=None, random_id=False,
84
"""Add a single text on top of the versioned file.
86
Must raise RevisionAlreadyPresent if the new version is
87
already present in file history.
89
Must raise RevisionNotPresent if any of the given parents are
90
not present in file history.
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
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.
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)
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)
132
def add_lines_with_ghosts(self, version_id, parents, lines,
133
parent_texts=None, nostore_sha=None, random_id=False,
135
"""Add lines to the versioned file, allowing ghosts to be present.
137
This takes the same parameters as add_lines and returns the same.
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)
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)
150
def check(self, progress_bar=None):
151
"""Check the versioned file for integrity."""
152
raise NotImplementedError(self.check)
154
def _check_lines_not_unicode(self, lines):
155
"""Check that lines being added to a versioned file are not unicode."""
157
if line.__class__ is not str:
158
raise errors.BzrBadParameterUnicode("lines")
160
def _check_lines_are_lines(self, lines):
161
"""Check that the lines really are full lines without inline EOL."""
163
if '\n' in line[:-1]:
164
raise errors.BzrBadParameterContainsNewline("lines")
166
def _check_write_ok(self):
167
"""Is the versioned file marked as 'finished' ? Raise if it is."""
169
raise errors.OutSideTransaction()
170
if self._access_mode != 'w':
171
raise errors.ReadOnlyObjectDirtiedError(self)
173
def enable_cache(self):
174
"""Tell this versioned file that it should cache any data it reads.
176
This is advisory, implementations do not have to support caching.
180
def clear_cache(self):
181
"""Remove any data cached in the versioned file object.
183
This only needs to be supported if caches are supported
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.
190
Must raise RevisionNotPresent if the old version or any of the
191
parents are not present in file history.
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)
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)
205
def create_empty(self, name, transport, mode=None):
206
"""Create a new versioned file of this exact type.
208
:param name: the file name
209
:param transport: the transport
210
:param mode: optional file mode.
212
raise NotImplementedError(self.create_empty)
214
def get_format_signature(self):
215
"""Get a text description of the data encoding in this file.
219
raise NotImplementedError(self.get_format_signature)
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)))
230
for version_id in version_ids:
231
target = lines[version_id]
232
parents = [lines[p] for p in self.get_parents(version_id)]
234
left_parent_blocks = self._extract_blocks(version_id,
237
left_parent_blocks = None
238
diffs.append(multiparent.MultiParent.from_lines(target, parents,
242
def _extract_blocks(self, version_id, source, target):
245
def add_mpdiffs(self, records):
246
"""Add mpdiffs to this VersionedFile.
248
Records should be iterables of version, parents, expected_sha1,
249
mpdiff. mpdiff should be a MultiParent instance.
251
# Does this need to call self._check_write_ok()? (IanC 20070919)
253
mpvf = multiparent.MultiMemoryVersionedFile()
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()))
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)
280
def get_sha1(self, version_id):
281
"""Get the stored sha1 sum for the given revision.
283
:param version_id: The name of the version to lookup
285
raise NotImplementedError(self.get_sha1)
287
def get_sha1s(self, version_ids):
288
"""Get the stored sha1 sums for the given revisions.
290
:param version_ids: The names of the versions to lookup
291
:return: a list of sha1s in order according to the version_ids
293
raise NotImplementedError(self.get_sha1s)
295
def get_suffixes(self):
296
"""Return the file suffixes associated with this versioned file."""
297
raise NotImplementedError(self.get_suffixes)
299
def get_text(self, version_id):
300
"""Return version contents as a text string.
302
Raises RevisionNotPresent if version is not present in
305
return ''.join(self.get_lines(version_id))
306
get_string = get_text
308
def get_texts(self, version_ids):
309
"""Return the texts of listed versions as a list of strings.
311
Raises RevisionNotPresent if version is not present in
314
return [''.join(self.get_lines(v)) for v in version_ids]
316
def get_lines(self, version_id):
317
"""Return version contents as a sequence of lines.
319
Raises RevisionNotPresent if version is not present in
322
raise NotImplementedError(self.get_lines)
324
def _get_lf_split_line_list(self, version_ids):
325
return [StringIO(t).readlines() for t in self.get_texts(version_ids)]
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.
331
This list will not be topologically sorted if topo_sorted=False is
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)
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.
344
Must raise RevisionNotPresent if any of the given versions are
345
not present in file history.
347
Ghosts that are known about will be included in ancestry list,
348
but are not explicitly marked.
350
raise NotImplementedError(self.get_ancestry_with_ghosts)
352
def get_graph(self, version_ids=None):
353
"""Return a graph from the versioned file.
355
Ghosts are not listed or referenced in the graph.
356
:param version_ids: Versions to select.
357
None means retrieve all versions.
359
if version_ids is None:
360
return dict(self.iter_parents(self.versions()))
362
pending = set(osutils.safe_revision_id(v) for v in version_ids)
364
this_iteration = pending
366
for version, parents in self.iter_parents(this_iteration):
367
result[version] = parents
368
for parent in parents:
374
def get_graph_with_ghosts(self):
375
"""Return a graph for the entire versioned file.
377
Ghosts are referenced in parents list but are not
380
raise NotImplementedError(self.get_graph_with_ghosts)
382
def get_parents(self, version_id):
383
"""Return version names for parents of a version.
385
Must raise RevisionNotPresent if version is not present in
388
raise NotImplementedError(self.get_parents)
390
def get_parents_with_ghosts(self, version_id):
391
"""Return version names for parents of version_id.
393
Will raise RevisionNotPresent if version_id is not present
396
Ghosts that are known about will be included in the parent list,
397
but are not explicitly marked.
399
raise NotImplementedError(self.get_parents_with_ghosts)
401
def annotate_iter(self, version_id):
402
"""Yield list of (version-id, line) pairs for the specified
405
Must raise RevisionNotPresent if the given version is
406
not present in file history.
408
raise NotImplementedError(self.annotate_iter)
410
def annotate(self, version_id):
411
return list(self.annotate_iter(version_id))
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.
417
If version_ids is None all versions from other should be
418
incorporated into this versioned file.
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.
424
self._check_write_ok()
425
return InterVersionedFile.get(other, self).join(
431
def iter_lines_added_or_present_in_versions(self, version_ids=None,
433
"""Iterate over the lines in the versioned file from version_ids.
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.
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
445
NOTES: Lines are normalised: they will all have \n terminators.
446
Lines are returned in arbitrary order.
448
raise NotImplementedError(self.iter_lines_added_or_present_in_versions)
450
def iter_parents(self, version_ids):
451
"""Iterate through the parents for many version ids.
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.
459
for version_id in version_ids:
461
yield version_id, tuple(self.get_parents(version_id))
462
except errors.RevisionNotPresent:
465
def transaction_finished(self):
466
"""The transaction that this file was opened in has finished.
468
This records self.finished = True and should cause all mutating
473
def plan_merge(self, ver_a, ver_b):
474
"""Return pseudo-annotation indicating how the two versions merge.
476
This is computed between versions a and b and their common
479
Weave lines present in none of them are skipped entirely.
482
killed-base Dead in base revision
483
killed-both Killed in each revision
486
unchanged Alive in both a and b (possibly created in both)
489
ghost-a Killed in a, unborn in b
490
ghost-b Killed in b, unborn in a
491
irrelevant Not in either revision
493
raise NotImplementedError(VersionedFile.plan_merge)
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]
500
class PlanWeaveMerge(TextMerge):
501
"""Weave merge that takes a plan as its input.
503
This exists so that VersionedFile.plan_merge is implementable.
504
Most callers will want to use WeaveMerge instead.
507
def __init__(self, plan, a_marker=TextMerge.A_MARKER,
508
b_marker=TextMerge.B_MARKER):
509
TextMerge.__init__(self, a_marker, b_marker)
512
def _merge_struct(self):
517
def outstanding_struct():
518
if not lines_a and not lines_b:
520
elif ch_a and not ch_b:
523
elif ch_b and not ch_a:
525
elif lines_a == lines_b:
528
yield (lines_a, lines_b)
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():
542
if state == 'unchanged':
545
elif state == 'killed-a':
548
elif state == 'killed-b':
551
elif state == 'new-a':
554
elif state == 'new-b':
558
assert state in ('irrelevant', 'ghost-a', 'ghost-b',
559
'killed-base', 'killed-both'), state
560
for struct in outstanding_struct():
564
class WeaveMerge(PlanWeaveMerge):
565
"""Weave merge that takes a VersionedFile and two versions as its input."""
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)
573
class InterVersionedFile(InterObject):
574
"""This class represents operations taking place between two VersionedFiles.
576
Its instances have methods like join, and contain
577
references to the source and target versionedfiles these operations can be
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).
586
"""The available optimised InterVersionedFile types."""
588
def join(self, pb=None, msg=None, version_ids=None, ignore_missing=False):
589
"""Integrate versions from self.source into self.target.
591
If version_ids is None all versions from source should be
592
incorporated into this versioned file.
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.
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
604
if not self.target.versions():
607
# Make a new target-format versioned file.
608
temp_source = self.target.create_empty("temp", MemoryTransport())
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()
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
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))
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
638
# this should hit the native code path for target
639
if target is not self.target:
640
return self.target.join(temp_source,
650
def _get_source_version_ids(self, version_ids, ignore_missing):
651
"""Determine the version ids to be used from self.source.
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.
660
if version_ids is None:
661
# None cannot be in source.versions
662
return set(self.source.versions())
664
version_ids = [osutils.safe_revision_id(v) for v in version_ids]
666
return set(self.source.versions()).intersection(set(version_ids))
668
new_version_ids = set()
669
for version in version_ids:
672
if not self.source.has_version(version):
673
raise errors.RevisionNotPresent(version, str(self.source))
675
new_version_ids.add(version)
676
return new_version_ids