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):
159
origin, text = line.split(' ', 1)
160
lines.append((int(origin), text))
161
return KnitContent(lines)
163
def parse_line_delta_iter(self, lines):
165
header = lines.pop(0)
166
start, end, c = [int(n) for n in header.split(',')]
169
origin, text = lines.pop(0).split(' ', 1)
170
contents.append((int(origin), text))
171
yield start, end, c, contents
173
def parse_line_delta(self, lines, version):
174
return list(self.parse_line_delta_iter(lines))
176
def lower_fulltext(self, content):
177
return ['%d %s' % (o, t) for o, t in content._lines]
179
def lower_line_delta(self, delta):
181
for start, end, c, lines in delta:
182
out.append('%d,%d,%d\n' % (start, end, c))
183
for origin, text in lines:
184
out.append('%d %s' % (origin, text))
188
class KnitPlainFactory(_KnitFactory):
189
"""Factory for creating plain Content objects."""
193
def parse_fulltext(self, content, version):
194
return self.make(content, version)
196
def parse_line_delta_iter(self, lines, version):
198
header = lines.pop(0)
199
start, end, c = [int(n) for n in header.split(',')]
200
yield start, end, c, zip([version] * c, lines[:c])
203
def parse_line_delta(self, lines, version):
204
return list(self.parse_line_delta_iter(lines, version))
206
def lower_fulltext(self, content):
207
return content.text()
209
def lower_line_delta(self, delta):
211
for start, end, c, lines in delta:
212
out.append('%d,%d,%d\n' % (start, end, c))
213
out.extend([text for origin, text in lines])
217
def make_empty_knit(transport, relpath):
218
"""Construct a empty knit at the specified location."""
219
k = KnitVersionedFile(transport, relpath, 'w', KnitPlainFactory)
223
class KnitVersionedFile(VersionedFile):
224
"""Weave-like structure with faster random access.
226
A knit stores a number of texts and a summary of the relationships
227
between them. Texts are identified by a string version-id. Texts
228
are normally stored and retrieved as a series of lines, but can
229
also be passed as single strings.
231
Lines are stored with the trailing newline (if any) included, to
232
avoid special cases for files with no final newline. Lines are
233
composed of 8-bit characters, not unicode. The combination of
234
these approaches should mean any 'binary' file can be safely
235
stored and retrieved.
238
def __init__(self, relpath, transport, file_mode=None, access_mode=None, factory=None,
239
basis_knit=None, delta=True, create=False):
240
"""Construct a knit at location specified by relpath.
242
:param create: If not True, only open an existing knit.
244
if access_mode is None:
246
super(KnitVersionedFile, self).__init__(access_mode)
247
assert access_mode in ('r', 'w'), "invalid mode specified %r" % access_mode
248
assert not basis_knit or isinstance(basis_knit, KnitVersionedFile), \
251
self.transport = transport
252
self.filename = relpath
253
self.basis_knit = basis_knit
254
self.factory = factory or KnitAnnotateFactory()
255
self.writable = (access_mode == 'w')
258
self._index = _KnitIndex(transport, relpath + INDEX_SUFFIX,
259
access_mode, create=create)
260
self._data = _KnitData(transport, relpath + DATA_SUFFIX,
261
access_mode, create=not len(self.versions()))
263
def clear_cache(self):
264
"""Clear the data cache only."""
265
self._data.clear_cache()
267
def copy_to(self, name, transport):
268
"""See VersionedFile.copy_to()."""
269
# copy the current index to a temp index to avoid racing with local
271
transport.put(name + INDEX_SUFFIX + '.tmp', self.transport.get(self._index._filename))
273
transport.put(name + DATA_SUFFIX, self._data._open_file())
274
# rename the copied index into place
275
transport.rename(name + INDEX_SUFFIX + '.tmp', name + INDEX_SUFFIX)
277
def create_empty(self, name, transport, mode=None):
278
return KnitVersionedFile(name, transport, factory=self.factory, delta=self.delta, create=True)
280
def _fix_parents(self, version, new_parents):
281
"""Fix the parents list for version.
283
This is done by appending a new version to the index
284
with identical data except for the parents list.
285
the parents list must be a superset of the current
288
current_values = self._index._cache[version]
289
assert set(current_values[4]).difference(set(new_parents)) == set()
290
self._index.add_version(version,
296
def get_graph_with_ghosts(self):
297
"""See VersionedFile.get_graph_with_ghosts()."""
298
graph_items = self._index.get_graph()
299
return dict(graph_items)
303
"""See VersionedFile.get_suffixes()."""
304
return [DATA_SUFFIX, INDEX_SUFFIX]
306
def has_ghost(self, version_id):
307
"""True if there is a ghost reference in the file to version_id."""
309
if self.has_version(version_id):
311
# optimisable if needed by memoising the _ghosts set.
312
items = self._index.get_graph()
313
for node, parents in items:
314
for parent in parents:
315
if parent not in self._index._cache:
316
if parent == version_id:
321
"""See VersionedFile.versions."""
322
return self._index.get_versions()
324
def has_version(self, version_id):
325
"""See VersionedFile.has_version."""
326
return self._index.has_version(version_id)
328
__contains__ = has_version
330
def _merge_annotations(self, content, parents):
331
"""Merge annotations for content. This is done by comparing
332
the annotations based on changed to the text."""
333
for parent_id in parents:
334
merge_content = self._get_content(parent_id)
335
seq = SequenceMatcher(None, merge_content.text(), content.text())
336
for i, j, n in seq.get_matching_blocks():
339
content._lines[j:j+n] = merge_content._lines[i:i+n]
341
def _get_components(self, version_id):
342
"""Return a list of (version_id, method, data) tuples that
343
makes up version specified by version_id of the knit.
345
The components should be applied in the order of the returned
348
The basis knit will be used to the largest extent possible
349
since it is assumed that accesses to it is faster.
351
# needed_revisions holds a list of (method, version_id) of
352
# versions that is needed to be fetched to construct the final
353
# version of the file.
355
# basis_revisions is a list of versions that needs to be
356
# fetched but exists in the basis knit.
358
basis = self.basis_knit
365
if basis and basis._index.has_version(cursor):
367
basis_versions.append(cursor)
368
method = picked_knit._index.get_method(cursor)
369
needed_versions.append((method, cursor))
370
if method == 'fulltext':
372
cursor = picked_knit.get_parents(cursor)[0]
377
for comp_id in basis_versions:
378
data_pos, data_size = basis._index.get_data_position(comp_id)
379
records.append((piece_id, data_pos, data_size))
380
components.update(basis._data.read_records(records))
383
for comp_id in [vid for method, vid in needed_versions
384
if vid not in basis_versions]:
385
data_pos, data_size = self._index.get_position(comp_id)
386
records.append((comp_id, data_pos, data_size))
387
components.update(self._data.read_records(records))
389
# get_data_records returns a mapping with the version id as
390
# index and the value as data. The order the components need
391
# to be applied is held by needed_versions (reversed).
393
for method, comp_id in reversed(needed_versions):
394
out.append((comp_id, method, components[comp_id]))
398
def _get_content(self, version_id):
399
"""Returns a content object that makes up the specified
401
if not self.has_version(version_id):
402
raise RevisionNotPresent(version_id, self.filename)
404
if self.basis_knit and version_id in self.basis_knit:
405
return self.basis_knit._get_content(version_id)
408
components = self._get_components(version_id)
409
for component_id, method, (data, digest) in components:
410
version_idx = self._index.lookup(component_id)
411
if method == 'fulltext':
412
assert content is None
413
content = self.factory.parse_fulltext(data, version_idx)
414
elif method == 'line-delta':
415
delta = self.factory.parse_line_delta(data, version_idx)
416
content.apply_delta(delta)
418
if 'no-eol' in self._index.get_options(version_id):
419
line = content._lines[-1][1].rstrip('\n')
420
content._lines[-1] = (content._lines[-1][0], line)
422
if sha_strings(content.text()) != digest:
423
raise KnitCorrupt(self.filename, 'sha-1 does not match')
427
def _check_versions_present(self, version_ids):
428
"""Check that all specified versions are present."""
429
version_ids = set(version_ids)
430
for r in list(version_ids):
431
if self._index.has_version(r):
432
version_ids.remove(r)
434
raise RevisionNotPresent(list(version_ids)[0], self.filename)
436
def _add_lines_with_ghosts(self, version_id, parents, lines):
437
"""See VersionedFile.add_lines_with_ghosts()."""
438
self._check_add(version_id, lines)
439
return self._add(version_id, lines[:], parents, self.delta)
441
def _add_lines(self, version_id, parents, lines):
442
"""See VersionedFile.add_lines."""
443
self._check_add(version_id, lines)
444
self._check_versions_present(parents)
445
return self._add(version_id, lines[:], parents, self.delta)
447
def _check_add(self, version_id, lines):
448
"""check that version_id and lines are safe to add."""
449
assert self.writable, "knit is not opened for write"
450
### FIXME escape. RBC 20060228
451
if contains_whitespace(version_id):
452
raise InvalidRevisionId(version_id)
453
if self.has_version(version_id):
454
raise RevisionAlreadyPresent(version_id, self.filename)
456
if False or __debug__:
458
assert '\n' not in l[:-1]
460
def _add(self, version_id, lines, parents, delta):
461
"""Add a set of lines on top of version specified by parents.
463
If delta is true, compress the text as a line-delta against
466
Any versions not present will be converted into ghosts.
468
ghostless_parents = []
470
for parent in parents:
471
if not self.has_version(parent):
472
ghosts.append(parent)
474
ghostless_parents.append(parent)
476
if delta and not len(ghostless_parents):
479
digest = sha_strings(lines)
482
if lines[-1][-1] != '\n':
483
options.append('no-eol')
484
lines[-1] = lines[-1] + '\n'
486
lines = self.factory.make(lines, len(self._index))
487
if self.factory.annotated and len(ghostless_parents) > 0:
488
# Merge annotations from parent texts if so is needed.
489
self._merge_annotations(lines, ghostless_parents)
491
if len(ghostless_parents) and delta:
492
# To speed the extract of texts the delta chain is limited
493
# to a fixed number of deltas. This should minimize both
494
# I/O and the time spend applying deltas.
496
delta_parents = ghostless_parents
498
parent = delta_parents[0]
499
method = self._index.get_method(parent)
500
if method == 'fulltext':
502
delta_parents = self._index.get_parents(parent)
504
if method == 'line-delta':
508
options.append('line-delta')
509
content = self._get_content(ghostless_parents[0])
510
delta_hunks = content.line_delta(lines)
511
store_lines = self.factory.lower_line_delta(delta_hunks)
513
options.append('fulltext')
514
store_lines = self.factory.lower_fulltext(lines)
516
where, size = self._data.add_record(version_id, digest, store_lines)
517
self._index.add_version(version_id, options, where, size, parents)
519
def check(self, progress_bar=None):
520
"""See VersionedFile.check()."""
522
def _clone_text(self, new_version_id, old_version_id, parents):
523
"""See VersionedFile.clone_text()."""
524
# FIXME RBC 20060228 make fast by only inserting an index with null delta.
525
self.add_lines(new_version_id, parents, self.get_lines(old_version_id))
527
def get_lines(self, version_id):
528
"""See VersionedFile.get_lines()."""
529
return self._get_content(version_id).text()
531
def iter_lines_added_or_present_in_versions(self, version_ids=None):
532
"""See VersionedFile.iter_lines_added_or_present_in_versions()."""
533
if version_ids is None:
534
version_ids = self.versions()
535
# we dont care about inclusions, the caller cares.
536
# but we need to setup a list of records to visit.
537
# we need version_id, position, length
538
version_id_records = []
539
requested_versions = list(version_ids)
540
# filter for available versions
541
for version_id in requested_versions:
542
if not self.has_version(version_id):
543
raise RevisionNotPresent(version_id, self.filename)
544
# get a in-component-order queue:
546
for version_id in self.versions():
547
if version_id in requested_versions:
548
version_ids.append(version_id)
549
data_pos, length = self._index.get_position(version_id)
550
version_id_records.append((version_id, data_pos, length))
552
pb = bzrlib.ui.ui_factory.nested_progress_bar()
554
total = len(version_id_records)
556
pb.update('Walking content.', count, total)
557
for version_id, data, sha_value in \
558
self._data.read_records_iter(version_id_records):
559
pb.update('Walking content.', count, total)
560
method = self._index.get_method(version_id)
561
version_idx = self._index.lookup(version_id)
562
assert method in ('fulltext', 'line-delta')
563
if method == 'fulltext':
564
content = self.factory.parse_fulltext(data, version_idx)
565
for line in content.text():
568
delta = self.factory.parse_line_delta(data, version_idx)
569
for start, end, count, lines in delta:
570
for origin, line in lines:
573
pb.update('Walking content.', total, total)
576
pb.update('Walking content.', total, total)
580
def num_versions(self):
581
"""See VersionedFile.num_versions()."""
582
return self._index.num_versions()
584
__len__ = num_versions
586
def annotate_iter(self, version_id):
587
"""See VersionedFile.annotate_iter."""
588
content = self._get_content(version_id)
589
for origin, text in content.annotate_iter():
590
yield self._index.idx_to_name(origin), text
592
def get_parents(self, version_id):
593
"""See VersionedFile.get_parents."""
594
self._check_versions_present([version_id])
595
return list(self._index.get_parents(version_id))
597
def get_parents_with_ghosts(self, version_id):
598
"""See VersionedFile.get_parents."""
599
self._check_versions_present([version_id])
600
return list(self._index.get_parents_with_ghosts(version_id))
602
def get_ancestry(self, versions):
603
"""See VersionedFile.get_ancestry."""
604
if isinstance(versions, basestring):
605
versions = [versions]
608
self._check_versions_present(versions)
609
return self._index.get_ancestry(versions)
611
def get_ancestry_with_ghosts(self, versions):
612
"""See VersionedFile.get_ancestry_with_ghosts."""
613
if isinstance(versions, basestring):
614
versions = [versions]
617
self._check_versions_present(versions)
618
return self._index.get_ancestry_with_ghosts(versions)
620
def _reannotate_line_delta(self, other, lines, new_version_id,
622
"""Re-annotate line-delta and return new delta."""
624
for start, end, count, contents \
625
in self.factory.parse_line_delta_iter(lines):
627
for origin, line in contents:
628
old_version_id = other._index.idx_to_name(origin)
629
if old_version_id == new_version_id:
630
idx = new_version_idx
632
idx = self._index.lookup(old_version_id)
633
new_lines.append((idx, line))
634
new_delta.append((start, end, count, new_lines))
636
return self.factory.lower_line_delta(new_delta)
638
def _reannotate_fulltext(self, other, lines, new_version_id,
640
"""Re-annotate fulltext and return new version."""
641
content = self.factory.parse_fulltext(lines, new_version_idx)
643
for origin, line in content.annotate_iter():
644
old_version_id = other._index.idx_to_name(origin)
645
if old_version_id == new_version_id:
646
idx = new_version_idx
648
idx = self._index.lookup(old_version_id)
649
new_lines.append((idx, line))
651
return self.factory.lower_fulltext(KnitContent(new_lines))
653
#@deprecated_method(zero_eight)
654
def walk(self, version_ids):
655
"""See VersionedFile.walk."""
656
# We take the short path here, and extract all relevant texts
657
# and put them in a weave and let that do all the work. Far
658
# from optimal, but is much simpler.
659
# FIXME RB 20060228 this really is inefficient!
660
from bzrlib.weave import Weave
662
w = Weave(self.filename)
663
ancestry = self.get_ancestry(version_ids)
664
sorted_graph = topo_sort(self._index.get_graph())
665
version_list = [vid for vid in sorted_graph if vid in ancestry]
667
for version_id in version_list:
668
lines = self.get_lines(version_id)
669
w.add_lines(version_id, self.get_parents(version_id), lines)
671
for lineno, insert_id, dset, line in w.walk(version_ids):
672
yield lineno, insert_id, dset, line
675
class _KnitComponentFile(object):
676
"""One of the files used to implement a knit database"""
678
def __init__(self, transport, filename, mode):
679
self._transport = transport
680
self._filename = filename
683
def write_header(self):
684
old_len = self._transport.append(self._filename, StringIO(self.HEADER))
686
raise KnitCorrupt(self._filename, 'misaligned after writing header')
688
def check_header(self, fp):
689
line = fp.read(len(self.HEADER))
690
if line != self.HEADER:
691
raise KnitHeaderError(badline=line)
694
"""Commit is a nop."""
697
return '%s(%s)' % (self.__class__.__name__, self._filename)
700
class _KnitIndex(_KnitComponentFile):
701
"""Manages knit index file.
703
The index is already kept in memory and read on startup, to enable
704
fast lookups of revision information. The cursor of the index
705
file is always pointing to the end, making it easy to append
708
_cache is a cache for fast mapping from version id to a Index
711
_history is a cache for fast mapping from indexes to version ids.
713
The index data format is dictionary compressed when it comes to
714
parent references; a index entry may only have parents that with a
715
lover index number. As a result, the index is topological sorted.
717
Duplicate entries may be written to the index for a single version id
718
if this is done then the latter one completely replaces the former:
719
this allows updates to correct version and parent information.
720
Note that the two entries may share the delta, and that successive
721
annotations and references MUST point to the first entry.
724
HEADER = "# bzr knit index 7\n"
726
def _cache_version(self, version_id, options, pos, size, parents):
727
val = (version_id, options, pos, size, parents)
728
self._cache[version_id] = val
729
if not version_id in self._history:
730
self._history.append(version_id)
732
def _iter_index(self, fp):
738
#for l in lines.splitlines(False):
741
def __init__(self, transport, filename, mode, create=False):
742
_KnitComponentFile.__init__(self, transport, filename, mode)
744
# position in _history is the 'official' index for a revision
745
# but the values may have come from a newer entry.
746
# so - wc -l of a knit index is != the number of uniqe names
749
pb = bzrlib.ui.ui_factory.nested_progress_bar()
754
pb.update('read knit index', count, total)
755
fp = self._transport.get(self._filename)
756
self.check_header(fp)
757
for rec in self._iter_index(fp):
760
pb.update('read knit index', count, total)
761
parents = self._parse_parents(rec[4:])
762
self._cache_version(rec[0], rec[1].split(','), int(rec[2]), int(rec[3]),
764
except NoSuchFile, e:
765
if mode != 'w' or not create:
769
pb.update('read knit index', total, total)
772
def _parse_parents(self, compressed_parents):
773
"""convert a list of string parent values into version ids.
775
ints are looked up in the index.
776
.FOO values are ghosts and converted in to FOO.
779
for value in compressed_parents:
780
if value.startswith('.'):
781
result.append(value[1:])
783
assert isinstance(value, str)
784
result.append(self._history[int(value)])
789
for version_id, index in self._cache.iteritems():
790
graph.append((version_id, index[4]))
793
def get_ancestry(self, versions):
794
"""See VersionedFile.get_ancestry."""
795
# get a graph of all the mentioned versions:
797
pending = set(versions)
799
version = pending.pop()
800
parents = self._cache[version][4]
803
parents = [parent for parent in parents if parent in self._cache]
804
for parent in parents:
805
# if not completed and not a ghost
806
if parent not in graph:
808
graph[version] = parents
809
return topo_sort(graph.items())
811
def get_ancestry_with_ghosts(self, versions):
812
"""See VersionedFile.get_ancestry_with_ghosts."""
813
# get a graph of all the mentioned versions:
815
pending = set(versions)
817
version = pending.pop()
819
parents = self._cache[version][4]
826
for parent in parents:
827
if parent not in graph:
829
graph[version] = parents
830
return topo_sort(graph.items())
832
def num_versions(self):
833
return len(self._history)
835
__len__ = num_versions
837
def get_versions(self):
840
def idx_to_name(self, idx):
841
return self._history[idx]
843
def lookup(self, version_id):
844
assert version_id in self._cache
845
return self._history.index(version_id)
847
def _version_list_to_index(self, versions):
849
for version in versions:
850
if version in self._cache:
851
result_list.append(str(self._history.index(version)))
853
result_list.append('.' + version.encode('utf-8'))
854
return ' '.join(result_list)
856
def add_version(self, version_id, options, pos, size, parents):
857
"""Add a version record to the index."""
858
self._cache_version(version_id, options, pos, size, parents)
860
content = "%s %s %s %s %s\n" % (version_id,
864
self._version_list_to_index(parents))
865
self._transport.append(self._filename, StringIO(content))
867
def has_version(self, version_id):
868
"""True if the version is in the index."""
869
return self._cache.has_key(version_id)
871
def get_position(self, version_id):
872
"""Return data position and size of specified version."""
873
return (self._cache[version_id][2], \
874
self._cache[version_id][3])
876
def get_method(self, version_id):
877
"""Return compression method of specified version."""
878
options = self._cache[version_id][1]
879
if 'fulltext' in options:
882
assert 'line-delta' in options
885
def get_options(self, version_id):
886
return self._cache[version_id][1]
888
def get_parents(self, version_id):
889
"""Return parents of specified version ignoring ghosts."""
890
return [parent for parent in self._cache[version_id][4]
891
if parent in self._cache]
893
def get_parents_with_ghosts(self, version_id):
894
"""Return parents of specified version wth ghosts."""
895
return self._cache[version_id][4]
897
def check_versions_present(self, version_ids):
898
"""Check that all specified versions are present."""
899
version_ids = set(version_ids)
900
for version_id in list(version_ids):
901
if version_id in self._cache:
902
version_ids.remove(version_id)
904
raise RevisionNotPresent(list(version_ids)[0], self.filename)
907
class _KnitData(_KnitComponentFile):
908
"""Contents of the knit data file"""
910
HEADER = "# bzr knit data 7\n"
912
def __init__(self, transport, filename, mode, create=False):
913
_KnitComponentFile.__init__(self, transport, filename, mode)
915
self._checked = False
917
self._transport.put(self._filename, StringIO(''))
920
def clear_cache(self):
921
"""Clear the record cache."""
924
def _open_file(self):
925
if self._file is None:
927
self._file = self._transport.get(self._filename)
932
def add_record(self, version_id, digest, lines):
933
"""Write new text record to disk. Returns the position in the
934
file where it was written."""
936
data_file = GzipFile(None, mode='wb', fileobj=sio)
937
print >>data_file, "version %s %d %s" % (version_id, len(lines), digest)
938
data_file.writelines(lines)
939
print >>data_file, "end %s\n" % version_id
943
self._records[version_id] = (digest, lines)
945
content = sio.getvalue()
947
start_pos = self._transport.append(self._filename, sio)
948
return start_pos, len(content)
950
def _parse_record(self, version_id, data):
951
df = GzipFile(mode='rb', fileobj=StringIO(data))
952
rec = df.readline().split()
954
raise KnitCorrupt(self._filename, 'unexpected number of records')
955
if rec[1] != version_id:
956
raise KnitCorrupt(self._filename,
957
'unexpected version, wanted %r, got %r' % (
960
record_contents = self._read_record_contents(df, lines)
962
if l != 'end %s\n' % version_id:
963
raise KnitCorrupt(self._filename, 'unexpected version end line %r, wanted %r'
965
return record_contents, rec[3]
967
def _read_record_contents(self, df, record_lines):
968
"""Read and return n lines from datafile."""
970
for i in range(record_lines):
971
r.append(df.readline())
974
def read_records_iter(self, records):
975
"""Read text records from data file and yield result.
977
Each passed record is a tuple of (version_id, pos, len) and
978
will be read in the given order. Yields (version_id,
983
for version_id, pos, size in records:
984
if version_id not in self._records:
985
needed_records.append((version_id, pos, size))
987
if len(needed_records):
988
# We take it that the transport optimizes the fetching as good
989
# as possible (ie, reads continous ranges.)
990
response = self._transport.readv(self._filename,
991
[(pos, size) for version_id, pos, size in needed_records])
993
for (record_id, pos, size), (pos, data) in izip(iter(needed_records), response):
994
content, digest = self._parse_record(record_id, data)
995
self._records[record_id] = (digest, content)
997
for version_id, pos, size in records:
998
yield version_id, copy(self._records[version_id][1]), copy(self._records[version_id][0])
1000
def read_records(self, records):
1001
"""Read records into a dictionary."""
1003
for record_id, content, digest in self.read_records_iter(records):
1004
components[record_id] = (content, digest)
1008
class InterKnit(InterVersionedFile):
1009
"""Optimised code paths for knit to knit operations."""
1011
_matching_file_factory = KnitVersionedFile
1014
def is_compatible(source, target):
1015
"""Be compatible with knits. """
1017
return (isinstance(source, KnitVersionedFile) and
1018
isinstance(target, KnitVersionedFile))
1019
except AttributeError:
1022
def join(self, pb=None, msg=None, version_ids=None, ignore_missing=False):
1023
"""See InterVersionedFile.join."""
1024
assert isinstance(self.source, KnitVersionedFile)
1025
assert isinstance(self.target, KnitVersionedFile)
1027
if version_ids is None:
1028
version_ids = self.source.versions()
1030
if not ignore_missing:
1031
self.source._check_versions_present(version_ids)
1033
version_ids = set(self.source.versions()).intersection(
1039
pb = bzrlib.ui.ui_factory.nested_progress_bar()
1041
version_ids = list(version_ids)
1042
if None in version_ids:
1043
version_ids.remove(None)
1045
self.source_ancestry = set(self.source.get_ancestry(version_ids))
1046
this_versions = set(self.target._index.get_versions())
1047
needed_versions = self.source_ancestry - this_versions
1048
cross_check_versions = self.source_ancestry.intersection(this_versions)
1049
mismatched_versions = set()
1050
for version in cross_check_versions:
1051
# scan to include needed parents.
1052
n1 = set(self.target.get_parents_with_ghosts(version))
1053
n2 = set(self.source.get_parents_with_ghosts(version))
1055
# FIXME TEST this check for cycles being introduced works
1056
# the logic is we have a cycle if in our graph we are an
1057
# ancestor of any of the n2 revisions.
1063
parent_ancestors = self.source.get_ancestry(parent)
1064
if version in parent_ancestors:
1065
raise errors.GraphCycleError([parent, version])
1066
# ensure this parent will be available later.
1067
new_parents = n2.difference(n1)
1068
needed_versions.update(new_parents.difference(this_versions))
1069
mismatched_versions.add(version)
1071
if not needed_versions and not cross_check_versions:
1073
full_list = topo_sort(self.source.get_graph())
1075
version_list = [i for i in full_list if (not self.target.has_version(i)
1076
and i in needed_versions)]
1079
for version_id in version_list:
1080
data_pos, data_size = self.source._index.get_position(version_id)
1081
records.append((version_id, data_pos, data_size))
1084
for version_id, lines, digest \
1085
in self.source._data.read_records_iter(records):
1086
options = self.source._index.get_options(version_id)
1087
parents = self.source._index.get_parents_with_ghosts(version_id)
1089
for parent in parents:
1090
# if source has the parent, we must hav grabbed it first.
1091
assert (self.target.has_version(parent) or not
1092
self.source.has_version(parent))
1094
if self.target.factory.annotated:
1095
# FIXME jrydberg: it should be possible to skip
1096
# re-annotating components if we know that we are
1097
# going to pull all revisions in the same order.
1098
new_version_id = version_id
1099
new_version_idx = self.target._index.num_versions()
1100
if 'fulltext' in options:
1101
lines = self.target._reannotate_fulltext(self.source, lines,
1102
new_version_id, new_version_idx)
1103
elif 'line-delta' in options:
1104
lines = self.target._reannotate_line_delta(self.source, lines,
1105
new_version_id, new_version_idx)
1108
pb.update("Joining knit", count, len(version_list))
1110
pos, size = self.target._data.add_record(version_id, digest, lines)
1111
self.target._index.add_version(version_id, options, pos, size, parents)
1113
for version in mismatched_versions:
1114
n1 = set(self.target.get_parents_with_ghosts(version))
1115
n2 = set(self.source.get_parents_with_ghosts(version))
1116
# write a combined record to our history preserving the current
1117
# parents as first in the list
1118
new_parents = self.target.get_parents_with_ghosts(version) + list(n2.difference(n1))
1119
self.target.fix_parents(version, new_parents)
1126
InterVersionedFile.register_optimiser(InterKnit)