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.graph import Graph
34
from bzrlib.transport.memory import MemoryTransport
37
from cStringIO import StringIO
39
from bzrlib.inter import InterObject
40
from bzrlib.symbol_versioning import *
41
from bzrlib.textmerge import TextMerge
44
class VersionedFile(object):
45
"""Versioned text file storage.
47
A versioned file manages versions of line-based text files,
48
keeping track of the originating version for each line.
50
To clients the "lines" of the file are represented as a list of
51
strings. These strings will typically have terminal newline
52
characters, but this is not required. In particular files commonly
53
do not have a newline at the end of the file.
55
Texts are identified by a version-id string.
59
def check_not_reserved_id(version_id):
60
revision.check_not_reserved_id(version_id)
62
def copy_to(self, name, transport):
63
"""Copy this versioned file to name on transport."""
64
raise NotImplementedError(self.copy_to)
67
"""Return a unsorted list of versions."""
68
raise NotImplementedError(self.versions)
70
@deprecated_method(one_four)
71
def has_ghost(self, version_id):
72
"""Returns whether version is present as a ghost."""
73
raise NotImplementedError(self.has_ghost)
75
def has_version(self, version_id):
76
"""Returns whether version is present."""
77
raise NotImplementedError(self.has_version)
79
def add_lines(self, version_id, parents, lines, parent_texts=None,
80
left_matching_blocks=None, nostore_sha=None, random_id=False,
82
"""Add a single text on top of the versioned file.
84
Must raise RevisionAlreadyPresent if the new version is
85
already present in file history.
87
Must raise RevisionNotPresent if any of the given parents are
88
not present in file history.
90
:param lines: A list of lines. Each line must be a bytestring. And all
91
of them except the last must be terminated with \n and contain no
92
other \n's. The last line may either contain no \n's or a single
93
terminated \n. If the lines list does meet this constraint the add
94
routine may error or may succeed - but you will be unable to read
95
the data back accurately. (Checking the lines have been split
96
correctly is expensive and extremely unlikely to catch bugs so it
97
is not done at runtime unless check_content is True.)
98
:param parent_texts: An optional dictionary containing the opaque
99
representations of some or all of the parents of version_id to
100
allow delta optimisations. VERY IMPORTANT: the texts must be those
101
returned by add_lines or data corruption can be caused.
102
:param left_matching_blocks: a hint about which areas are common
103
between the text and its left-hand-parent. The format is
104
the SequenceMatcher.get_matching_blocks format.
105
:param nostore_sha: Raise ExistingContent and do not add the lines to
106
the versioned file if the digest of the lines matches this.
107
:param random_id: If True a random id has been selected rather than
108
an id determined by some deterministic process such as a converter
109
from a foreign VCS. When True the backend may choose not to check
110
for uniqueness of the resulting key within the versioned file, so
111
this should only be done when the result is expected to be unique
113
:param check_content: If True, the lines supplied are verified to be
114
bytestrings that are correctly formed lines.
115
:return: The text sha1, the number of bytes in the text, and an opaque
116
representation of the inserted version which can be provided
117
back to future add_lines calls in the parent_texts dictionary.
119
self._check_write_ok()
120
return self._add_lines(version_id, parents, lines, parent_texts,
121
left_matching_blocks, nostore_sha, random_id, check_content)
123
def _add_lines(self, version_id, parents, lines, parent_texts,
124
left_matching_blocks, nostore_sha, random_id, check_content):
125
"""Helper to do the class specific add_lines."""
126
raise NotImplementedError(self.add_lines)
128
def add_lines_with_ghosts(self, version_id, parents, lines,
129
parent_texts=None, nostore_sha=None, random_id=False,
130
check_content=True, left_matching_blocks=None):
131
"""Add lines to the versioned file, allowing ghosts to be present.
133
This takes the same parameters as add_lines and returns the same.
135
self._check_write_ok()
136
return self._add_lines_with_ghosts(version_id, parents, lines,
137
parent_texts, nostore_sha, random_id, check_content, left_matching_blocks)
139
def _add_lines_with_ghosts(self, version_id, parents, lines, parent_texts,
140
nostore_sha, random_id, check_content, left_matching_blocks):
141
"""Helper to do class specific add_lines_with_ghosts."""
142
raise NotImplementedError(self.add_lines_with_ghosts)
144
def check(self, progress_bar=None):
145
"""Check the versioned file for integrity."""
146
raise NotImplementedError(self.check)
148
def _check_lines_not_unicode(self, lines):
149
"""Check that lines being added to a versioned file are not unicode."""
151
if line.__class__ is not str:
152
raise errors.BzrBadParameterUnicode("lines")
154
def _check_lines_are_lines(self, lines):
155
"""Check that the lines really are full lines without inline EOL."""
157
if '\n' in line[:-1]:
158
raise errors.BzrBadParameterContainsNewline("lines")
160
def enable_cache(self):
161
"""Tell this versioned file that it should cache any data it reads.
163
This is advisory, implementations do not have to support caching.
167
def clear_cache(self):
168
"""Remove any data cached in the versioned file object.
170
This only needs to be supported if caches are supported
174
def clone_text(self, new_version_id, old_version_id, parents):
175
"""Add an identical text to old_version_id as new_version_id.
177
Must raise RevisionNotPresent if the old version or any of the
178
parents are not present in file history.
180
Must raise RevisionAlreadyPresent if the new version is
181
already present in file history."""
182
self._check_write_ok()
183
return self._clone_text(new_version_id, old_version_id, parents)
185
def _clone_text(self, new_version_id, old_version_id, parents):
186
"""Helper function to do the _clone_text work."""
187
raise NotImplementedError(self.clone_text)
189
def get_format_signature(self):
190
"""Get a text description of the data encoding in this file.
194
raise NotImplementedError(self.get_format_signature)
196
def make_mpdiffs(self, version_ids):
197
"""Create multiparent diffs for specified versions."""
198
knit_versions = set()
199
knit_versions.update(version_ids)
200
parent_map = self.get_parent_map(version_ids)
201
for version_id in version_ids:
203
knit_versions.update(parent_map[version_id])
205
raise RevisionNotPresent(version_id, self)
206
# We need to filter out ghosts, because we can't diff against them.
207
knit_versions = set(self.get_parent_map(knit_versions).keys())
208
lines = dict(zip(knit_versions,
209
self._get_lf_split_line_list(knit_versions)))
211
for version_id in version_ids:
212
target = lines[version_id]
214
parents = [lines[p] for p in parent_map[version_id] if p in
217
raise RevisionNotPresent(version_id, self)
219
left_parent_blocks = self._extract_blocks(version_id,
222
left_parent_blocks = None
223
diffs.append(multiparent.MultiParent.from_lines(target, parents,
227
def _extract_blocks(self, version_id, source, target):
230
def add_mpdiffs(self, records):
231
"""Add mpdiffs to this VersionedFile.
233
Records should be iterables of version, parents, expected_sha1,
234
mpdiff. mpdiff should be a MultiParent instance.
236
# Does this need to call self._check_write_ok()? (IanC 20070919)
238
mpvf = multiparent.MultiMemoryVersionedFile()
240
for version, parent_ids, expected_sha1, mpdiff in records:
241
versions.append(version)
242
mpvf.add_diff(mpdiff, version, parent_ids)
243
needed_parents = set()
244
for version, parent_ids, expected_sha1, mpdiff in records:
245
needed_parents.update(p for p in parent_ids
246
if not mpvf.has_version(p))
247
present_parents = set(self.get_parent_map(needed_parents).keys())
248
for parent_id, lines in zip(present_parents,
249
self._get_lf_split_line_list(present_parents)):
250
mpvf.add_version(lines, parent_id, [])
251
for (version, parent_ids, expected_sha1, mpdiff), lines in\
252
zip(records, mpvf.get_line_list(versions)):
253
if len(parent_ids) == 1:
254
left_matching_blocks = list(mpdiff.get_matching_blocks(0,
255
mpvf.get_diff(parent_ids[0]).num_lines()))
257
left_matching_blocks = None
259
_, _, version_text = self.add_lines_with_ghosts(version,
260
parent_ids, lines, vf_parents,
261
left_matching_blocks=left_matching_blocks)
262
except NotImplementedError:
263
# The vf can't handle ghosts, so add lines normally, which will
264
# (reasonably) fail if there are ghosts in the data.
265
_, _, version_text = self.add_lines(version,
266
parent_ids, lines, vf_parents,
267
left_matching_blocks=left_matching_blocks)
268
vf_parents[version] = version_text
269
for (version, parent_ids, expected_sha1, mpdiff), sha1 in\
270
zip(records, self.get_sha1s(versions)):
271
if expected_sha1 != sha1:
272
raise errors.VersionedFileInvalidChecksum(version)
274
def get_sha1(self, version_id):
275
"""Get the stored sha1 sum for the given revision.
277
:param version_id: The name of the version to lookup
279
raise NotImplementedError(self.get_sha1)
281
def get_sha1s(self, version_ids):
282
"""Get the stored sha1 sums for the given revisions.
284
:param version_ids: The names of the versions to lookup
285
:return: a list of sha1s in order according to the version_ids
287
raise NotImplementedError(self.get_sha1s)
289
def get_text(self, version_id):
290
"""Return version contents as a text string.
292
Raises RevisionNotPresent if version is not present in
295
return ''.join(self.get_lines(version_id))
296
get_string = get_text
298
def get_texts(self, version_ids):
299
"""Return the texts of listed versions as a list of strings.
301
Raises RevisionNotPresent if version is not present in
304
return [''.join(self.get_lines(v)) for v in version_ids]
306
def get_lines(self, version_id):
307
"""Return version contents as a sequence of lines.
309
Raises RevisionNotPresent if version is not present in
312
raise NotImplementedError(self.get_lines)
314
def _get_lf_split_line_list(self, version_ids):
315
return [StringIO(t).readlines() for t in self.get_texts(version_ids)]
317
def get_ancestry(self, version_ids, topo_sorted=True):
318
"""Return a list of all ancestors of given version(s). This
319
will not include the null revision.
321
This list will not be topologically sorted if topo_sorted=False is
324
Must raise RevisionNotPresent if any of the given versions are
325
not present in file history."""
326
if isinstance(version_ids, basestring):
327
version_ids = [version_ids]
328
raise NotImplementedError(self.get_ancestry)
330
def get_ancestry_with_ghosts(self, version_ids):
331
"""Return a list of all ancestors of given version(s). This
332
will not include the null revision.
334
Must raise RevisionNotPresent if any of the given versions are
335
not present in file history.
337
Ghosts that are known about will be included in ancestry list,
338
but are not explicitly marked.
340
raise NotImplementedError(self.get_ancestry_with_ghosts)
342
@deprecated_method(one_four)
343
def get_graph(self, version_ids=None):
344
"""Return a graph from the versioned file.
346
Ghosts are not listed or referenced in the graph.
347
:param version_ids: Versions to select.
348
None means retrieve all versions.
350
if version_ids is None:
351
result = self.get_parent_map(self.versions())
354
pending = set(version_ids)
356
this_iteration = pending
358
parents = self.get_parent_map(this_iteration)
359
for version, parents in parents.iteritems():
360
result[version] = parents
361
for parent in parents:
366
for parents in result.itervalues():
367
references.update(parents)
368
existing_parents = self.get_parent_map(references)
369
for key, parents in result.iteritems():
370
present_parents = [parent for parent in parents if parent in
372
result[key] = tuple(present_parents)
375
@deprecated_method(one_four)
376
def get_graph_with_ghosts(self):
377
"""Return a graph for the entire versioned file.
379
Ghosts are referenced in parents list but are not
382
raise NotImplementedError(self.get_graph_with_ghosts)
384
def get_parent_map(self, version_ids):
385
"""Get a map of the parents of version_ids.
387
:param version_ids: The version ids to look up parents for.
388
:return: A mapping from version id to parents.
390
raise NotImplementedError(self.get_parent_map)
392
@deprecated_method(one_four)
393
def get_parents(self, version_id):
394
"""Return version names for parents of a version.
396
Must raise RevisionNotPresent if version is not present in
400
all = self.get_parent_map([version_id])[version_id]
402
raise errors.RevisionNotPresent(version_id, self)
404
parent_parents = self.get_parent_map(all)
405
for version_id in all:
406
if version_id in parent_parents:
407
result.append(version_id)
410
def get_parents_with_ghosts(self, version_id):
411
"""Return version names for parents of version_id.
413
Will raise RevisionNotPresent if version_id is not present
416
Ghosts that are known about will be included in the parent list,
417
but are not explicitly marked.
420
return list(self.get_parent_map([version_id])[version_id])
422
raise errors.RevisionNotPresent(version_id, self)
424
def annotate_iter(self, version_id):
425
"""Yield list of (version-id, line) pairs for the specified
428
Must raise RevisionNotPresent if the given version is
429
not present in file history.
431
raise NotImplementedError(self.annotate_iter)
433
def annotate(self, version_id):
434
return list(self.annotate_iter(version_id))
436
def join(self, other, pb=None, msg=None, version_ids=None,
437
ignore_missing=False):
438
"""Integrate versions from other into this versioned file.
440
If version_ids is None all versions from other should be
441
incorporated into this versioned file.
443
Must raise RevisionNotPresent if any of the specified versions
444
are not present in the other file's history unless ignore_missing
445
is supplied in which case they are silently skipped.
447
self._check_write_ok()
448
return InterVersionedFile.get(other, self).join(
454
def iter_lines_added_or_present_in_versions(self, version_ids=None,
456
"""Iterate over the lines in the versioned file from version_ids.
458
This may return lines from other versions. Each item the returned
459
iterator yields is a tuple of a line and a text version that that line
460
is present in (not introduced in).
462
Ordering of results is in whatever order is most suitable for the
463
underlying storage format.
465
If a progress bar is supplied, it may be used to indicate progress.
466
The caller is responsible for cleaning up progress bars (because this
469
NOTES: Lines are normalised: they will all have \n terminators.
470
Lines are returned in arbitrary order.
472
:return: An iterator over (line, version_id).
474
raise NotImplementedError(self.iter_lines_added_or_present_in_versions)
476
@deprecated_method(one_four)
477
def iter_parents(self, version_ids):
478
"""Iterate through the parents for many version ids.
480
:param version_ids: An iterable yielding version_ids.
481
:return: An iterator that yields (version_id, parents). Requested
482
version_ids not present in the versioned file are simply skipped.
483
The order is undefined, allowing for different optimisations in
484
the underlying implementation.
486
return self.get_parent_map(version_ids).iteritems()
488
def plan_merge(self, ver_a, ver_b):
489
"""Return pseudo-annotation indicating how the two versions merge.
491
This is computed between versions a and b and their common
494
Weave lines present in none of them are skipped entirely.
497
killed-base Dead in base revision
498
killed-both Killed in each revision
501
unchanged Alive in both a and b (possibly created in both)
504
ghost-a Killed in a, unborn in b
505
ghost-b Killed in b, unborn in a
506
irrelevant Not in either revision
508
raise NotImplementedError(VersionedFile.plan_merge)
510
def weave_merge(self, plan, a_marker=TextMerge.A_MARKER,
511
b_marker=TextMerge.B_MARKER):
512
return PlanWeaveMerge(plan, a_marker, b_marker).merge_lines()[0]
515
class _PlanMergeVersionedFile(object):
516
"""A VersionedFile for uncommitted and committed texts.
518
It is intended to allow merges to be planned with working tree texts.
519
It implements only the small part of the VersionedFile interface used by
520
PlanMerge. It falls back to multiple versionedfiles for data not stored in
521
_PlanMergeVersionedFile itself.
524
def __init__(self, file_id, fallback_versionedfiles=None):
527
:param file_id: Used when raising exceptions.
528
:param fallback_versionedfiles: If supplied, the set of fallbacks to
529
use. Otherwise, _PlanMergeVersionedFile.fallback_versionedfiles
530
can be appended to later.
532
self._file_id = file_id
533
if fallback_versionedfiles is None:
534
self.fallback_versionedfiles = []
536
self.fallback_versionedfiles = fallback_versionedfiles
540
def plan_merge(self, ver_a, ver_b, base=None):
541
"""See VersionedFile.plan_merge"""
542
from bzrlib.merge import _PlanMerge
544
return _PlanMerge(ver_a, ver_b, self).plan_merge()
545
old_plan = list(_PlanMerge(ver_a, base, self).plan_merge())
546
new_plan = list(_PlanMerge(ver_a, ver_b, self).plan_merge())
547
return _PlanMerge._subtract_plans(old_plan, new_plan)
549
def plan_lca_merge(self, ver_a, ver_b, base=None):
550
from bzrlib.merge import _PlanLCAMerge
551
graph = self._get_graph()
552
new_plan = _PlanLCAMerge(ver_a, ver_b, self, graph).plan_merge()
555
old_plan = _PlanLCAMerge(ver_a, base, self, graph).plan_merge()
556
return _PlanLCAMerge._subtract_plans(list(old_plan), list(new_plan))
558
def add_lines(self, version_id, parents, lines):
559
"""See VersionedFile.add_lines
561
Lines are added locally, not fallback versionedfiles. Also, ghosts are
562
permitted. Only reserved ids are permitted.
564
if not revision.is_reserved_id(version_id):
565
raise ValueError('Only reserved ids may be used')
567
raise ValueError('Parents may not be None')
569
raise ValueError('Lines may not be None')
570
self._parents[version_id] = tuple(parents)
571
self._lines[version_id] = lines
573
def get_lines(self, version_id):
574
"""See VersionedFile.get_ancestry"""
575
lines = self._lines.get(version_id)
576
if lines is not None:
578
for versionedfile in self.fallback_versionedfiles:
580
return versionedfile.get_lines(version_id)
581
except errors.RevisionNotPresent:
584
raise errors.RevisionNotPresent(version_id, self._file_id)
586
def get_ancestry(self, version_id, topo_sorted=False):
587
"""See VersionedFile.get_ancestry.
589
Note that this implementation assumes that if a VersionedFile can
590
answer get_ancestry at all, it can give an authoritative answer. In
591
fact, ghosts can invalidate this assumption. But it's good enough
592
99% of the time, and far cheaper/simpler.
594
Also note that the results of this version are never topologically
595
sorted, and are a set.
598
raise ValueError('This implementation does not provide sorting')
599
parents = self._parents.get(version_id)
601
for vf in self.fallback_versionedfiles:
603
return vf.get_ancestry(version_id, topo_sorted=False)
604
except errors.RevisionNotPresent:
607
raise errors.RevisionNotPresent(version_id, self._file_id)
608
ancestry = set([version_id])
609
for parent in parents:
610
ancestry.update(self.get_ancestry(parent, topo_sorted=False))
613
def get_parent_map(self, version_ids):
614
"""See VersionedFile.get_parent_map"""
616
pending = set(version_ids)
617
for key in version_ids:
619
result[key] = self._parents[key]
622
pending = pending - set(result.keys())
623
for versionedfile in self.fallback_versionedfiles:
624
parents = versionedfile.get_parent_map(pending)
625
result.update(parents)
626
pending = pending - set(parents.keys())
631
def _get_graph(self):
632
from bzrlib.graph import (
635
_StackedParentsProvider,
637
from bzrlib.repofmt.knitrepo import _KnitParentsProvider
638
parent_providers = [DictParentsProvider(self._parents)]
639
for vf in self.fallback_versionedfiles:
640
parent_providers.append(_KnitParentsProvider(vf))
641
return Graph(_StackedParentsProvider(parent_providers))
644
class PlanWeaveMerge(TextMerge):
645
"""Weave merge that takes a plan as its input.
647
This exists so that VersionedFile.plan_merge is implementable.
648
Most callers will want to use WeaveMerge instead.
651
def __init__(self, plan, a_marker=TextMerge.A_MARKER,
652
b_marker=TextMerge.B_MARKER):
653
TextMerge.__init__(self, a_marker, b_marker)
656
def _merge_struct(self):
661
def outstanding_struct():
662
if not lines_a and not lines_b:
664
elif ch_a and not ch_b:
667
elif ch_b and not ch_a:
669
elif lines_a == lines_b:
672
yield (lines_a, lines_b)
674
# We previously considered either 'unchanged' or 'killed-both' lines
675
# to be possible places to resynchronize. However, assuming agreement
676
# on killed-both lines may be too aggressive. -- mbp 20060324
677
for state, line in self.plan:
678
if state == 'unchanged':
679
# resync and flush queued conflicts changes if any
680
for struct in outstanding_struct():
686
if state == 'unchanged':
689
elif state == 'killed-a':
692
elif state == 'killed-b':
695
elif state == 'new-a':
698
elif state == 'new-b':
701
elif state == 'conflicted-a':
704
elif state == 'conflicted-b':
708
assert state in ('irrelevant', 'ghost-a', 'ghost-b',
709
'killed-base', 'killed-both'), state
710
for struct in outstanding_struct():
714
class WeaveMerge(PlanWeaveMerge):
715
"""Weave merge that takes a VersionedFile and two versions as its input."""
717
def __init__(self, versionedfile, ver_a, ver_b,
718
a_marker=PlanWeaveMerge.A_MARKER, b_marker=PlanWeaveMerge.B_MARKER):
719
plan = versionedfile.plan_merge(ver_a, ver_b)
720
PlanWeaveMerge.__init__(self, plan, a_marker, b_marker)
723
class InterVersionedFile(InterObject):
724
"""This class represents operations taking place between two VersionedFiles.
726
Its instances have methods like join, and contain
727
references to the source and target versionedfiles these operations can be
730
Often we will provide convenience methods on 'versionedfile' which carry out
731
operations with another versionedfile - they will always forward to
732
InterVersionedFile.get(other).method_name(parameters).
736
"""The available optimised InterVersionedFile types."""
738
def join(self, pb=None, msg=None, version_ids=None, ignore_missing=False):
739
"""Integrate versions from self.source into self.target.
741
If version_ids is None all versions from source should be
742
incorporated into this versioned file.
744
Must raise RevisionNotPresent if any of the specified versions
745
are not present in the other file's history unless ignore_missing is
746
supplied in which case they are silently skipped.
749
version_ids = self._get_source_version_ids(version_ids, ignore_missing)
750
graph = Graph(self.source)
751
search = graph._make_breadth_first_searcher(version_ids)
752
transitive_ids = set()
753
map(transitive_ids.update, list(search))
754
parent_map = self.source.get_parent_map(transitive_ids)
755
order = tsort.topo_sort(parent_map.items())
756
pb = ui.ui_factory.nested_progress_bar()
759
# TODO for incremental cross-format work:
760
# make a versioned file with the following content:
761
# all revisions we have been asked to join
762
# all their ancestors that are *not* in target already.
763
# the immediate parents of the above two sets, with
764
# empty parent lists - these versions are in target already
765
# and the incorrect version data will be ignored.
766
# TODO: for all ancestors that are present in target already,
767
# check them for consistent data, this requires moving sha1 from
769
# TODO: remove parent texts when they are not relevant any more for
770
# memory pressure reduction. RBC 20060313
771
# pb.update('Converting versioned data', 0, len(order))
773
for index, version in enumerate(order):
774
pb.update('Converting versioned data', index, total)
775
if version in target:
777
_, _, parent_text = target.add_lines(version,
779
self.source.get_lines(version),
780
parent_texts=parent_texts)
781
parent_texts[version] = parent_text
786
def _get_source_version_ids(self, version_ids, ignore_missing):
787
"""Determine the version ids to be used from self.source.
789
:param version_ids: The caller-supplied version ids to check. (None
790
for all). If None is in version_ids, it is stripped.
791
:param ignore_missing: if True, remove missing ids from the version
792
list. If False, raise RevisionNotPresent on
793
a missing version id.
794
:return: A set of version ids.
796
if version_ids is None:
797
# None cannot be in source.versions
798
return set(self.source.versions())
801
return set(self.source.versions()).intersection(set(version_ids))
803
new_version_ids = set()
804
for version in version_ids:
807
if not self.source.has_version(version):
808
raise errors.RevisionNotPresent(version, str(self.source))
810
new_version_ids.add(version)
811
return new_version_ids