61
61
balanced tree indexed by SHA1 so we can much more efficiently find the
62
62
index associated with a particular hash. For 100,000 revs we would be
63
63
able to find it in about 17 random reads, which is not too bad.
65
This performs pretty well except when trying to calculate deltas of
66
really large files. For that the main thing would be to plug in
67
something faster than difflib, which is after all pure Python.
68
Another approach is to just store the gzipped full text of big files,
69
though perhaps that's too perverse?
71
The iter method here will generally read through the whole index file
72
in one go. With readahead in the kernel and python/libc (typically
73
128kB) this means that there should be no seeks and often only one
74
read() call to get everything into memory.
78
67
# TODO: Something like pread() would make this slightly simpler and
79
68
# perhaps more efficient.
81
# TODO: Could also try to mmap things... Might be faster for the
82
# index in particular?
84
# TODO: Some kind of faster lookup of SHAs? The bad thing is that probably means
85
# rewriting existing records, which is not so nice.
87
# TODO: Something to check that regions identified in the index file
88
# completely butt up and do not overlap. Strictly it's not a problem
89
# if there are gaps and that can happen if we're interrupted while
90
# writing to the datafile. Overlapping would be very bad though.
92
# TODO: Shouldn't need to lock if we always write in append mode and
93
# then ftell after writing to see where it went. In any case we
94
# assume the whole branch is protected by a lock.
70
# TODO: Could also try to mmap things...
96
73
import sys, zlib, struct, mdiff, stat, os, sha
97
74
from binascii import hexlify, unhexlify
101
80
_HEADER = "bzr revfile v1\n"
114
# maximum number of patches in a row before recording a whole text.
118
94
class RevfileError(Exception):
121
class LimitHitException(Exception):
124
class Revfile(object):
125
def __init__(self, basename, mode):
100
def __init__(self, basename):
101
# TODO: Option to open readonly
126
103
# TODO: Lock file while open
128
105
# TODO: advise of random access
130
107
self.basename = basename
132
if mode not in ['r', 'w']:
133
raise RevfileError("invalid open mode %r" % mode)
136
109
idxname = basename + '.irev'
137
110
dataname = basename + '.drev'
143
116
raise RevfileError("half-assed revfile")
145
118
if not idx_exists:
147
raise RevfileError("Revfile %r does not exist" % basename)
149
119
self.idxfile = open(idxname, 'w+b')
150
120
self.datafile = open(dataname, 'w+b')
122
print 'init empty file'
152
123
self.idxfile.write(_HEADER)
153
124
self.idxfile.flush()
160
self.idxfile = open(idxname, diskmode)
161
self.datafile = open(dataname, diskmode)
126
self.idxfile = open(idxname, 'r+b')
127
self.datafile = open(dataname, 'r+b')
163
129
h = self.idxfile.read(_RECORDSIZE)
183
145
if idxrec[I_SHA] == s:
190
def _add_compressed(self, text_sha, data, base, compress):
191
# well, maybe compress
196
# don't do compression if it's too small; it's unlikely to win
197
# enough to be worthwhile
198
compr_data = zlib.compress(data)
199
compr_len = len(compr_data)
200
if compr_len < data_len:
203
##print '- compressed %d -> %d, %.1f%%' \
204
## % (data_len, compr_len, float(compr_len)/float(data_len) * 100.0)
205
return self._add_raw(text_sha, data, base, flags)
209
def _add_raw(self, text_sha, data, base, flags):
151
def _add_common(self, text_sha, data, base):
210
152
"""Add pre-processed data, can be either full text or delta.
212
154
This does the compression if that makes sense."""
159
# don't do compression if it's too small; it's unlikely to win
160
# enough to be worthwhile
161
compr_data = zlib.compress(data)
162
compr_len = len(compr_data)
163
if compr_len < data_len:
166
print '- compressed %d -> %d, %.1f%%' \
167
% (data_len, compr_len, float(compr_len)/float(data_len) * 100.0)
214
170
self.datafile.seek(0, 2) # to end
215
171
self.idxfile.seek(0, 2)
216
172
assert self.idxfile.tell() == _RECORDSIZE * (idx + 1)
217
173
data_offset = self.datafile.tell()
219
assert isinstance(data, str) # not unicode or anything weird
175
assert isinstance(data, str) # not unicode or anything wierd
221
177
self.datafile.write(data)
222
178
self.datafile.flush()
236
def _add_full_text(self, text, text_sha, compress):
192
def _add_full_text(self, text, text_sha):
237
193
"""Add a full text to the file.
239
195
This is not compressed against any reference version.
241
197
Returns the index for that text."""
242
return self._add_compressed(text_sha, text, _NO_RECORD, compress)
246
def _choose_base(self, seed, base):
248
if base == _NO_RECORD:
251
if idxrec[I_BASE] == _NO_RECORD:
254
base = idxrec[I_BASE]
257
return base # relative to this full text
261
def _add_delta(self, text, text_sha, base, compress):
198
return self._add_common(text_sha, text, _NO_RECORD)
201
def _add_delta(self, text, text_sha, base):
262
202
"""Add a text stored relative to a previous text."""
263
203
self._check_index(base)
266
base_text = self.get(base, CHAIN_LIMIT)
267
except LimitHitException:
268
return self._add_full_text(text, text_sha, compress)
204
base_text = self.get(base)
270
205
data = mdiff.bdiff(base_text, text)
273
if True: # paranoid early check for bad diff
274
result = mdiff.bpatch(base_text, data)
275
assert result == text
278
207
# If the delta is larger than the text, we might as well just
279
208
# store the text. (OK, the delta might be more compressible,
280
209
# but the overhead of applying it probably still makes it
281
210
# bad, and I don't want to compress both of them to find out.)
282
211
if len(data) >= len(text):
283
return self._add_full_text(text, text_sha, compress)
212
return self._add_full_text(text, text_sha)
285
return self._add_compressed(text_sha, data, base, compress)
288
def add(self, text, base=None, compress=True):
214
return self._add_common(text_sha, data, base)
217
def add(self, text, base=_NO_RECORD):
289
218
"""Add a new text to the revfile.
291
220
If the text is already present them its existing id is
292
221
returned and the file is not changed.
294
If compress is true then gzip compression will be used if it
297
223
If a base index is specified, that text *may* be used for
298
224
delta compression of the new text. Delta compression will
299
225
only be used if it would be a size win and if the existing
300
226
base is not at too long of a delta chain already.
307
228
text_sha = sha.new(text).digest()
309
230
idx = self.find_sha(text_sha)
312
233
# it's the same, in case someone ever breaks SHA-1.
313
234
return idx # already present
315
# base = self._choose_base(ord(text_sha[0]), base)
317
236
if base == _NO_RECORD:
318
return self._add_full_text(text, text_sha, compress)
237
return self._add_full_text(text, text_sha)
320
return self._add_delta(text, text_sha, base, compress)
324
def get(self, idx, recursion_limit=None):
325
"""Retrieve text of a previous revision.
327
If recursion_limit is an integer then walk back at most that
328
many revisions and then raise LimitHitException, indicating
329
that we ought to record a new file text instead of another
330
delta. Don't use this when trying to get out an existing
239
return self._add_delta(text, text_sha, base)
333
244
idxrec = self[idx]
334
245
base = idxrec[I_BASE]
335
246
if base == _NO_RECORD:
336
247
text = self._get_full_text(idx, idxrec)
338
text = self._get_patched(idx, idxrec, recursion_limit)
249
text = self._get_patched(idx, idxrec)
340
251
if sha.new(text).digest() != idxrec[I_SHA]:
341
raise RevfileError("corrupt SHA-1 digest on record %d in %s"
342
% (idx, self.basename))
252
raise RevfileError("corrupt SHA-1 digest on record %d"
380
def _get_patched(self, idx, idxrec, recursion_limit):
291
def _get_patched(self, idx, idxrec):
381
292
base = idxrec[I_BASE]
383
294
assert base < idx # no loops!
385
if recursion_limit == None:
388
sub_limit = recursion_limit - 1
390
raise LimitHitException()
392
base_text = self.get(base, sub_limit)
296
base_text = self.get(base)
393
297
patch = self._get_raw(idx, idxrec)
395
299
text = mdiff.bpatch(base_text, patch)
412
316
"""Index by sequence id returns the index field"""
413
317
## TODO: Can avoid seek if we just moved there...
414
318
self._seek_index(idx)
415
idxrec = self._read_next_index()
417
raise IndexError("no index %d" % idx)
319
return self._read_next_index()
422
322
def _seek_index(self, idx):
424
324
raise RevfileError("invalid index %r" % idx)
425
325
self.idxfile.seek((idx + 1) * _RECORDSIZE)
430
"""Read back all index records.
432
Do not seek the index file while this is underway!"""
433
## sys.stderr.write(" ** iter called ** \n")
436
idxrec = self._read_next_index()
442
328
def _read_next_index(self):
443
329
rec = self.idxfile.read(_RECORDSIZE)
331
raise IndexError("end of index file")
446
332
elif len(rec) != _RECORDSIZE:
447
333
raise RevfileError("short read of %d bytes getting index %d from %r"
448
334
% (len(rec), idx, self.basename))
464
350
f.write("#%-7d " % rec[1])
466
352
f.write("%8x %8d %8d\n" % (rec[2], rec[3], rec[4]))
469
def total_text_size(self):
470
"""Return the sum of sizes of all file texts.
472
This is how much space they would occupy if they were stored without
473
delta and gzip compression.
475
As a side effect this completely validates the Revfile, checking that all
476
texts can be reproduced with the correct SHA-1."""
478
for idx in range(len(self)):
479
t += len(self.get(idx))
483
def check(self, pb=None):
484
"""Extract every version and check its hash."""
486
for i in range(total):
488
pb.update("check revision", i, total)
489
# the get method implicitly checks the SHA-1
357
r = Revfile("testrev")
500
361
except IndexError:
501
sys.stderr.write("usage: revfile dump REVFILE\n"
502
" revfile add REVFILE < INPUT\n"
503
" revfile add-delta REVFILE BASE < INPUT\n"
504
" revfile add-series REVFILE BASE FILE...\n"
505
" revfile get REVFILE IDX\n"
506
" revfile find-sha REVFILE HEX\n"
507
" revfile total-text-size REVFILE\n"
508
" revfile last REVFILE\n")
362
sys.stderr.write("usage: revfile dump\n"
364
" revfile add-delta BASE\n"
366
" revfile find-sha HEX\n")
511
if filename.endswith('.drev') or filename.endswith('.irev'):
512
filename = filename[:-5]
515
return Revfile(filename, 'w')
518
return Revfile(filename, 'r')
521
print rw().add(sys.stdin.read())
371
new_idx = r.add(sys.stdin.read())
522
373
elif cmd == 'add-delta':
523
print rw().add(sys.stdin.read(), int(argv[3]))
524
elif cmd == 'add-series':
529
rev = r.add(file(fn).read(), rev)
374
new_idx = r.add(sys.stdin.read(), int(argv[2]))
530
376
elif cmd == 'dump':
532
378
elif cmd == 'get':
535
381
except IndexError:
536
sys.stderr.write("usage: revfile get FILE IDX\n")
382
sys.stderr.write("usage: revfile get IDX\n")
541
385
if idx < 0 or idx >= len(r):
542
386
sys.stderr.write("invalid index %r\n" % idx)