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 ?
67
from cStringIO import StringIO
69
from difflib import SequenceMatcher
70
from gzip import GzipFile
71
from itertools import izip
76
import bzrlib.errors as errors
77
from bzrlib.errors import FileExists, NoSuchFile, KnitError, \
78
InvalidRevisionId, KnitCorrupt, KnitHeaderError, \
79
RevisionNotPresent, RevisionAlreadyPresent
80
from bzrlib.trace import mutter
81
from bzrlib.osutils import contains_whitespace, contains_linebreaks, \
83
from bzrlib.versionedfile import VersionedFile, InterVersionedFile
84
from bzrlib.tsort import topo_sort
87
# TODO: Split out code specific to this format into an associated object.
89
# TODO: Can we put in some kind of value to check that the index and data
90
# files belong together?
92
# TODO: accomodate binaries, perhaps by storing a byte count
94
# TODO: function to check whole file
96
# TODO: atomically append data, then measure backwards from the cursor
97
# position after writing to work out where it was located. we may need to
98
# bypass python file buffering.
100
DATA_SUFFIX = '.knit'
101
INDEX_SUFFIX = '.kndx'
104
class KnitContent(object):
105
"""Content of a knit version to which deltas can be applied."""
107
def __init__(self, lines):
110
def annotate_iter(self):
111
"""Yield tuples of (origin, text) for each content line."""
112
for origin, text in self._lines:
116
"""Return a list of (origin, text) tuples."""
117
return list(self.annotate_iter())
119
def apply_delta(self, delta):
120
"""Apply delta to this content."""
122
for start, end, count, lines in delta:
123
self._lines[offset+start:offset+end] = lines
124
offset = offset + (start - end) + count
126
def line_delta_iter(self, new_lines):
127
"""Generate line-based delta from new_lines to this content."""
128
new_texts = [text for origin, text in new_lines._lines]
129
old_texts = [text for origin, text in self._lines]
130
s = difflib.SequenceMatcher(None, old_texts, new_texts)
131
for op in s.get_opcodes():
134
yield (op[1], op[2], op[4]-op[3], new_lines._lines[op[3]:op[4]])
136
def line_delta(self, new_lines):
137
return list(self.line_delta_iter(new_lines))
140
return [text for origin, text in self._lines]
143
class _KnitFactory(object):
144
"""Base factory for creating content objects."""
146
def make(self, lines, version):
147
num_lines = len(lines)
148
return KnitContent(zip([version] * num_lines, lines))
151
class KnitAnnotateFactory(_KnitFactory):
152
"""Factory for creating annotated Content objects."""
156
def parse_fulltext(self, content, version):
157
"""Convert fulltext to internal representation
159
fulltext content is of the format
160
revid(utf8) plaintext\n
161
internal representation is of the format:
166
origin, text = line.split(' ', 1)
167
lines.append((origin.decode('utf-8'), text))
168
return KnitContent(lines)
170
def parse_line_delta_iter(self, lines):
171
"""Convert a line based delta into internal representation.
173
line delta is in the form of:
174
intstart intend intcount
176
revid(utf8) newline\n
177
internal represnetation is
178
(start, end, count, [1..count tuples (revid, newline)])
181
header = lines.pop(0)
182
start, end, c = [int(n) for n in header.split(',')]
185
origin, text = lines.pop(0).split(' ', 1)
186
contents.append((origin.decode('utf-8'), text))
187
yield start, end, c, contents
189
def parse_line_delta(self, lines, version):
190
return list(self.parse_line_delta_iter(lines))
192
def lower_fulltext(self, content):
193
"""convert a fulltext content record into a serializable form.
195
see parse_fulltext which this inverts.
197
return ['%s %s' % (o.encode('utf-8'), t) for o, t in content._lines]
199
def lower_line_delta(self, delta):
200
"""convert a delta into a serializable form.
202
See parse_line_delta_iter which this inverts.
205
for start, end, c, lines in delta:
206
out.append('%d,%d,%d\n' % (start, end, c))
207
for origin, text in lines:
208
out.append('%s %s' % (origin.encode('utf-8'), text))
212
class KnitPlainFactory(_KnitFactory):
213
"""Factory for creating plain Content objects."""
217
def parse_fulltext(self, content, version):
218
"""This parses an unannotated fulltext.
220
Note that this is not a noop - the internal representation
221
has (versionid, line) - its just a constant versionid.
223
return self.make(content, version)
225
def parse_line_delta_iter(self, lines, version):
227
header = lines.pop(0)
228
start, end, c = [int(n) for n in header.split(',')]
229
yield start, end, c, zip([version] * c, lines[:c])
232
def parse_line_delta(self, lines, version):
233
return list(self.parse_line_delta_iter(lines, version))
235
def lower_fulltext(self, content):
236
return content.text()
238
def lower_line_delta(self, delta):
240
for start, end, c, lines in delta:
241
out.append('%d,%d,%d\n' % (start, end, c))
242
out.extend([text for origin, text in lines])
246
def make_empty_knit(transport, relpath):
247
"""Construct a empty knit at the specified location."""
248
k = KnitVersionedFile(transport, relpath, 'w', KnitPlainFactory)
252
class KnitVersionedFile(VersionedFile):
253
"""Weave-like structure with faster random access.
255
A knit stores a number of texts and a summary of the relationships
256
between them. Texts are identified by a string version-id. Texts
257
are normally stored and retrieved as a series of lines, but can
258
also be passed as single strings.
260
Lines are stored with the trailing newline (if any) included, to
261
avoid special cases for files with no final newline. Lines are
262
composed of 8-bit characters, not unicode. The combination of
263
these approaches should mean any 'binary' file can be safely
264
stored and retrieved.
267
def __init__(self, relpath, transport, file_mode=None, access_mode=None, factory=None,
268
basis_knit=None, delta=True, create=False):
269
"""Construct a knit at location specified by relpath.
271
:param create: If not True, only open an existing knit.
273
if access_mode is None:
275
super(KnitVersionedFile, self).__init__(access_mode)
276
assert access_mode in ('r', 'w'), "invalid mode specified %r" % access_mode
277
assert not basis_knit or isinstance(basis_knit, KnitVersionedFile), \
280
self.transport = transport
281
self.filename = relpath
282
self.basis_knit = basis_knit
283
self.factory = factory or KnitAnnotateFactory()
284
self.writable = (access_mode == 'w')
287
self._index = _KnitIndex(transport, relpath + INDEX_SUFFIX,
288
access_mode, create=create)
289
self._data = _KnitData(transport, relpath + DATA_SUFFIX,
290
access_mode, create=not len(self.versions()))
292
def clear_cache(self):
293
"""Clear the data cache only."""
294
self._data.clear_cache()
296
def copy_to(self, name, transport):
297
"""See VersionedFile.copy_to()."""
298
# copy the current index to a temp index to avoid racing with local
300
transport.put(name + INDEX_SUFFIX + '.tmp', self.transport.get(self._index._filename))
302
transport.put(name + DATA_SUFFIX, self._data._open_file())
303
# rename the copied index into place
304
transport.rename(name + INDEX_SUFFIX + '.tmp', name + INDEX_SUFFIX)
306
def create_empty(self, name, transport, mode=None):
307
return KnitVersionedFile(name, transport, factory=self.factory, delta=self.delta, create=True)
309
def _fix_parents(self, version, new_parents):
310
"""Fix the parents list for version.
312
This is done by appending a new version to the index
313
with identical data except for the parents list.
314
the parents list must be a superset of the current
317
current_values = self._index._cache[version]
318
assert set(current_values[4]).difference(set(new_parents)) == set()
319
self._index.add_version(version,
325
def get_graph_with_ghosts(self):
326
"""See VersionedFile.get_graph_with_ghosts()."""
327
graph_items = self._index.get_graph()
328
return dict(graph_items)
332
"""See VersionedFile.get_suffixes()."""
333
return [DATA_SUFFIX, INDEX_SUFFIX]
335
def has_ghost(self, version_id):
336
"""True if there is a ghost reference in the file to version_id."""
338
if self.has_version(version_id):
340
# optimisable if needed by memoising the _ghosts set.
341
items = self._index.get_graph()
342
for node, parents in items:
343
for parent in parents:
344
if parent not in self._index._cache:
345
if parent == version_id:
350
"""See VersionedFile.versions."""
351
return self._index.get_versions()
353
def has_version(self, version_id):
354
"""See VersionedFile.has_version."""
355
return self._index.has_version(version_id)
357
__contains__ = has_version
359
def _merge_annotations(self, content, parents):
360
"""Merge annotations for content. This is done by comparing
361
the annotations based on changed to the text."""
362
for parent_id in parents:
363
merge_content = self._get_content(parent_id)
364
seq = SequenceMatcher(None, merge_content.text(), content.text())
365
for i, j, n in seq.get_matching_blocks():
368
content._lines[j:j+n] = merge_content._lines[i:i+n]
370
def _get_components(self, version_id):
371
"""Return a list of (version_id, method, data) tuples that
372
makes up version specified by version_id of the knit.
374
The components should be applied in the order of the returned
377
The basis knit will be used to the largest extent possible
378
since it is assumed that accesses to it is faster.
380
# needed_revisions holds a list of (method, version_id) of
381
# versions that is needed to be fetched to construct the final
382
# version of the file.
384
# basis_revisions is a list of versions that needs to be
385
# fetched but exists in the basis knit.
387
basis = self.basis_knit
394
if basis and basis._index.has_version(cursor):
396
basis_versions.append(cursor)
397
method = picked_knit._index.get_method(cursor)
398
needed_versions.append((method, cursor))
399
if method == 'fulltext':
401
cursor = picked_knit.get_parents(cursor)[0]
406
for comp_id in basis_versions:
407
data_pos, data_size = basis._index.get_data_position(comp_id)
408
records.append((piece_id, data_pos, data_size))
409
components.update(basis._data.read_records(records))
412
for comp_id in [vid for method, vid in needed_versions
413
if vid not in basis_versions]:
414
data_pos, data_size = self._index.get_position(comp_id)
415
records.append((comp_id, data_pos, data_size))
416
components.update(self._data.read_records(records))
418
# get_data_records returns a mapping with the version id as
419
# index and the value as data. The order the components need
420
# to be applied is held by needed_versions (reversed).
422
for method, comp_id in reversed(needed_versions):
423
out.append((comp_id, method, components[comp_id]))
427
def _get_content(self, version_id):
428
"""Returns a content object that makes up the specified
430
if not self.has_version(version_id):
431
raise RevisionNotPresent(version_id, self.filename)
433
if self.basis_knit and version_id in self.basis_knit:
434
return self.basis_knit._get_content(version_id)
437
components = self._get_components(version_id)
438
for component_id, method, (data, digest) in components:
439
version_idx = self._index.lookup(component_id)
440
if method == 'fulltext':
441
assert content is None
442
content = self.factory.parse_fulltext(data, version_idx)
443
elif method == 'line-delta':
444
delta = self.factory.parse_line_delta(data, version_idx)
445
content.apply_delta(delta)
447
if 'no-eol' in self._index.get_options(version_id):
448
line = content._lines[-1][1].rstrip('\n')
449
content._lines[-1] = (content._lines[-1][0], line)
451
if sha_strings(content.text()) != digest:
452
raise KnitCorrupt(self.filename, 'sha-1 does not match')
456
def _check_versions_present(self, version_ids):
457
"""Check that all specified versions are present."""
458
version_ids = set(version_ids)
459
for r in list(version_ids):
460
if self._index.has_version(r):
461
version_ids.remove(r)
463
raise RevisionNotPresent(list(version_ids)[0], self.filename)
465
def _add_lines_with_ghosts(self, version_id, parents, lines):
466
"""See VersionedFile.add_lines_with_ghosts()."""
467
self._check_add(version_id, lines)
468
return self._add(version_id, lines[:], parents, self.delta)
470
def _add_lines(self, version_id, parents, lines):
471
"""See VersionedFile.add_lines."""
472
self._check_add(version_id, lines)
473
self._check_versions_present(parents)
474
return self._add(version_id, lines[:], parents, self.delta)
476
def _check_add(self, version_id, lines):
477
"""check that version_id and lines are safe to add."""
478
assert self.writable, "knit is not opened for write"
479
### FIXME escape. RBC 20060228
480
if contains_whitespace(version_id):
481
raise InvalidRevisionId(version_id)
482
if self.has_version(version_id):
483
raise RevisionAlreadyPresent(version_id, self.filename)
485
if False or __debug__:
487
assert '\n' not in l[:-1]
489
def _add(self, version_id, lines, parents, delta):
490
"""Add a set of lines on top of version specified by parents.
492
If delta is true, compress the text as a line-delta against
495
Any versions not present will be converted into ghosts.
497
ghostless_parents = []
499
for parent in parents:
500
if not self.has_version(parent):
501
ghosts.append(parent)
503
ghostless_parents.append(parent)
505
if delta and not len(ghostless_parents):
508
digest = sha_strings(lines)
511
if lines[-1][-1] != '\n':
512
options.append('no-eol')
513
lines[-1] = lines[-1] + '\n'
515
lines = self.factory.make(lines, version_id) #len(self._index))
516
if self.factory.annotated and len(ghostless_parents) > 0:
517
# Merge annotations from parent texts if so is needed.
518
self._merge_annotations(lines, ghostless_parents)
520
if len(ghostless_parents) and delta:
521
# To speed the extract of texts the delta chain is limited
522
# to a fixed number of deltas. This should minimize both
523
# I/O and the time spend applying deltas.
525
delta_parents = ghostless_parents
527
parent = delta_parents[0]
528
method = self._index.get_method(parent)
529
if method == 'fulltext':
531
delta_parents = self._index.get_parents(parent)
533
if method == 'line-delta':
537
options.append('line-delta')
538
content = self._get_content(ghostless_parents[0])
539
delta_hunks = content.line_delta(lines)
540
store_lines = self.factory.lower_line_delta(delta_hunks)
542
options.append('fulltext')
543
store_lines = self.factory.lower_fulltext(lines)
545
where, size = self._data.add_record(version_id, digest, store_lines)
546
self._index.add_version(version_id, options, where, size, parents)
548
def check(self, progress_bar=None):
549
"""See VersionedFile.check()."""
551
def _clone_text(self, new_version_id, old_version_id, parents):
552
"""See VersionedFile.clone_text()."""
553
# FIXME RBC 20060228 make fast by only inserting an index with null delta.
554
self.add_lines(new_version_id, parents, self.get_lines(old_version_id))
556
def get_lines(self, version_id):
557
"""See VersionedFile.get_lines()."""
558
return self._get_content(version_id).text()
560
def iter_lines_added_or_present_in_versions(self, version_ids=None):
561
"""See VersionedFile.iter_lines_added_or_present_in_versions()."""
562
if version_ids is None:
563
version_ids = self.versions()
564
# we dont care about inclusions, the caller cares.
565
# but we need to setup a list of records to visit.
566
# we need version_id, position, length
567
version_id_records = []
568
requested_versions = list(version_ids)
569
# filter for available versions
570
for version_id in requested_versions:
571
if not self.has_version(version_id):
572
raise RevisionNotPresent(version_id, self.filename)
573
# get a in-component-order queue:
575
for version_id in self.versions():
576
if version_id in requested_versions:
577
version_ids.append(version_id)
578
data_pos, length = self._index.get_position(version_id)
579
version_id_records.append((version_id, data_pos, length))
581
pb = bzrlib.ui.ui_factory.nested_progress_bar()
583
total = len(version_id_records)
585
pb.update('Walking content.', count, total)
586
for version_id, data, sha_value in \
587
self._data.read_records_iter(version_id_records):
588
pb.update('Walking content.', count, total)
589
method = self._index.get_method(version_id)
590
version_idx = self._index.lookup(version_id)
591
assert method in ('fulltext', 'line-delta')
592
if method == 'fulltext':
593
content = self.factory.parse_fulltext(data, version_idx)
594
for line in content.text():
597
delta = self.factory.parse_line_delta(data, version_idx)
598
for start, end, count, lines in delta:
599
for origin, line in lines:
602
pb.update('Walking content.', total, total)
605
pb.update('Walking content.', total, total)
609
def num_versions(self):
610
"""See VersionedFile.num_versions()."""
611
return self._index.num_versions()
613
__len__ = num_versions
615
def annotate_iter(self, version_id):
616
"""See VersionedFile.annotate_iter."""
617
content = self._get_content(version_id)
618
for origin, text in content.annotate_iter():
621
def get_parents(self, version_id):
622
"""See VersionedFile.get_parents."""
623
self._check_versions_present([version_id])
624
return list(self._index.get_parents(version_id))
626
def get_parents_with_ghosts(self, version_id):
627
"""See VersionedFile.get_parents."""
628
self._check_versions_present([version_id])
629
return list(self._index.get_parents_with_ghosts(version_id))
631
def get_ancestry(self, versions):
632
"""See VersionedFile.get_ancestry."""
633
if isinstance(versions, basestring):
634
versions = [versions]
637
self._check_versions_present(versions)
638
return self._index.get_ancestry(versions)
640
def get_ancestry_with_ghosts(self, versions):
641
"""See VersionedFile.get_ancestry_with_ghosts."""
642
if isinstance(versions, basestring):
643
versions = [versions]
646
self._check_versions_present(versions)
647
return self._index.get_ancestry_with_ghosts(versions)
649
#@deprecated_method(zero_eight)
650
def walk(self, version_ids):
651
"""See VersionedFile.walk."""
652
# We take the short path here, and extract all relevant texts
653
# and put them in a weave and let that do all the work. Far
654
# from optimal, but is much simpler.
655
# FIXME RB 20060228 this really is inefficient!
656
from bzrlib.weave import Weave
658
w = Weave(self.filename)
659
ancestry = self.get_ancestry(version_ids)
660
sorted_graph = topo_sort(self._index.get_graph())
661
version_list = [vid for vid in sorted_graph if vid in ancestry]
663
for version_id in version_list:
664
lines = self.get_lines(version_id)
665
w.add_lines(version_id, self.get_parents(version_id), lines)
667
for lineno, insert_id, dset, line in w.walk(version_ids):
668
yield lineno, insert_id, dset, line
671
class _KnitComponentFile(object):
672
"""One of the files used to implement a knit database"""
674
def __init__(self, transport, filename, mode):
675
self._transport = transport
676
self._filename = filename
679
def write_header(self):
680
old_len = self._transport.append(self._filename, StringIO(self.HEADER))
682
raise KnitCorrupt(self._filename, 'misaligned after writing header')
684
def check_header(self, fp):
685
line = fp.read(len(self.HEADER))
686
if line != self.HEADER:
687
raise KnitHeaderError(badline=line)
690
"""Commit is a nop."""
693
return '%s(%s)' % (self.__class__.__name__, self._filename)
696
class _KnitIndex(_KnitComponentFile):
697
"""Manages knit index file.
699
The index is already kept in memory and read on startup, to enable
700
fast lookups of revision information. The cursor of the index
701
file is always pointing to the end, making it easy to append
704
_cache is a cache for fast mapping from version id to a Index
707
_history is a cache for fast mapping from indexes to version ids.
709
The index data format is dictionary compressed when it comes to
710
parent references; a index entry may only have parents that with a
711
lover index number. As a result, the index is topological sorted.
713
Duplicate entries may be written to the index for a single version id
714
if this is done then the latter one completely replaces the former:
715
this allows updates to correct version and parent information.
716
Note that the two entries may share the delta, and that successive
717
annotations and references MUST point to the first entry.
720
HEADER = "# bzr knit index 7\n"
722
def _cache_version(self, version_id, options, pos, size, parents):
723
val = (version_id, options, pos, size, parents)
724
self._cache[version_id] = val
725
if not version_id in self._history:
726
self._history.append(version_id)
728
def _iter_index(self, fp):
734
#for l in lines.splitlines(False):
737
def __init__(self, transport, filename, mode, create=False):
738
_KnitComponentFile.__init__(self, transport, filename, mode)
740
# position in _history is the 'official' index for a revision
741
# but the values may have come from a newer entry.
742
# so - wc -l of a knit index is != the number of uniqe names
745
pb = bzrlib.ui.ui_factory.nested_progress_bar()
750
pb.update('read knit index', count, total)
751
fp = self._transport.get(self._filename)
752
self.check_header(fp)
753
for rec in self._iter_index(fp):
756
pb.update('read knit index', count, total)
757
parents = self._parse_parents(rec[4:])
758
self._cache_version(rec[0], rec[1].split(','), int(rec[2]), int(rec[3]),
760
except NoSuchFile, e:
761
if mode != 'w' or not create:
765
pb.update('read knit index', total, total)
768
def _parse_parents(self, compressed_parents):
769
"""convert a list of string parent values into version ids.
771
ints are looked up in the index.
772
.FOO values are ghosts and converted in to FOO.
775
for value in compressed_parents:
776
if value.startswith('.'):
777
result.append(value[1:])
779
assert isinstance(value, str)
780
result.append(self._history[int(value)])
785
for version_id, index in self._cache.iteritems():
786
graph.append((version_id, index[4]))
789
def get_ancestry(self, versions):
790
"""See VersionedFile.get_ancestry."""
791
# get a graph of all the mentioned versions:
793
pending = set(versions)
795
version = pending.pop()
796
parents = self._cache[version][4]
799
parents = [parent for parent in parents if parent in self._cache]
800
for parent in parents:
801
# if not completed and not a ghost
802
if parent not in graph:
804
graph[version] = parents
805
return topo_sort(graph.items())
807
def get_ancestry_with_ghosts(self, versions):
808
"""See VersionedFile.get_ancestry_with_ghosts."""
809
# get a graph of all the mentioned versions:
811
pending = set(versions)
813
version = pending.pop()
815
parents = self._cache[version][4]
822
for parent in parents:
823
if parent not in graph:
825
graph[version] = parents
826
return topo_sort(graph.items())
828
def num_versions(self):
829
return len(self._history)
831
__len__ = num_versions
833
def get_versions(self):
836
def idx_to_name(self, idx):
837
return self._history[idx]
839
def lookup(self, version_id):
840
assert version_id in self._cache
841
return self._history.index(version_id)
843
def _version_list_to_index(self, versions):
845
for version in versions:
846
if version in self._cache:
847
result_list.append(str(self._history.index(version)))
849
result_list.append('.' + version.encode('utf-8'))
850
return ' '.join(result_list)
852
def add_version(self, version_id, options, pos, size, parents):
853
"""Add a version record to the index."""
854
self._cache_version(version_id, options, pos, size, parents)
856
content = "%s %s %s %s %s\n" % (version_id,
860
self._version_list_to_index(parents))
861
self._transport.append(self._filename, StringIO(content))
863
def has_version(self, version_id):
864
"""True if the version is in the index."""
865
return self._cache.has_key(version_id)
867
def get_position(self, version_id):
868
"""Return data position and size of specified version."""
869
return (self._cache[version_id][2], \
870
self._cache[version_id][3])
872
def get_method(self, version_id):
873
"""Return compression method of specified version."""
874
options = self._cache[version_id][1]
875
if 'fulltext' in options:
878
assert 'line-delta' in options
881
def get_options(self, version_id):
882
return self._cache[version_id][1]
884
def get_parents(self, version_id):
885
"""Return parents of specified version ignoring ghosts."""
886
return [parent for parent in self._cache[version_id][4]
887
if parent in self._cache]
889
def get_parents_with_ghosts(self, version_id):
890
"""Return parents of specified version wth ghosts."""
891
return self._cache[version_id][4]
893
def check_versions_present(self, version_ids):
894
"""Check that all specified versions are present."""
895
version_ids = set(version_ids)
896
for version_id in list(version_ids):
897
if version_id in self._cache:
898
version_ids.remove(version_id)
900
raise RevisionNotPresent(list(version_ids)[0], self.filename)
903
class _KnitData(_KnitComponentFile):
904
"""Contents of the knit data file"""
906
HEADER = "# bzr knit data 7\n"
908
def __init__(self, transport, filename, mode, create=False):
909
_KnitComponentFile.__init__(self, transport, filename, mode)
911
self._checked = False
913
self._transport.put(self._filename, StringIO(''))
916
def clear_cache(self):
917
"""Clear the record cache."""
920
def _open_file(self):
921
if self._file is None:
923
self._file = self._transport.get(self._filename)
928
def add_record(self, version_id, digest, lines):
929
"""Write new text record to disk. Returns the position in the
930
file where it was written."""
932
data_file = GzipFile(None, mode='wb', fileobj=sio)
933
print >>data_file, "version %s %d %s" % (version_id, len(lines), digest)
934
data_file.writelines(lines)
935
print >>data_file, "end %s\n" % version_id
939
self._records[version_id] = (digest, lines)
941
content = sio.getvalue()
943
start_pos = self._transport.append(self._filename, sio)
944
return start_pos, len(content)
946
def _parse_record(self, version_id, data):
947
df = GzipFile(mode='rb', fileobj=StringIO(data))
948
rec = df.readline().split()
950
raise KnitCorrupt(self._filename, 'unexpected number of records')
951
if rec[1] != version_id:
952
raise KnitCorrupt(self._filename,
953
'unexpected version, wanted %r, got %r' % (
956
record_contents = self._read_record_contents(df, lines)
958
if l != 'end %s\n' % version_id:
959
raise KnitCorrupt(self._filename, 'unexpected version end line %r, wanted %r'
961
return record_contents, rec[3]
963
def _read_record_contents(self, df, record_lines):
964
"""Read and return n lines from datafile."""
966
for i in range(record_lines):
967
r.append(df.readline())
970
def read_records_iter(self, records):
971
"""Read text records from data file and yield result.
973
Each passed record is a tuple of (version_id, pos, len) and
974
will be read in the given order. Yields (version_id,
979
for version_id, pos, size in records:
980
if version_id not in self._records:
981
needed_records.append((version_id, pos, size))
983
if len(needed_records):
984
# We take it that the transport optimizes the fetching as good
985
# as possible (ie, reads continous ranges.)
986
response = self._transport.readv(self._filename,
987
[(pos, size) for version_id, pos, size in needed_records])
989
for (record_id, pos, size), (pos, data) in izip(iter(needed_records), response):
990
content, digest = self._parse_record(record_id, data)
991
self._records[record_id] = (digest, content)
993
for version_id, pos, size in records:
994
yield version_id, copy(self._records[version_id][1]), copy(self._records[version_id][0])
996
def read_records(self, records):
997
"""Read records into a dictionary."""
999
for record_id, content, digest in self.read_records_iter(records):
1000
components[record_id] = (content, digest)
1004
class InterKnit(InterVersionedFile):
1005
"""Optimised code paths for knit to knit operations."""
1007
_matching_file_factory = KnitVersionedFile
1010
def is_compatible(source, target):
1011
"""Be compatible with knits. """
1013
return (isinstance(source, KnitVersionedFile) and
1014
isinstance(target, KnitVersionedFile))
1015
except AttributeError:
1018
def join(self, pb=None, msg=None, version_ids=None, ignore_missing=False):
1019
"""See InterVersionedFile.join."""
1020
assert isinstance(self.source, KnitVersionedFile)
1021
assert isinstance(self.target, KnitVersionedFile)
1023
if version_ids is None:
1024
version_ids = self.source.versions()
1026
if not ignore_missing:
1027
self.source._check_versions_present(version_ids)
1029
version_ids = set(self.source.versions()).intersection(
1035
pb = bzrlib.ui.ui_factory.nested_progress_bar()
1037
version_ids = list(version_ids)
1038
if None in version_ids:
1039
version_ids.remove(None)
1041
self.source_ancestry = set(self.source.get_ancestry(version_ids))
1042
this_versions = set(self.target._index.get_versions())
1043
needed_versions = self.source_ancestry - this_versions
1044
cross_check_versions = self.source_ancestry.intersection(this_versions)
1045
mismatched_versions = set()
1046
for version in cross_check_versions:
1047
# scan to include needed parents.
1048
n1 = set(self.target.get_parents_with_ghosts(version))
1049
n2 = set(self.source.get_parents_with_ghosts(version))
1051
# FIXME TEST this check for cycles being introduced works
1052
# the logic is we have a cycle if in our graph we are an
1053
# ancestor of any of the n2 revisions.
1059
parent_ancestors = self.source.get_ancestry(parent)
1060
if version in parent_ancestors:
1061
raise errors.GraphCycleError([parent, version])
1062
# ensure this parent will be available later.
1063
new_parents = n2.difference(n1)
1064
needed_versions.update(new_parents.difference(this_versions))
1065
mismatched_versions.add(version)
1067
if not needed_versions and not cross_check_versions:
1069
full_list = topo_sort(self.source.get_graph())
1071
version_list = [i for i in full_list if (not self.target.has_version(i)
1072
and i in needed_versions)]
1075
for version_id in version_list:
1076
data_pos, data_size = self.source._index.get_position(version_id)
1077
records.append((version_id, data_pos, data_size))
1080
for version_id, lines, digest \
1081
in self.source._data.read_records_iter(records):
1082
options = self.source._index.get_options(version_id)
1083
parents = self.source._index.get_parents_with_ghosts(version_id)
1085
for parent in parents:
1086
# if source has the parent, we must hav grabbed it first.
1087
assert (self.target.has_version(parent) or not
1088
self.source.has_version(parent))
1091
pb.update("Joining knit", count, len(version_list))
1093
pos, size = self.target._data.add_record(version_id, digest, lines)
1094
self.target._index.add_version(version_id, options, pos, size, parents)
1096
for version in mismatched_versions:
1097
n1 = set(self.target.get_parents_with_ghosts(version))
1098
n2 = set(self.source.get_parents_with_ghosts(version))
1099
# write a combined record to our history preserving the current
1100
# parents as first in the list
1101
new_parents = self.target.get_parents_with_ghosts(version) + list(n2.difference(n1))
1102
self.target.fix_parents(version, new_parents)
1109
InterVersionedFile.register_optimiser(InterKnit)