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
70
from itertools import izip
75
import bzrlib.errors as errors
76
from bzrlib.errors import FileExists, NoSuchFile, KnitError, \
77
InvalidRevisionId, KnitCorrupt, KnitHeaderError, \
78
RevisionNotPresent, RevisionAlreadyPresent
79
from bzrlib.trace import mutter
80
from bzrlib.osutils import contains_whitespace, contains_linebreaks, \
82
from bzrlib.versionedfile import VersionedFile, InterVersionedFile
83
from bzrlib.tsort import topo_sort
86
# TODO: Split out code specific to this format into an associated object.
88
# TODO: Can we put in some kind of value to check that the index and data
89
# files belong together?
91
# TODO: accomodate binaries, perhaps by storing a byte count
93
# TODO: function to check whole file
95
# TODO: atomically append data, then measure backwards from the cursor
96
# position after writing to work out where it was located. we may need to
97
# bypass python file buffering.
100
INDEX_SUFFIX = '.kndx'
103
class KnitContent(object):
104
"""Content of a knit version to which deltas can be applied."""
106
def __init__(self, lines):
109
def annotate_iter(self):
110
"""Yield tuples of (origin, text) for each content line."""
111
for origin, text in self._lines:
115
"""Return a list of (origin, text) tuples."""
116
return list(self.annotate_iter())
118
def apply_delta(self, delta):
119
"""Apply delta to this content."""
121
for start, end, count, lines in delta:
122
self._lines[offset+start:offset+end] = lines
123
offset = offset + (start - end) + count
125
def line_delta_iter(self, new_lines):
126
"""Generate line-based delta from new_lines to this content."""
127
new_texts = [text for origin, text in new_lines._lines]
128
old_texts = [text for origin, text in self._lines]
129
s = difflib.SequenceMatcher(None, old_texts, new_texts)
130
for op in s.get_opcodes():
133
yield (op[1], op[2], op[4]-op[3], new_lines._lines[op[3]:op[4]])
135
def line_delta(self, new_lines):
136
return list(self.line_delta_iter(new_lines))
139
return [text for origin, text in self._lines]
142
class _KnitFactory(object):
143
"""Base factory for creating content objects."""
145
def make(self, lines, version):
146
num_lines = len(lines)
147
return KnitContent(zip([version] * num_lines, lines))
150
class KnitAnnotateFactory(_KnitFactory):
151
"""Factory for creating annotated Content objects."""
155
def parse_fulltext(self, content, version):
158
origin, text = line.split(' ', 1)
159
lines.append((int(origin), text))
160
return KnitContent(lines)
162
def parse_line_delta_iter(self, lines):
164
header = lines.pop(0)
165
start, end, c = [int(n) for n in header.split(',')]
168
origin, text = lines.pop(0).split(' ', 1)
169
contents.append((int(origin), text))
170
yield start, end, c, contents
172
def parse_line_delta(self, lines, version):
173
return list(self.parse_line_delta_iter(lines))
175
def lower_fulltext(self, content):
176
return ['%d %s' % (o, t) for o, t in content._lines]
178
def lower_line_delta(self, delta):
180
for start, end, c, lines in delta:
181
out.append('%d,%d,%d\n' % (start, end, c))
182
for origin, text in lines:
183
out.append('%d %s' % (origin, text))
187
class KnitPlainFactory(_KnitFactory):
188
"""Factory for creating plain Content objects."""
192
def parse_fulltext(self, content, version):
193
return self.make(content, version)
195
def parse_line_delta_iter(self, lines, version):
197
header = lines.pop(0)
198
start, end, c = [int(n) for n in header.split(',')]
199
yield start, end, c, zip([version] * c, lines[:c])
202
def parse_line_delta(self, lines, version):
203
return list(self.parse_line_delta_iter(lines, version))
205
def lower_fulltext(self, content):
206
return content.text()
208
def lower_line_delta(self, delta):
210
for start, end, c, lines in delta:
211
out.append('%d,%d,%d\n' % (start, end, c))
212
out.extend([text for origin, text in lines])
216
def make_empty_knit(transport, relpath):
217
"""Construct a empty knit at the specified location."""
218
k = KnitVersionedFile(transport, relpath, 'w', KnitPlainFactory)
222
class KnitVersionedFile(VersionedFile):
223
"""Weave-like structure with faster random access.
225
A knit stores a number of texts and a summary of the relationships
226
between them. Texts are identified by a string version-id. Texts
227
are normally stored and retrieved as a series of lines, but can
228
also be passed as single strings.
230
Lines are stored with the trailing newline (if any) included, to
231
avoid special cases for files with no final newline. Lines are
232
composed of 8-bit characters, not unicode. The combination of
233
these approaches should mean any 'binary' file can be safely
234
stored and retrieved.
237
def __init__(self, relpath, transport, file_mode=None, access_mode=None, factory=None,
238
basis_knit=None, delta=True, create=False):
239
"""Construct a knit at location specified by relpath.
241
:param create: If not True, only open an existing knit.
243
if access_mode is None:
245
assert access_mode in ('r', 'w'), "invalid mode specified %r" % access_mode
246
assert not basis_knit or isinstance(basis_knit, KnitVersionedFile), \
249
self.transport = transport
250
self.filename = relpath
251
self.basis_knit = basis_knit
252
self.factory = factory or KnitAnnotateFactory()
253
self.writable = (access_mode == 'w')
256
self._index = _KnitIndex(transport, relpath + INDEX_SUFFIX,
257
access_mode, create=create)
258
self._data = _KnitData(transport, relpath + DATA_SUFFIX,
259
access_mode, create=not len(self.versions()))
261
def copy_to(self, name, transport):
262
"""See VersionedFile.copy_to()."""
263
# copy the current index to a temp index to avoid racing with local
265
transport.put(name + INDEX_SUFFIX + '.tmp', self.transport.get(self._index._filename))
267
transport.put(name + DATA_SUFFIX, self._data._open_file())
268
# rename the copied index into place
269
transport.rename(name + INDEX_SUFFIX + '.tmp', name + INDEX_SUFFIX)
271
def create_empty(self, name, transport, mode=None):
272
return KnitVersionedFile(name, transport, factory=self.factory, delta=self.delta, create=True)
274
def fix_parents(self, version, new_parents):
275
"""Fix the parents list for version.
277
This is done by appending a new version to the index
278
with identical data except for the parents list.
279
the parents list must be a superset of the current
282
current_values = self._index._cache[version]
283
assert set(current_values[4]).difference(set(new_parents)) == set()
284
self._index.add_version(version,
290
def get_graph_with_ghosts(self):
291
"""See VersionedFile.get_graph_with_ghosts()."""
292
graph_items = self._index.get_graph()
293
return dict(graph_items)
297
"""See VersionedFile.get_suffixes()."""
298
return [DATA_SUFFIX, INDEX_SUFFIX]
300
def has_ghost(self, version_id):
301
"""True if there is a ghost reference in the file to version_id."""
303
if self.has_version(version_id):
305
# optimisable if needed by memoising the _ghosts set.
306
items = self._index.get_graph()
307
for node, parents in items:
308
for parent in parents:
309
if parent not in self._index._cache:
310
if parent == version_id:
315
"""See VersionedFile.versions."""
316
return self._index.get_versions()
318
def has_version(self, version_id):
319
"""See VersionedFile.has_version."""
320
return self._index.has_version(version_id)
322
__contains__ = has_version
324
def _merge_annotations(self, content, parents):
325
"""Merge annotations for content. This is done by comparing
326
the annotations based on changed to the text."""
327
for parent_id in parents:
328
merge_content = self._get_content(parent_id)
329
seq = SequenceMatcher(None, merge_content.text(), content.text())
330
for i, j, n in seq.get_matching_blocks():
333
content._lines[j:j+n] = merge_content._lines[i:i+n]
335
def _get_components(self, version_id):
336
"""Return a list of (version_id, method, data) tuples that
337
makes up version specified by version_id of the knit.
339
The components should be applied in the order of the returned
342
The basis knit will be used to the largest extent possible
343
since it is assumed that accesses to it is faster.
345
# needed_revisions holds a list of (method, version_id) of
346
# versions that is needed to be fetched to construct the final
347
# version of the file.
349
# basis_revisions is a list of versions that needs to be
350
# fetched but exists in the basis knit.
352
basis = self.basis_knit
359
if basis and basis._index.has_version(cursor):
361
basis_versions.append(cursor)
362
method = picked_knit._index.get_method(cursor)
363
needed_versions.append((method, cursor))
364
if method == 'fulltext':
366
cursor = picked_knit.get_parents(cursor)[0]
371
for comp_id in basis_versions:
372
data_pos, data_size = basis._index.get_data_position(comp_id)
373
records.append((piece_id, data_pos, data_size))
374
components.update(basis._data.read_records(records))
377
for comp_id in [vid for method, vid in needed_versions
378
if vid not in basis_versions]:
379
data_pos, data_size = self._index.get_position(comp_id)
380
records.append((comp_id, data_pos, data_size))
381
components.update(self._data.read_records(records))
383
# get_data_records returns a mapping with the version id as
384
# index and the value as data. The order the components need
385
# to be applied is held by needed_versions (reversed).
387
for method, comp_id in reversed(needed_versions):
388
out.append((comp_id, method, components[comp_id]))
392
def _get_content(self, version_id):
393
"""Returns a content object that makes up the specified
395
if not self.has_version(version_id):
396
raise RevisionNotPresent(version_id, self.filename)
398
if self.basis_knit and version_id in self.basis_knit:
399
return self.basis_knit._get_content(version_id)
402
components = self._get_components(version_id)
403
for component_id, method, (data, digest) in components:
404
version_idx = self._index.lookup(component_id)
405
if method == 'fulltext':
406
assert content is None
407
content = self.factory.parse_fulltext(data, version_idx)
408
elif method == 'line-delta':
409
delta = self.factory.parse_line_delta(data, version_idx)
410
content.apply_delta(delta)
412
if 'no-eol' in self._index.get_options(version_id):
413
line = content._lines[-1][1].rstrip('\n')
414
content._lines[-1] = (content._lines[-1][0], line)
416
if sha_strings(content.text()) != digest:
417
raise KnitCorrupt(self.filename, 'sha-1 does not match')
421
def _check_versions_present(self, version_ids):
422
"""Check that all specified versions are present."""
423
version_ids = set(version_ids)
424
for r in list(version_ids):
425
if self._index.has_version(r):
426
version_ids.remove(r)
428
raise RevisionNotPresent(list(version_ids)[0], self.filename)
430
def add_lines_with_ghosts(self, version_id, parents, lines):
431
"""See VersionedFile.add_lines_with_ghosts()."""
432
self._check_add(version_id, lines)
433
return self._add(version_id, lines[:], parents, self.delta)
435
def add_lines(self, version_id, parents, lines):
436
"""See VersionedFile.add_lines."""
437
self._check_add(version_id, lines)
438
self._check_versions_present(parents)
439
return self._add(version_id, lines[:], parents, self.delta)
441
def _check_add(self, version_id, lines):
442
"""check that version_id and lines are safe to add."""
443
assert self.writable, "knit is not opened for write"
444
### FIXME escape. RBC 20060228
445
if contains_whitespace(version_id):
446
raise InvalidRevisionId(version_id)
447
if self.has_version(version_id):
448
raise RevisionAlreadyPresent(version_id, self.filename)
450
if False or __debug__:
452
assert '\n' not in l[:-1]
454
def _add(self, version_id, lines, parents, delta):
455
"""Add a set of lines on top of version specified by parents.
457
If delta is true, compress the text as a line-delta against
460
Any versions not present will be converted into ghosts.
462
ghostless_parents = []
464
for parent in parents:
465
if not self.has_version(parent):
466
ghosts.append(parent)
468
ghostless_parents.append(parent)
470
if delta and not len(ghostless_parents):
473
digest = sha_strings(lines)
476
if lines[-1][-1] != '\n':
477
options.append('no-eol')
478
lines[-1] = lines[-1] + '\n'
480
lines = self.factory.make(lines, len(self._index))
481
if self.factory.annotated and len(ghostless_parents) > 0:
482
# Merge annotations from parent texts if so is needed.
483
self._merge_annotations(lines, ghostless_parents)
485
if len(ghostless_parents) and delta:
486
# To speed the extract of texts the delta chain is limited
487
# to a fixed number of deltas. This should minimize both
488
# I/O and the time spend applying deltas.
490
delta_parents = ghostless_parents
492
parent = delta_parents[0]
493
method = self._index.get_method(parent)
494
if method == 'fulltext':
496
delta_parents = self._index.get_parents(parent)
498
if method == 'line-delta':
502
options.append('line-delta')
503
content = self._get_content(ghostless_parents[0])
504
delta_hunks = content.line_delta(lines)
505
store_lines = self.factory.lower_line_delta(delta_hunks)
507
options.append('fulltext')
508
store_lines = self.factory.lower_fulltext(lines)
510
where, size = self._data.add_record(version_id, digest, store_lines)
511
self._index.add_version(version_id, options, where, size, parents)
513
def check(self, progress_bar=None):
514
"""See VersionedFile.check()."""
516
def clone_text(self, new_version_id, old_version_id, parents):
517
"""See VersionedFile.clone_text()."""
518
# FIXME RBC 20060228 make fast by only inserting an index with null delta.
519
self.add_lines(new_version_id, parents, self.get_lines(old_version_id))
521
def get_lines(self, version_id):
522
"""See VersionedFile.get_lines()."""
523
return self._get_content(version_id).text()
525
def iter_lines_added_or_present_in_versions(self, version_ids=None):
526
"""See VersionedFile.iter_lines_added_or_present_in_versions()."""
527
if version_ids is None:
528
version_ids = self.versions()
529
# we dont care about inclusions, the caller cares.
530
# but we need to setup a list of records to visit.
531
# we need version_id, position, length
532
version_id_records = []
533
for version_id in version_ids:
534
if not self.has_version(version_id):
535
raise RevisionNotPresent(version_id, self.filename)
536
data_pos, length = self._index.get_position(version_id)
537
version_id_records.append((version_id, data_pos, length))
538
pb = bzrlib.ui.ui_factory.nested_progress_bar()
540
total = len(version_id_records)
542
pb.update('Walking content.', count, total)
543
for version_id, data, sha_value in \
544
self._data.read_records_iter(version_id_records):
545
pb.update('Walking content.', count, total)
546
method = self._index.get_method(version_id)
547
version_idx = self._index.lookup(version_id)
548
assert method in ('fulltext', 'line-delta')
549
if method == 'fulltext':
550
content = self.factory.parse_fulltext(data, version_idx)
551
for line in content.text():
554
delta = self.factory.parse_line_delta(data, version_idx)
555
for start, end, count, lines in delta:
556
for origin, line in lines:
559
pb.update('Walking content.', total, total)
562
pb.update('Walking content.', total, total)
566
def num_versions(self):
567
"""See VersionedFile.num_versions()."""
568
return self._index.num_versions()
570
__len__ = num_versions
572
def annotate_iter(self, version_id):
573
"""See VersionedFile.annotate_iter."""
574
content = self._get_content(version_id)
575
for origin, text in content.annotate_iter():
576
yield self._index.idx_to_name(origin), text
578
def get_parents(self, version_id):
579
"""See VersionedFile.get_parents."""
580
self._check_versions_present([version_id])
581
return list(self._index.get_parents(version_id))
583
def get_parents_with_ghosts(self, version_id):
584
"""See VersionedFile.get_parents."""
585
self._check_versions_present([version_id])
586
return list(self._index.get_parents_with_ghosts(version_id))
588
def get_ancestry(self, versions):
589
"""See VersionedFile.get_ancestry."""
590
if isinstance(versions, basestring):
591
versions = [versions]
594
self._check_versions_present(versions)
595
return self._index.get_ancestry(versions)
597
def get_ancestry_with_ghosts(self, versions):
598
"""See VersionedFile.get_ancestry_with_ghosts."""
599
if isinstance(versions, basestring):
600
versions = [versions]
603
self._check_versions_present(versions)
604
return self._index.get_ancestry_with_ghosts(versions)
606
def _reannotate_line_delta(self, other, lines, new_version_id,
608
"""Re-annotate line-delta and return new delta."""
610
for start, end, count, contents \
611
in self.factory.parse_line_delta_iter(lines):
613
for origin, line in contents:
614
old_version_id = other._index.idx_to_name(origin)
615
if old_version_id == new_version_id:
616
idx = new_version_idx
618
idx = self._index.lookup(old_version_id)
619
new_lines.append((idx, line))
620
new_delta.append((start, end, count, new_lines))
622
return self.factory.lower_line_delta(new_delta)
624
def _reannotate_fulltext(self, other, lines, new_version_id,
626
"""Re-annotate fulltext and return new version."""
627
content = self.factory.parse_fulltext(lines, new_version_idx)
629
for origin, line in content.annotate_iter():
630
old_version_id = other._index.idx_to_name(origin)
631
if old_version_id == new_version_id:
632
idx = new_version_idx
634
idx = self._index.lookup(old_version_id)
635
new_lines.append((idx, line))
637
return self.factory.lower_fulltext(KnitContent(new_lines))
639
#@deprecated_method(zero_eight)
640
def walk(self, version_ids):
641
"""See VersionedFile.walk."""
642
# We take the short path here, and extract all relevant texts
643
# and put them in a weave and let that do all the work. Far
644
# from optimal, but is much simpler.
645
# FIXME RB 20060228 this really is inefficient!
646
from bzrlib.weave import Weave
648
w = Weave(self.filename)
649
ancestry = self.get_ancestry(version_ids)
650
sorted_graph = topo_sort(self._index.get_graph())
651
version_list = [vid for vid in sorted_graph if vid in ancestry]
653
for version_id in version_list:
654
lines = self.get_lines(version_id)
655
w.add_lines(version_id, self.get_parents(version_id), lines)
657
for lineno, insert_id, dset, line in w.walk(version_ids):
658
yield lineno, insert_id, dset, line
661
class _KnitComponentFile(object):
662
"""One of the files used to implement a knit database"""
664
def __init__(self, transport, filename, mode):
665
self._transport = transport
666
self._filename = filename
669
def write_header(self):
670
old_len = self._transport.append(self._filename, StringIO(self.HEADER))
672
raise KnitCorrupt(self._filename, 'misaligned after writing header')
674
def check_header(self, fp):
675
line = fp.read(len(self.HEADER))
676
if line != self.HEADER:
677
raise KnitHeaderError(badline=line)
680
"""Commit is a nop."""
683
return '%s(%s)' % (self.__class__.__name__, self._filename)
686
class _KnitIndex(_KnitComponentFile):
687
"""Manages knit index file.
689
The index is already kept in memory and read on startup, to enable
690
fast lookups of revision information. The cursor of the index
691
file is always pointing to the end, making it easy to append
694
_cache is a cache for fast mapping from version id to a Index
697
_history is a cache for fast mapping from indexes to version ids.
699
The index data format is dictionary compressed when it comes to
700
parent references; a index entry may only have parents that with a
701
lover index number. As a result, the index is topological sorted.
703
Duplicate entries may be written to the index for a single version id
704
if this is done then the latter one completely replaces the former:
705
this allows updates to correct version and parent information.
706
Note that the two entries may share the delta, and that successive
707
annotations and references MUST point to the first entry.
710
HEADER = "# bzr knit index 7\n"
712
def _cache_version(self, version_id, options, pos, size, parents):
713
val = (version_id, options, pos, size, parents)
714
self._cache[version_id] = val
715
if not version_id in self._history:
716
self._history.append(version_id)
718
def _iter_index(self, fp):
724
#for l in lines.splitlines(False):
727
def __init__(self, transport, filename, mode, create=False):
728
_KnitComponentFile.__init__(self, transport, filename, mode)
730
# position in _history is the 'official' index for a revision
731
# but the values may have come from a newer entry.
732
# so - wc -l of a knit index is != the number of uniqe names
735
pb = bzrlib.ui.ui_factory.nested_progress_bar()
740
pb.update('read knit index', count, total)
741
fp = self._transport.get(self._filename)
742
self.check_header(fp)
743
for rec in self._iter_index(fp):
746
pb.update('read knit index', count, total)
747
parents = self._parse_parents(rec[4:])
748
self._cache_version(rec[0], rec[1].split(','), int(rec[2]), int(rec[3]),
750
except NoSuchFile, e:
751
if mode != 'w' or not create:
755
pb.update('read knit index', total, total)
758
def _parse_parents(self, compressed_parents):
759
"""convert a list of string parent values into version ids.
761
ints are looked up in the index.
762
.FOO values are ghosts and converted in to FOO.
765
for value in compressed_parents:
766
if value.startswith('.'):
767
result.append(value[1:])
769
assert isinstance(value, str)
770
result.append(self._history[int(value)])
775
for version_id, index in self._cache.iteritems():
776
graph.append((version_id, index[4]))
779
def get_ancestry(self, versions):
780
"""See VersionedFile.get_ancestry."""
781
# get a graph of all the mentioned versions:
783
pending = set(versions)
785
version = pending.pop()
786
parents = self._cache[version][4]
789
parents = [parent for parent in parents if parent in self._cache]
790
for parent in parents:
791
# if not completed and not a ghost
792
if parent not in graph:
794
graph[version] = parents
795
return topo_sort(graph.items())
797
def get_ancestry_with_ghosts(self, versions):
798
"""See VersionedFile.get_ancestry_with_ghosts."""
799
# get a graph of all the mentioned versions:
801
pending = set(versions)
803
version = pending.pop()
805
parents = self._cache[version][4]
812
for parent in parents:
813
if parent not in graph:
815
graph[version] = parents
816
return topo_sort(graph.items())
818
def num_versions(self):
819
return len(self._history)
821
__len__ = num_versions
823
def get_versions(self):
826
def idx_to_name(self, idx):
827
return self._history[idx]
829
def lookup(self, version_id):
830
assert version_id in self._cache
831
return self._history.index(version_id)
833
def _version_list_to_index(self, versions):
835
for version in versions:
836
if version in self._cache:
837
result_list.append(str(self._history.index(version)))
839
result_list.append('.' + version.encode('utf-8'))
840
return ' '.join(result_list)
842
def add_version(self, version_id, options, pos, size, parents):
843
"""Add a version record to the index."""
844
self._cache_version(version_id, options, pos, size, parents)
846
content = "%s %s %s %s %s\n" % (version_id,
850
self._version_list_to_index(parents))
851
self._transport.append(self._filename, StringIO(content))
853
def has_version(self, version_id):
854
"""True if the version is in the index."""
855
return self._cache.has_key(version_id)
857
def get_position(self, version_id):
858
"""Return data position and size of specified version."""
859
return (self._cache[version_id][2], \
860
self._cache[version_id][3])
862
def get_method(self, version_id):
863
"""Return compression method of specified version."""
864
options = self._cache[version_id][1]
865
if 'fulltext' in options:
868
assert 'line-delta' in options
871
def get_options(self, version_id):
872
return self._cache[version_id][1]
874
def get_parents(self, version_id):
875
"""Return parents of specified version ignoring ghosts."""
876
return [parent for parent in self._cache[version_id][4]
877
if parent in self._cache]
879
def get_parents_with_ghosts(self, version_id):
880
"""Return parents of specified version wth ghosts."""
881
return self._cache[version_id][4]
883
def check_versions_present(self, version_ids):
884
"""Check that all specified versions are present."""
885
version_ids = set(version_ids)
886
for version_id in list(version_ids):
887
if version_id in self._cache:
888
version_ids.remove(version_id)
890
raise RevisionNotPresent(list(version_ids)[0], self.filename)
893
class _KnitData(_KnitComponentFile):
894
"""Contents of the knit data file"""
896
HEADER = "# bzr knit data 7\n"
898
def __init__(self, transport, filename, mode, create=False):
899
_KnitComponentFile.__init__(self, transport, filename, mode)
901
self._checked = False
903
self._transport.put(self._filename, StringIO(''))
905
def _open_file(self):
906
if self._file is None:
908
self._file = self._transport.get(self._filename)
913
def add_record(self, version_id, digest, lines):
914
"""Write new text record to disk. Returns the position in the
915
file where it was written."""
917
data_file = GzipFile(None, mode='wb', fileobj=sio)
918
print >>data_file, "version %s %d %s" % (version_id, len(lines), digest)
919
data_file.writelines(lines)
920
print >>data_file, "end %s\n" % version_id
923
content = sio.getvalue()
924
start_pos = self._transport.append(self._filename, StringIO(content))
925
return start_pos, len(content)
927
def _parse_record(self, version_id, data):
928
df = GzipFile(mode='rb', fileobj=StringIO(data))
929
rec = df.readline().split()
931
raise KnitCorrupt(self._filename, 'unexpected number of records')
932
if rec[1] != version_id:
933
raise KnitCorrupt(self.file.name,
934
'unexpected version, wanted %r' % version_id)
936
record_contents = self._read_record_contents(df, lines)
938
if l != 'end %s\n' % version_id:
939
raise KnitCorrupt(self._filename, 'unexpected version end line %r, wanted %r'
941
return record_contents, rec[3]
943
def _read_record_contents(self, df, record_lines):
944
"""Read and return n lines from datafile."""
946
for i in range(record_lines):
947
r.append(df.readline())
950
def read_records_iter(self, records):
951
"""Read text records from data file and yield result.
953
Each passed record is a tuple of (version_id, pos, len) and
954
will be read in the given order. Yields (version_id,
958
class ContinuousRange:
959
def __init__(self, rec_id, pos, size):
961
self.end_pos = pos + size
962
self.versions = [(rec_id, pos, size)]
964
def add(self, rec_id, pos, size):
965
if self.end_pos != pos:
967
self.end_pos = pos + size
968
self.versions.append((rec_id, pos, size))
972
for rec_id, pos, size in self.versions:
973
yield rec_id, fp.read(size)
975
# We take it that the transport optimizes the fetching as good
976
# as possible (ie, reads continous ranges.)
977
response = self._transport.readv(self._filename,
978
[(pos, size) for version_id, pos, size in records])
980
for (record_id, pos, size), (pos, data) in izip(iter(records), response):
981
content, digest = self._parse_record(record_id, data)
982
yield record_id, content, digest
984
def read_records(self, records):
985
"""Read records into a dictionary."""
987
for record_id, content, digest in self.read_records_iter(records):
988
components[record_id] = (content, digest)
992
class InterKnit(InterVersionedFile):
993
"""Optimised code paths for knit to knit operations."""
995
_matching_file_factory = KnitVersionedFile
998
def is_compatible(source, target):
999
"""Be compatible with knits. """
1001
return (isinstance(source, KnitVersionedFile) and
1002
isinstance(target, KnitVersionedFile))
1003
except AttributeError:
1006
def join(self, pb=None, msg=None, version_ids=None, ignore_missing=False):
1007
"""See InterVersionedFile.join."""
1008
assert isinstance(self.source, KnitVersionedFile)
1009
assert isinstance(self.target, KnitVersionedFile)
1011
if version_ids is None:
1012
version_ids = self.source.versions()
1014
if not ignore_missing:
1015
self.source._check_versions_present(version_ids)
1017
version_ids = set(self.source.versions()).intersection(
1024
from bzrlib.progress import DummyProgress
1025
pb = DummyProgress()
1027
version_ids = list(version_ids)
1028
if None in version_ids:
1029
version_ids.remove(None)
1031
self.source_ancestry = set(self.source.get_ancestry(version_ids))
1032
this_versions = set(self.target._index.get_versions())
1033
needed_versions = self.source_ancestry - this_versions
1034
cross_check_versions = self.source_ancestry.intersection(this_versions)
1035
mismatched_versions = set()
1036
for version in cross_check_versions:
1037
# scan to include needed parents.
1038
n1 = set(self.target.get_parents_with_ghosts(version))
1039
n2 = set(self.source.get_parents_with_ghosts(version))
1041
# FIXME TEST this check for cycles being introduced works
1042
# the logic is we have a cycle if in our graph we are an
1043
# ancestor of any of the n2 revisions.
1049
parent_ancestors = self.source.get_ancestry(parent)
1050
if version in parent_ancestors:
1051
raise errors.GraphCycleError([parent, version])
1052
# ensure this parent will be available later.
1053
new_parents = n2.difference(n1)
1054
needed_versions.update(new_parents.difference(this_versions))
1055
mismatched_versions.add(version)
1057
if not needed_versions and not cross_check_versions:
1059
full_list = topo_sort(self.source.get_graph())
1061
version_list = [i for i in full_list if (not self.target.has_version(i)
1062
and i in needed_versions)]
1065
for version_id in version_list:
1066
data_pos, data_size = self.source._index.get_position(version_id)
1067
records.append((version_id, data_pos, data_size))
1070
for version_id, lines, digest \
1071
in self.source._data.read_records_iter(records):
1072
options = self.source._index.get_options(version_id)
1073
parents = self.source._index.get_parents_with_ghosts(version_id)
1075
for parent in parents:
1076
# if source has the parent, we must hav grabbed it first.
1077
assert (self.target.has_version(parent) or not
1078
self.source.has_version(parent))
1080
if self.target.factory.annotated:
1081
# FIXME jrydberg: it should be possible to skip
1082
# re-annotating components if we know that we are
1083
# going to pull all revisions in the same order.
1084
new_version_id = version_id
1085
new_version_idx = self.target._index.num_versions()
1086
if 'fulltext' in options:
1087
lines = self.target._reannotate_fulltext(self.source, lines,
1088
new_version_id, new_version_idx)
1089
elif 'line-delta' in options:
1090
lines = self.target._reannotate_line_delta(self.source, lines,
1091
new_version_id, new_version_idx)
1094
pb.update("Joining knit", count, len(version_list))
1096
pos, size = self.target._data.add_record(version_id, digest, lines)
1097
self.target._index.add_version(version_id, options, pos, size, parents)
1099
for version in mismatched_versions:
1100
n1 = set(self.target.get_parents_with_ghosts(version))
1101
n2 = set(self.source.get_parents_with_ghosts(version))
1102
# write a combined record to our history preserving the current
1103
# parents as first in the list
1104
new_parents = self.target.get_parents_with_ghosts(version) + list(n2.difference(n1))
1105
self.target.fix_parents(version, new_parents)
1110
InterVersionedFile.register_optimiser(InterKnit)