67
67
something faster than difflib, which is after all pure Python.
68
68
Another approach is to just store the gzipped full text of big files,
69
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.
89
84
# if there are gaps and that can happen if we're interrupted while
90
85
# 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.
96
89
import sys, zlib, struct, mdiff, stat, os, sha
97
90
from binascii import hexlify, unhexlify
101
96
_HEADER = "bzr revfile v1\n"
121
116
class LimitHitException(Exception):
124
class Revfile(object):
125
def __init__(self, basename, mode):
120
def __init__(self, basename):
121
# TODO: Option to open readonly
126
123
# TODO: Lock file while open
128
125
# TODO: advise of random access
130
127
self.basename = basename
132
if mode not in ['r', 'w']:
133
raise RevfileError("invalid open mode %r" % mode)
136
129
idxname = basename + '.irev'
137
130
dataname = basename + '.drev'
143
136
raise RevfileError("half-assed revfile")
145
138
if not idx_exists:
147
raise RevfileError("Revfile %r does not exist" % basename)
149
139
self.idxfile = open(idxname, 'w+b')
150
140
self.datafile = open(dataname, 'w+b')
142
print 'init empty file'
152
143
self.idxfile.write(_HEADER)
153
144
self.idxfile.flush()
160
self.idxfile = open(idxname, diskmode)
161
self.datafile = open(dataname, diskmode)
146
self.idxfile = open(idxname, 'r+b')
147
self.datafile = open(dataname, 'r+b')
163
149
h = self.idxfile.read(_RECORDSIZE)
170
156
if idx < 0 or idx > len(self):
171
157
raise RevfileError("invalid index %r" % idx)
173
def _check_write(self):
175
raise RevfileError("%r is open readonly" % self.basename)
178
160
def find_sha(self, s):
179
161
assert isinstance(s, str)
216
198
assert self.idxfile.tell() == _RECORDSIZE * (idx + 1)
217
199
data_offset = self.datafile.tell()
219
assert isinstance(data, str) # not unicode or anything weird
201
assert isinstance(data, str) # not unicode or anything wierd
221
203
self.datafile.write(data)
222
204
self.datafile.flush()
242
224
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
227
def _add_delta(self, text, text_sha, base, compress):
262
228
"""Add a text stored relative to a previous text."""
263
229
self._check_index(base)
266
base_text = self.get(base, CHAIN_LIMIT)
232
base_text = self.get(base, recursion_limit=CHAIN_LIMIT)
267
233
except LimitHitException:
268
234
return self._add_full_text(text, text_sha, compress)
270
236
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
238
# If the delta is larger than the text, we might as well just
279
239
# store the text. (OK, the delta might be more compressible,
285
245
return self._add_compressed(text_sha, data, base, compress)
288
def add(self, text, base=None, compress=True):
248
def add(self, text, base=_NO_RECORD, compress=True):
289
249
"""Add a new text to the revfile.
291
251
If the text is already present them its existing id is
312
267
# it's the same, in case someone ever breaks SHA-1.
313
268
return idx # already present
315
# base = self._choose_base(ord(text_sha[0]), base)
317
270
if base == _NO_RECORD:
318
271
return self._add_full_text(text, text_sha, compress)
338
291
text = self._get_patched(idx, idxrec, recursion_limit)
340
293
if sha.new(text).digest() != idxrec[I_SHA]:
341
raise RevfileError("corrupt SHA-1 digest on record %d in %s"
342
% (idx, self.basename))
294
raise RevfileError("corrupt SHA-1 digest on record %d"
412
365
"""Index by sequence id returns the index field"""
413
366
## TODO: Can avoid seek if we just moved there...
414
367
self._seek_index(idx)
415
idxrec = self._read_next_index()
417
raise IndexError("no index %d" % idx)
368
return self._read_next_index()
422
371
def _seek_index(self, idx):
424
373
raise RevfileError("invalid index %r" % idx)
425
374
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
377
def _read_next_index(self):
443
378
rec = self.idxfile.read(_RECORDSIZE)
380
raise IndexError("end of index file")
446
381
elif len(rec) != _RECORDSIZE:
447
382
raise RevfileError("short read of %d bytes getting index %d from %r"
448
383
% (len(rec), idx, self.basename))
478
413
for idx in range(len(self)):
479
414
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
420
r = Revfile("testrev")
500
424
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")
425
sys.stderr.write("usage: revfile dump\n"
427
" revfile add-delta BASE\n"
429
" revfile find-sha HEX\n"
430
" revfile total-text-size\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())
435
new_idx = r.add(sys.stdin.read())
522
437
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)
438
new_idx = r.add(sys.stdin.read(), int(argv[2]))
530
440
elif cmd == 'dump':
532
442
elif cmd == 'get':
535
445
except IndexError:
536
sys.stderr.write("usage: revfile get FILE IDX\n")
446
sys.stderr.write("usage: revfile get IDX\n")
541
449
if idx < 0 or idx >= len(r):
542
450
sys.stderr.write("invalid index %r\n" % idx)
545
453
sys.stdout.write(r.get(idx))
546
454
elif cmd == 'find-sha':
548
s = unhexlify(argv[3])
456
s = unhexlify(argv[2])
549
457
except IndexError:
550
sys.stderr.write("usage: revfile find-sha FILE HEX\n")
458
sys.stderr.write("usage: revfile find-sha HEX\n")
553
idx = ro().find_sha(s)
554
462
if idx == _NO_RECORD:
555
463
sys.stderr.write("no such record\n")
559
467
elif cmd == 'total-text-size':
560
print ro().total_text_size()
468
print r.total_text_size()
561
469
elif cmd == 'last':
564
import bzrlib.progress
565
pb = bzrlib.progress.ProgressBar()
568
472
sys.stderr.write("unknown command %r\n" % cmd)