1
# Copyright (C) 2005, 2006 by Canonical Ltd
2
# Written by Martin Pool.
3
# Modified by Johan Rydberg <jrydberg@gnu.org>
4
# Modified by Robert Collins <robert.collins@canonical.com>
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
"""Knit versionedfile implementation.
22
A knit is a versioned file implementation that supports efficient append only
26
lifeless: the data file is made up of "delta records". each delta record has a delta header
27
that contains; (1) a version id, (2) the size of the delta (in lines), and (3) the digest of
28
the -expanded data- (ie, the delta applied to the parent). the delta also ends with a
29
end-marker; simply "end VERSION"
31
delta can be line or full contents.a
32
... the 8's there are the index number of the annotation.
33
version robertc@robertcollins.net-20051003014215-ee2990904cc4c7ad 7 c7d23b2a5bd6ca00e8e266cec0ec228158ee9f9e
37
8 e.set('executable', 'yes')
39
8 if elt.get('executable') == 'yes':
40
8 ie.executable = True
41
end robertc@robertcollins.net-20051003014215-ee2990904cc4c7ad
45
09:33 < jrydberg> lifeless: each index is made up of a tuple of; version id, options, position, size, parents
46
09:33 < jrydberg> lifeless: the parents are currently dictionary compressed
47
09:33 < jrydberg> lifeless: (meaning it currently does not support ghosts)
48
09:33 < lifeless> right
49
09:33 < jrydberg> lifeless: the position and size is the range in the data file
52
so the index sequence is the dictionary compressed sequence number used
53
in the deltas to provide line annotation
58
# 10:16 < lifeless> make partial index writes safe
59
# 10:16 < lifeless> implement 'knit.check()' like weave.check()
60
# 10:17 < lifeless> record known ghosts so we can detect when they are filled in rather than the current 'reweave
62
# move sha1 out of the content so that join is faster at verifying parents
63
# record content length ?
66
from cStringIO import StringIO
68
from difflib import SequenceMatcher
69
from gzip import GzipFile
72
import bzrlib.errors as errors
73
from bzrlib.errors import FileExists, NoSuchFile, KnitError, \
74
InvalidRevisionId, KnitCorrupt, KnitHeaderError, \
75
RevisionNotPresent, RevisionAlreadyPresent
76
from bzrlib.trace import mutter
77
from bzrlib.osutils import contains_whitespace, contains_linebreaks, \
79
from bzrlib.versionedfile import VersionedFile, InterVersionedFile
80
from bzrlib.tsort import topo_sort
83
# TODO: Split out code specific to this format into an associated object.
85
# TODO: Can we put in some kind of value to check that the index and data
86
# files belong together?
88
# TODO: accomodate binaries, perhaps by storing a byte count
90
# TODO: function to check whole file
92
# TODO: atomically append data, then measure backwards from the cursor
93
# position after writing to work out where it was located. we may need to
94
# bypass python file buffering.
97
INDEX_SUFFIX = '.kndx'
100
class KnitContent(object):
101
"""Content of a knit version to which deltas can be applied."""
103
def __init__(self, lines):
106
def annotate_iter(self):
107
"""Yield tuples of (origin, text) for each content line."""
108
for origin, text in self._lines:
112
"""Return a list of (origin, text) tuples."""
113
return list(self.annotate_iter())
115
def apply_delta(self, delta):
116
"""Apply delta to this content."""
118
for start, end, count, lines in delta:
119
self._lines[offset+start:offset+end] = lines
120
offset = offset + (start - end) + count
122
def line_delta_iter(self, new_lines):
123
"""Generate line-based delta from new_lines to this content."""
124
new_texts = [text for origin, text in new_lines._lines]
125
old_texts = [text for origin, text in self._lines]
126
s = difflib.SequenceMatcher(None, old_texts, new_texts)
127
for op in s.get_opcodes():
130
yield (op[1], op[2], op[4]-op[3], new_lines._lines[op[3]:op[4]])
132
def line_delta(self, new_lines):
133
return list(self.line_delta_iter(new_lines))
136
return [text for origin, text in self._lines]
139
class _KnitFactory(object):
140
"""Base factory for creating content objects."""
142
def make(self, lines, version):
143
num_lines = len(lines)
144
return KnitContent(zip([version] * num_lines, lines))
147
class KnitAnnotateFactory(_KnitFactory):
148
"""Factory for creating annotated Content objects."""
152
def parse_fulltext(self, content, version):
155
origin, text = line.split(' ', 1)
156
lines.append((int(origin), text))
157
return KnitContent(lines)
159
def parse_line_delta_iter(self, lines):
161
header = lines.pop(0)
162
start, end, c = [int(n) for n in header.split(',')]
165
origin, text = lines.pop(0).split(' ', 1)
166
contents.append((int(origin), text))
167
yield start, end, c, contents
169
def parse_line_delta(self, lines, version):
170
return list(self.parse_line_delta_iter(lines))
172
def lower_fulltext(self, content):
173
return ['%d %s' % (o, t) for o, t in content._lines]
175
def lower_line_delta(self, delta):
177
for start, end, c, lines in delta:
178
out.append('%d,%d,%d\n' % (start, end, c))
179
for origin, text in lines:
180
out.append('%d %s' % (origin, text))
184
class KnitPlainFactory(_KnitFactory):
185
"""Factory for creating plain Content objects."""
189
def parse_fulltext(self, content, version):
190
return self.make(content, version)
192
def parse_line_delta_iter(self, lines, version):
194
header = lines.pop(0)
195
start, end, c = [int(n) for n in header.split(',')]
196
yield start, end, c, zip([version] * c, lines[:c])
199
def parse_line_delta(self, lines, version):
200
return list(self.parse_line_delta_iter(lines, version))
202
def lower_fulltext(self, content):
203
return content.text()
205
def lower_line_delta(self, delta):
207
for start, end, c, lines in delta:
208
out.append('%d,%d,%d\n' % (start, end, c))
209
out.extend([text for origin, text in lines])
213
def make_empty_knit(transport, relpath):
214
"""Construct a empty knit at the specified location."""
215
k = KnitVersionedFile(transport, relpath, 'w', KnitPlainFactory)
219
class KnitVersionedFile(VersionedFile):
220
"""Weave-like structure with faster random access.
222
A knit stores a number of texts and a summary of the relationships
223
between them. Texts are identified by a string version-id. Texts
224
are normally stored and retrieved as a series of lines, but can
225
also be passed as single strings.
227
Lines are stored with the trailing newline (if any) included, to
228
avoid special cases for files with no final newline. Lines are
229
composed of 8-bit characters, not unicode. The combination of
230
these approaches should mean any 'binary' file can be safely
231
stored and retrieved.
234
def __init__(self, relpath, transport, file_mode=None, access_mode=None, factory=None,
235
basis_knit=None, delta=True, create=False):
236
"""Construct a knit at location specified by relpath.
238
:param create: If not True, only open an existing knit.
240
if access_mode is None:
242
assert access_mode in ('r', 'w'), "invalid mode specified %r" % access_mode
243
assert not basis_knit or isinstance(basis_knit, KnitVersionedFile), \
246
self.transport = transport
247
self.filename = relpath
248
self.basis_knit = basis_knit
249
self.factory = factory or KnitAnnotateFactory()
250
self.writable = (access_mode == 'w')
253
self._index = _KnitIndex(transport, relpath + INDEX_SUFFIX,
254
access_mode, create=create)
255
self._data = _KnitData(transport, relpath + DATA_SUFFIX,
256
access_mode, create=not len(self.versions()))
258
def copy_to(self, name, transport):
259
"""See VersionedFile.copy_to()."""
260
# copy the current index to a temp index to avoid racing with local
262
transport.put(name + INDEX_SUFFIX + '.tmp', self.transport.get(self._index._filename))
264
transport.put(name + DATA_SUFFIX, self._data._open_file())
265
# rename the copied index into place
266
transport.rename(name + INDEX_SUFFIX + '.tmp', name + INDEX_SUFFIX)
268
def create_empty(self, name, transport, mode=None):
269
return KnitVersionedFile(name, transport, factory=self.factory, delta=self.delta, create=True)
271
def fix_parents(self, version, new_parents):
272
"""Fix the parents list for version.
274
This is done by appending a new version to the index
275
with identical data except for the parents list.
276
the parents list must be a superset of the current
279
current_values = self._index._cache[version]
280
assert set(current_values[4]).difference(set(new_parents)) == set()
281
self._index.add_version(version,
287
def get_graph_with_ghosts(self):
288
"""See VersionedFile.get_graph_with_ghosts()."""
289
graph_items = self._index.get_graph()
290
return dict(graph_items)
294
"""See VersionedFile.get_suffixes()."""
295
return [DATA_SUFFIX, INDEX_SUFFIX]
297
def has_ghost(self, version_id):
298
"""True if there is a ghost reference in the file to version_id."""
300
if self.has_version(version_id):
302
# optimisable if needed by memoising the _ghosts set.
303
items = self._index.get_graph()
304
for node, parents in items:
305
for parent in parents:
306
if parent not in self._index._cache:
307
if parent == version_id:
312
"""See VersionedFile.versions."""
313
return self._index.get_versions()
315
def has_version(self, version_id):
316
"""See VersionedFile.has_version."""
317
return self._index.has_version(version_id)
319
__contains__ = has_version
321
def _merge_annotations(self, content, parents):
322
"""Merge annotations for content. This is done by comparing
323
the annotations based on changed to the text."""
324
for parent_id in parents:
325
merge_content = self._get_content(parent_id)
326
seq = SequenceMatcher(None, merge_content.text(), content.text())
327
for i, j, n in seq.get_matching_blocks():
330
content._lines[j:j+n] = merge_content._lines[i:i+n]
332
def _get_components(self, version_id):
333
"""Return a list of (version_id, method, data) tuples that
334
makes up version specified by version_id of the knit.
336
The components should be applied in the order of the returned
339
The basis knit will be used to the largest extent possible
340
since it is assumed that accesses to it is faster.
342
# needed_revisions holds a list of (method, version_id) of
343
# versions that is needed to be fetched to construct the final
344
# version of the file.
346
# basis_revisions is a list of versions that needs to be
347
# fetched but exists in the basis knit.
349
basis = self.basis_knit
356
if basis and basis._index.has_version(cursor):
358
basis_versions.append(cursor)
359
method = picked_knit._index.get_method(cursor)
360
needed_versions.append((method, cursor))
361
if method == 'fulltext':
363
cursor = picked_knit.get_parents(cursor)[0]
368
for comp_id in basis_versions:
369
data_pos, data_size = basis._index.get_data_position(comp_id)
370
records.append((piece_id, data_pos, data_size))
371
components.update(basis._data.read_records(records))
374
for comp_id in [vid for method, vid in needed_versions
375
if vid not in basis_versions]:
376
data_pos, data_size = self._index.get_position(comp_id)
377
records.append((comp_id, data_pos, data_size))
378
components.update(self._data.read_records(records))
380
# get_data_records returns a mapping with the version id as
381
# index and the value as data. The order the components need
382
# to be applied is held by needed_versions (reversed).
384
for method, comp_id in reversed(needed_versions):
385
out.append((comp_id, method, components[comp_id]))
389
def _get_content(self, version_id):
390
"""Returns a content object that makes up the specified
392
if not self.has_version(version_id):
393
raise RevisionNotPresent(version_id, self.filename)
395
if self.basis_knit and version_id in self.basis_knit:
396
return self.basis_knit._get_content(version_id)
399
components = self._get_components(version_id)
400
for component_id, method, (data, digest) in components:
401
version_idx = self._index.lookup(component_id)
402
if method == 'fulltext':
403
assert content is None
404
content = self.factory.parse_fulltext(data, version_idx)
405
elif method == 'line-delta':
406
delta = self.factory.parse_line_delta(data, version_idx)
407
content.apply_delta(delta)
409
if 'no-eol' in self._index.get_options(version_id):
410
line = content._lines[-1][1].rstrip('\n')
411
content._lines[-1] = (content._lines[-1][0], line)
413
if sha_strings(content.text()) != digest:
414
raise KnitCorrupt(self.filename, 'sha-1 does not match')
418
def _check_versions_present(self, version_ids):
419
"""Check that all specified versions are present."""
420
version_ids = set(version_ids)
421
for r in list(version_ids):
422
if self._index.has_version(r):
423
version_ids.remove(r)
425
raise RevisionNotPresent(list(version_ids)[0], self.filename)
427
def add_lines_with_ghosts(self, version_id, parents, lines):
428
"""See VersionedFile.add_lines_with_ghosts()."""
429
self._check_add(version_id, lines)
430
return self._add(version_id, lines[:], parents, self.delta)
432
def add_lines(self, version_id, parents, lines):
433
"""See VersionedFile.add_lines."""
434
self._check_add(version_id, lines)
435
self._check_versions_present(parents)
436
return self._add(version_id, lines[:], parents, self.delta)
438
def _check_add(self, version_id, lines):
439
"""check that version_id and lines are safe to add."""
440
assert self.writable, "knit is not opened for write"
441
### FIXME escape. RBC 20060228
442
if contains_whitespace(version_id):
443
raise InvalidRevisionId(version_id)
444
if self.has_version(version_id):
445
raise RevisionAlreadyPresent(version_id, self.filename)
447
if False or __debug__:
449
assert '\n' not in l[:-1]
451
def _add(self, version_id, lines, parents, delta):
452
"""Add a set of lines on top of version specified by parents.
454
If delta is true, compress the text as a line-delta against
457
Any versions not present will be converted into ghosts.
460
for parent in parents:
461
if not self.has_version(parent):
462
ghosts.append(parent)
464
if delta and not len(parents)-len(ghosts):
467
digest = sha_strings(lines)
470
if lines[-1][-1] != '\n':
471
options.append('no-eol')
472
lines[-1] = lines[-1] + '\n'
474
lines = self.factory.make(lines, len(self._index))
475
if self.factory.annotated and len(parents)-len(ghosts) > 0:
476
# Merge annotations from parent texts if so is needed.
477
self._merge_annotations(lines, parents)
479
if len(parents)-len(ghosts) and delta:
480
# To speed the extract of texts the delta chain is limited
481
# to a fixed number of deltas. This should minimize both
482
# I/O and the time spend applying deltas.
484
delta_parents = [parent for parent in parents if not parent in ghosts]
485
first_parent = delta_parents[0]
487
parent = delta_parents[0]
488
method = self._index.get_method(parent)
489
if method == 'fulltext':
491
delta_parents = self._index.get_parents(parent)
493
if method == 'line-delta':
497
options.append('line-delta')
498
content = self._get_content(first_parent)
499
delta_hunks = content.line_delta(lines)
500
store_lines = self.factory.lower_line_delta(delta_hunks)
502
options.append('fulltext')
503
store_lines = self.factory.lower_fulltext(lines)
505
where, size = self._data.add_record(version_id, digest, store_lines)
506
self._index.add_version(version_id, options, where, size, parents)
508
def check(self, progress_bar=None):
509
"""See VersionedFile.check()."""
511
def clone_text(self, new_version_id, old_version_id, parents):
512
"""See VersionedFile.clone_text()."""
513
# FIXME RBC 20060228 make fast by only inserting an index with null delta.
514
self.add_lines(new_version_id, parents, self.get_lines(old_version_id))
516
def get_lines(self, version_id):
517
"""See VersionedFile.get_lines()."""
518
return self._get_content(version_id).text()
520
def iter_lines_added_or_present_in_versions(self, version_ids=None):
521
"""See VersionedFile.iter_lines_added_or_present_in_versions()."""
522
if version_ids is None:
523
version_ids = self.versions()
524
# we dont care about inclusions, the caller cares.
525
# but we need to setup a list of records to visit.
526
# we need version_id, position, length
527
version_id_records = []
528
for version_id in version_ids:
529
if not self.has_version(version_id):
530
raise RevisionNotPresent(version_id, self.filename)
531
data_pos, length = self._index.get_position(version_id)
532
version_id_records.append((version_id, data_pos, length))
533
for version_id, data, sha_value in \
534
self._data.read_records_iter(version_id_records):
535
method = self._index.get_method(version_id)
536
version_idx = self._index.lookup(version_id)
537
assert method in ('fulltext', 'line-delta')
538
if method == 'fulltext':
539
content = self.factory.parse_fulltext(data, version_idx)
540
for line in content.text():
543
delta = self.factory.parse_line_delta(data, version_idx)
544
for start, end, count, lines in delta:
545
for origin, line in lines:
548
def num_versions(self):
549
"""See VersionedFile.num_versions()."""
550
return self._index.num_versions()
552
__len__ = num_versions
554
def annotate_iter(self, version_id):
555
"""See VersionedFile.annotate_iter."""
556
content = self._get_content(version_id)
557
for origin, text in content.annotate_iter():
558
yield self._index.idx_to_name(origin), text
560
def get_parents(self, version_id):
561
"""See VersionedFile.get_parents."""
562
self._check_versions_present([version_id])
563
return list(self._index.get_parents(version_id))
565
def get_parents_with_ghosts(self, version_id):
566
"""See VersionedFile.get_parents."""
567
self._check_versions_present([version_id])
568
return list(self._index.get_parents_with_ghosts(version_id))
570
def get_ancestry(self, versions):
571
"""See VersionedFile.get_ancestry."""
572
if isinstance(versions, basestring):
573
versions = [versions]
576
self._check_versions_present(versions)
577
return self._index.get_ancestry(versions)
579
def get_ancestry_with_ghosts(self, versions):
580
"""See VersionedFile.get_ancestry_with_ghosts."""
581
if isinstance(versions, basestring):
582
versions = [versions]
585
self._check_versions_present(versions)
586
return self._index.get_ancestry_with_ghosts(versions)
588
def _reannotate_line_delta(self, other, lines, new_version_id,
590
"""Re-annotate line-delta and return new delta."""
592
for start, end, count, contents \
593
in self.factory.parse_line_delta_iter(lines):
595
for origin, line in contents:
596
old_version_id = other._index.idx_to_name(origin)
597
if old_version_id == new_version_id:
598
idx = new_version_idx
600
idx = self._index.lookup(old_version_id)
601
new_lines.append((idx, line))
602
new_delta.append((start, end, count, new_lines))
604
return self.factory.lower_line_delta(new_delta)
606
def _reannotate_fulltext(self, other, lines, new_version_id,
608
"""Re-annotate fulltext and return new version."""
609
content = self.factory.parse_fulltext(lines, new_version_idx)
611
for origin, line in content.annotate_iter():
612
old_version_id = other._index.idx_to_name(origin)
613
if old_version_id == new_version_id:
614
idx = new_version_idx
616
idx = self._index.lookup(old_version_id)
617
new_lines.append((idx, line))
619
return self.factory.lower_fulltext(KnitContent(new_lines))
621
#@deprecated_method(zero_eight)
622
def walk(self, version_ids):
623
"""See VersionedFile.walk."""
624
# We take the short path here, and extract all relevant texts
625
# and put them in a weave and let that do all the work. Far
626
# from optimal, but is much simpler.
627
# FIXME RB 20060228 this really is inefficient!
628
from bzrlib.weave import Weave
630
w = Weave(self.filename)
631
ancestry = self.get_ancestry(version_ids)
632
sorted_graph = topo_sort(self._index.get_graph())
633
version_list = [vid for vid in sorted_graph if vid in ancestry]
635
for version_id in version_list:
636
lines = self.get_lines(version_id)
637
w.add_lines(version_id, self.get_parents(version_id), lines)
639
for lineno, insert_id, dset, line in w.walk(version_ids):
640
yield lineno, insert_id, dset, line
643
class _KnitComponentFile(object):
644
"""One of the files used to implement a knit database"""
646
def __init__(self, transport, filename, mode):
647
self._transport = transport
648
self._filename = filename
651
def write_header(self):
652
old_len = self._transport.append(self._filename, StringIO(self.HEADER))
654
raise KnitCorrupt(self._filename, 'misaligned after writing header')
656
def check_header(self, fp):
657
line = fp.read(len(self.HEADER))
658
if line != self.HEADER:
659
raise KnitHeaderError(badline=line)
662
"""Commit is a nop."""
665
return '%s(%s)' % (self.__class__.__name__, self._filename)
668
class _KnitIndex(_KnitComponentFile):
669
"""Manages knit index file.
671
The index is already kept in memory and read on startup, to enable
672
fast lookups of revision information. The cursor of the index
673
file is always pointing to the end, making it easy to append
676
_cache is a cache for fast mapping from version id to a Index
679
_history is a cache for fast mapping from indexes to version ids.
681
The index data format is dictionary compressed when it comes to
682
parent references; a index entry may only have parents that with a
683
lover index number. As a result, the index is topological sorted.
685
Duplicate entries may be written to the index for a single version id
686
if this is done then the latter one completely replaces the former:
687
this allows updates to correct version and parent information.
688
Note that the two entries may share the delta, and that successive
689
annotations and references MUST point to the first entry.
692
HEADER = "# bzr knit index 7\n"
694
def _cache_version(self, version_id, options, pos, size, parents):
695
val = (version_id, options, pos, size, parents)
696
self._cache[version_id] = val
697
if not version_id in self._history:
698
self._history.append(version_id)
700
def _iter_index(self, fp):
702
for l in lines.splitlines(False):
705
def __init__(self, transport, filename, mode, create=False):
706
_KnitComponentFile.__init__(self, transport, filename, mode)
708
# position in _history is the 'official' index for a revision
709
# but the values may have come from a newer entry.
710
# so - wc -l of a knit index is != the number of uniqe names
714
fp = self._transport.get(self._filename)
715
self.check_header(fp)
716
for rec in self._iter_index(fp):
717
parents = self._parse_parents(rec[4:])
718
self._cache_version(rec[0], rec[1].split(','), int(rec[2]), int(rec[3]),
720
except NoSuchFile, e:
721
if mode != 'w' or not create:
725
def _parse_parents(self, compressed_parents):
726
"""convert a list of string parent values into version ids.
728
ints are looked up in the index.
729
.FOO values are ghosts and converted in to FOO.
732
for value in compressed_parents:
733
if value.startswith('.'):
734
result.append(value[1:])
736
result.append(self._history[int(value)])
741
for version_id, index in self._cache.iteritems():
742
graph.append((version_id, index[4]))
745
def get_ancestry(self, versions):
746
"""See VersionedFile.get_ancestry."""
747
# get a graph of all the mentioned versions:
749
pending = set(versions)
751
version = pending.pop()
753
parents = self._cache[version][4]
760
parents = [parent for parent in parents if parent in self._cache]
761
for parent in parents:
762
# if not completed and not a ghost
763
if parent not in graph:
765
graph[version] = parents
766
return topo_sort(graph.items())
768
def get_ancestry_with_ghosts(self, versions):
769
"""See VersionedFile.get_ancestry_with_ghosts."""
770
# get a graph of all the mentioned versions:
772
pending = set(versions)
774
version = pending.pop()
776
parents = self._cache[version][4]
783
for parent in parents:
784
if parent not in graph:
786
graph[version] = parents
787
return topo_sort(graph.items())
789
def num_versions(self):
790
return len(self._history)
792
__len__ = num_versions
794
def get_versions(self):
797
def idx_to_name(self, idx):
798
return self._history[idx]
800
def lookup(self, version_id):
801
assert version_id in self._cache
802
return self._history.index(version_id)
804
def _version_list_to_index(self, versions):
806
for version in versions:
807
if version in self._cache:
808
result_list.append(str(self._history.index(version)))
810
result_list.append('.' + version)
811
return ' '.join(result_list)
813
def add_version(self, version_id, options, pos, size, parents):
814
"""Add a version record to the index."""
815
self._cache_version(version_id, options, pos, size, parents)
817
content = "%s %s %s %s %s\n" % (version_id,
821
self._version_list_to_index(parents))
822
self._transport.append(self._filename, StringIO(content))
824
def has_version(self, version_id):
825
"""True if the version is in the index."""
826
return self._cache.has_key(version_id)
828
def get_position(self, version_id):
829
"""Return data position and size of specified version."""
830
return (self._cache[version_id][2], \
831
self._cache[version_id][3])
833
def get_method(self, version_id):
834
"""Return compression method of specified version."""
835
options = self._cache[version_id][1]
836
if 'fulltext' in options:
839
assert 'line-delta' in options
842
def get_options(self, version_id):
843
return self._cache[version_id][1]
845
def get_parents(self, version_id):
846
"""Return parents of specified version ignoring ghosts."""
847
return [parent for parent in self._cache[version_id][4]
848
if parent in self._cache]
850
def get_parents_with_ghosts(self, version_id):
851
"""Return parents of specified version wth ghosts."""
852
return self._cache[version_id][4]
854
def check_versions_present(self, version_ids):
855
"""Check that all specified versions are present."""
856
version_ids = set(version_ids)
857
for version_id in list(version_ids):
858
if version_id in self._cache:
859
version_ids.remove(version_id)
861
raise RevisionNotPresent(list(version_ids)[0], self.filename)
864
class _KnitData(_KnitComponentFile):
865
"""Contents of the knit data file"""
867
HEADER = "# bzr knit data 7\n"
869
def __init__(self, transport, filename, mode, create=False):
870
_KnitComponentFile.__init__(self, transport, filename, mode)
872
self._checked = False
874
self._transport.put(self._filename, StringIO(''))
876
def _open_file(self):
877
if self._file is None:
879
self._file = self._transport.get(self._filename)
884
def add_record(self, version_id, digest, lines):
885
"""Write new text record to disk. Returns the position in the
886
file where it was written."""
888
data_file = GzipFile(None, mode='wb', fileobj=sio)
889
print >>data_file, "version %s %d %s" % (version_id, len(lines), digest)
890
data_file.writelines(lines)
891
print >>data_file, "end %s\n" % version_id
894
content = sio.getvalue()
895
start_pos = self._transport.append(self._filename, StringIO(content))
896
return start_pos, len(content)
898
def _parse_record(self, version_id, data):
899
df = GzipFile(mode='rb', fileobj=StringIO(data))
900
rec = df.readline().split()
902
raise KnitCorrupt(self._filename, 'unexpected number of records')
903
if rec[1] != version_id:
904
raise KnitCorrupt(self.file.name,
905
'unexpected version, wanted %r' % version_id)
907
record_contents = self._read_record_contents(df, lines)
909
if l != 'end %s\n' % version_id:
910
raise KnitCorrupt(self._filename, 'unexpected version end line %r, wanted %r'
912
return record_contents, rec[3]
914
def _read_record_contents(self, df, record_lines):
915
"""Read and return n lines from datafile."""
917
for i in range(record_lines):
918
r.append(df.readline())
921
def read_records_iter(self, records):
922
"""Read text records from data file and yield result.
924
Each passed record is a tuple of (version_id, pos, len) and
925
will be read in the given order. Yields (version_id,
929
class ContinuousRange:
930
def __init__(self, rec_id, pos, size):
932
self.end_pos = pos + size
933
self.versions = [(rec_id, pos, size)]
935
def add(self, rec_id, pos, size):
936
if self.end_pos != pos:
938
self.end_pos = pos + size
939
self.versions.append((rec_id, pos, size))
943
for rec_id, pos, size in self.versions:
944
yield rec_id, fp.read(size)
946
# We take it that the transport optimizes the fetching as good
947
# as possible (ie, reads continous ranges.)
948
response = self._transport.readv(self._filename,
949
[(pos, size) for version_id, pos, size in records])
951
for (record_id, pos, size), (pos, data) in zip(records, response):
952
content, digest = self._parse_record(record_id, data)
953
yield record_id, content, digest
955
def read_records(self, records):
956
"""Read records into a dictionary."""
958
for record_id, content, digest in self.read_records_iter(records):
959
components[record_id] = (content, digest)
963
class InterKnit(InterVersionedFile):
964
"""Optimised code paths for knit to knit operations."""
966
_matching_file_factory = KnitVersionedFile
969
def is_compatible(source, target):
970
"""Be compatible with knits. """
972
return (isinstance(source, KnitVersionedFile) and
973
isinstance(target, KnitVersionedFile))
974
except AttributeError:
977
def join(self, pb=None, msg=None, version_ids=None, ignore_missing=False):
978
"""See InterVersionedFile.join."""
979
assert isinstance(self.source, KnitVersionedFile)
980
assert isinstance(self.target, KnitVersionedFile)
982
if version_ids is None:
983
version_ids = self.source.versions()
985
if not ignore_missing:
986
self.source._check_versions_present(version_ids)
988
version_ids = set(self.source.versions()).intersection(
995
from bzrlib.progress import DummyProgress
998
version_ids = list(version_ids)
999
if None in version_ids:
1000
version_ids.remove(None)
1002
self.source_ancestry = set(self.source.get_ancestry(version_ids))
1003
this_versions = set(self.target._index.get_versions())
1004
needed_versions = self.source_ancestry - this_versions
1005
cross_check_versions = self.source_ancestry.intersection(this_versions)
1006
mismatched_versions = set()
1007
for version in cross_check_versions:
1008
# scan to include needed parents.
1009
n1 = set(self.target.get_parents_with_ghosts(version))
1010
n2 = set(self.source.get_parents_with_ghosts(version))
1012
# FIXME TEST this check for cycles being introduced works
1013
# the logic is we have a cycle if in our graph we are an
1014
# ancestor of any of the n2 revisions.
1020
parent_ancestors = self.source.get_ancestry(parent)
1021
if version in parent_ancestors:
1022
raise errors.GraphCycleError([parent, version])
1023
# ensure this parent will be available later.
1024
new_parents = n2.difference(n1)
1025
needed_versions.update(new_parents.difference(this_versions))
1026
mismatched_versions.add(version)
1028
if not needed_versions and not cross_check_versions:
1030
full_list = topo_sort(self.source.get_graph())
1032
version_list = [i for i in full_list if (not self.target.has_version(i)
1033
and i in needed_versions)]
1036
for version_id in version_list:
1037
data_pos, data_size = self.source._index.get_position(version_id)
1038
records.append((version_id, data_pos, data_size))
1041
for version_id, lines, digest \
1042
in self.source._data.read_records_iter(records):
1043
options = self.source._index.get_options(version_id)
1044
parents = self.source._index.get_parents_with_ghosts(version_id)
1046
for parent in parents:
1047
# if source has the parent, we must hav grabbed it first.
1048
assert (self.target.has_version(parent) or not
1049
self.source.has_version(parent))
1051
if self.target.factory.annotated:
1052
# FIXME jrydberg: it should be possible to skip
1053
# re-annotating components if we know that we are
1054
# going to pull all revisions in the same order.
1055
new_version_id = version_id
1056
new_version_idx = self.target._index.num_versions()
1057
if 'fulltext' in options:
1058
lines = self.target._reannotate_fulltext(self.source, lines,
1059
new_version_id, new_version_idx)
1060
elif 'line-delta' in options:
1061
lines = self.target._reannotate_line_delta(self.source, lines,
1062
new_version_id, new_version_idx)
1065
pb.update("Joining knit", count, len(version_list))
1067
pos, size = self.target._data.add_record(version_id, digest, lines)
1068
self.target._index.add_version(version_id, options, pos, size, parents)
1070
for version in mismatched_versions:
1071
n1 = set(self.target.get_parents_with_ghosts(version))
1072
n2 = set(self.source.get_parents_with_ghosts(version))
1073
# write a combined record to our history preserving the current
1074
# parents as first in the list
1075
new_parents = self.target.get_parents_with_ghosts(version) + list(n2.difference(n1))
1076
self.target.fix_parents(version, new_parents)
1081
InterVersionedFile.register_optimiser(InterKnit)