3
# (C) 2005 Canonical Ltd
5
# based on an idea by Matt Mackall
6
# modified to squish into bzr by Martin Pool
8
# This program is free software; you can redistribute it and/or modify
9
# it under the terms of the GNU General Public License as published by
10
# the Free Software Foundation; either version 2 of the License, or
11
# (at your option) any later version.
13
# This program is distributed in the hope that it will be useful,
14
# but WITHOUT ANY WARRANTY; without even the implied warranty of
15
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16
# GNU General Public License for more details.
18
# You should have received a copy of the GNU General Public License
19
# along with this program; if not, write to the Free Software
20
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
23
"""Packed file revision storage.
25
A Revfile holds the text history of a particular source file, such
26
as Makefile. It can represent a tree of text versions for that
27
file, allowing for microbranches within a single repository.
29
This is stored on disk as two files: an index file, and a data file.
30
The index file is short and always read completely into memory; the
31
data file is much longer and only the relevant bits of it,
32
identified by the index file, need to be read.
34
Each text version is identified by the SHA-1 of the full text of
35
that version. It also has a sequence number within the file.
37
The index file has a short header and then a sequence of fixed-length
40
* byte[20] SHA-1 of text (as binary, not hex)
41
* uint32 sequence number this is based on, or -1 for full text
42
* uint32 flags: 1=zlib compressed
43
* uint32 offset in text file of start
44
* uint32 length of compressed delta in text file
49
The header is also 48 bytes for tidyness and easy calculation.
51
Both the index and the text are only ever appended to; a consequence
52
is that sequence numbers are stable references. But not every
53
repository in the world will assign the same sequence numbers,
54
therefore the SHA-1 is the only universally unique reference.
56
This is meant to scale to hold 100,000 revisions of a single file, by
57
which time the index file will be ~4.8MB and a bit big to read
60
Some of the reserved fields could be used to implement a (semi?)
61
balanced tree indexed by SHA1 so we can much more efficiently find the
62
index associated with a particular hash. For 100,000 revs we would be
63
able to find it in about 17 random reads, which is not too bad.
67
# TODO: Something like pread() would make this slightly simpler and
68
# perhaps more efficient.
70
# TODO: Could also try to mmap things...
73
import sys, zlib, struct, mdiff, stat, os, sha
74
from binascii import hexlify, unhexlify
80
_HEADER = "bzr revfile v1\n"
81
_HEADER = _HEADER + ('\xff' * (_RECORDSIZE - len(_HEADER)))
82
_NO_RECORD = 0xFFFFFFFFL
84
# fields in the index record
94
class RevfileError(Exception):
100
def __init__(self, basename):
101
# TODO: Option to open readonly
103
# TODO: Lock file while open
105
# TODO: advise of random access
107
self.basename = basename
109
idxname = basename + '.irev'
110
dataname = basename + '.drev'
112
idx_exists = os.path.exists(idxname)
113
data_exists = os.path.exists(dataname)
115
if idx_exists != data_exists:
116
raise RevfileError("half-assed revfile")
119
self.idxfile = open(idxname, 'w+b')
120
self.datafile = open(dataname, 'w+b')
122
print 'init empty file'
123
self.idxfile.write(_HEADER)
126
self.idxfile = open(idxname, 'r+b')
127
self.datafile = open(dataname, 'r+b')
129
h = self.idxfile.read(_RECORDSIZE)
131
raise RevfileError("bad header %r in index of %r"
132
% (h, self.basename))
135
def _check_index(self, idx):
136
if idx < 0 or idx > len(self):
137
raise RevfileError("invalid index %r" % idx)
140
def find_sha(self, s):
141
assert isinstance(s, str)
144
for idx, idxrec in enumerate(self):
145
if idxrec[I_SHA] == s:
152
def _add_compressed(self, text_sha, data, base, compress):
153
# well, maybe compress
158
# don't do compression if it's too small; it's unlikely to win
159
# enough to be worthwhile
160
compr_data = zlib.compress(data)
161
compr_len = len(compr_data)
162
if compr_len < data_len:
165
##print '- compressed %d -> %d, %.1f%%' \
166
## % (data_len, compr_len, float(compr_len)/float(data_len) * 100.0)
167
return self._add_raw(text_sha, data, base, flags)
171
def _add_raw(self, text_sha, data, base, flags):
172
"""Add pre-processed data, can be either full text or delta.
174
This does the compression if that makes sense."""
176
self.datafile.seek(0, 2) # to end
177
self.idxfile.seek(0, 2)
178
assert self.idxfile.tell() == _RECORDSIZE * (idx + 1)
179
data_offset = self.datafile.tell()
181
assert isinstance(data, str) # not unicode or anything wierd
183
self.datafile.write(data)
184
self.datafile.flush()
186
assert isinstance(text_sha, str)
188
entry += struct.pack(">IIII12x", base, flags, data_offset, len(data))
189
assert len(entry) == _RECORDSIZE
191
self.idxfile.write(entry)
198
def _add_full_text(self, text, text_sha):
199
"""Add a full text to the file.
201
This is not compressed against any reference version.
203
Returns the index for that text."""
204
return self._add_compressed(text_sha, text, _NO_RECORD, compress)
207
def _add_delta(self, text, text_sha, base, compress):
208
"""Add a text stored relative to a previous text."""
209
self._check_index(base)
210
base_text = self.get(base)
211
data = mdiff.bdiff(base_text, text)
213
# If the delta is larger than the text, we might as well just
214
# store the text. (OK, the delta might be more compressible,
215
# but the overhead of applying it probably still makes it
216
# bad, and I don't want to compress both of them to find out.)
217
if len(data) >= len(text):
218
return self._add_full_text(text, text_sha, compress)
220
return self._add_compressed(text_sha, data, base, compress)
223
def add(self, text, base=_NO_RECORD, compress=True):
224
"""Add a new text to the revfile.
226
If the text is already present them its existing id is
227
returned and the file is not changed.
229
If compress is true then gzip compression will be used if it
232
If a base index is specified, that text *may* be used for
233
delta compression of the new text. Delta compression will
234
only be used if it would be a size win and if the existing
235
base is not at too long of a delta chain already.
237
text_sha = sha.new(text).digest()
239
idx = self.find_sha(text_sha)
240
if idx != _NO_RECORD:
241
# TODO: Optional paranoid mode where we read out that record and make sure
242
# it's the same, in case someone ever breaks SHA-1.
243
return idx # already present
245
if base == _NO_RECORD:
246
return self._add_full_text(text, text_sha, compress)
248
return self._add_delta(text, text_sha, base, compress)
254
base = idxrec[I_BASE]
255
if base == _NO_RECORD:
256
text = self._get_full_text(idx, idxrec)
258
text = self._get_patched(idx, idxrec)
260
if sha.new(text).digest() != idxrec[I_SHA]:
261
raise RevfileError("corrupt SHA-1 digest on record %d"
268
def _get_raw(self, idx, idxrec):
269
flags = idxrec[I_FLAGS]
271
raise RevfileError("unsupported index flags %#x on index %d"
278
self.datafile.seek(idxrec[I_OFFSET])
280
data = self.datafile.read(l)
282
raise RevfileError("short read %d of %d "
283
"getting text for record %d in %r"
284
% (len(data), l, idx, self.basename))
287
data = zlib.decompress(data)
292
def _get_full_text(self, idx, idxrec):
293
assert idxrec[I_BASE] == _NO_RECORD
295
text = self._get_raw(idx, idxrec)
300
def _get_patched(self, idx, idxrec):
301
base = idxrec[I_BASE]
303
assert base < idx # no loops!
305
base_text = self.get(base)
306
patch = self._get_raw(idx, idxrec)
308
text = mdiff.bpatch(base_text, patch)
315
"""Return number of revisions."""
316
l = os.fstat(self.idxfile.fileno())[stat.ST_SIZE]
318
raise RevfileError("bad length %d on index of %r" % (l, self.basename))
320
raise RevfileError("no header present in index of %r" % (self.basename))
321
return int(l / _RECORDSIZE) - 1
324
def __getitem__(self, idx):
325
"""Index by sequence id returns the index field"""
326
## TODO: Can avoid seek if we just moved there...
327
self._seek_index(idx)
328
return self._read_next_index()
331
def _seek_index(self, idx):
333
raise RevfileError("invalid index %r" % idx)
334
self.idxfile.seek((idx + 1) * _RECORDSIZE)
337
def _read_next_index(self):
338
rec = self.idxfile.read(_RECORDSIZE)
340
raise IndexError("end of index file")
341
elif len(rec) != _RECORDSIZE:
342
raise RevfileError("short read of %d bytes getting index %d from %r"
343
% (len(rec), idx, self.basename))
345
return struct.unpack(">20sIIII12x", rec)
348
def dump(self, f=sys.stdout):
349
f.write('%-8s %-40s %-8s %-8s %-8s %-8s\n'
350
% tuple('idx sha1 base flags offset len'.split()))
351
f.write('-------- ---------------------------------------- ')
352
f.write('-------- -------- -------- --------\n')
354
for i, rec in enumerate(self):
355
f.write("#%-7d %40s " % (i, hexlify(rec[0])))
356
if rec[1] == _NO_RECORD:
359
f.write("#%-7d " % rec[1])
361
f.write("%8x %8d %8d\n" % (rec[2], rec[3], rec[4]))
366
r = Revfile("testrev")
371
sys.stderr.write("usage: revfile dump\n"
373
" revfile add-delta BASE\n"
375
" revfile find-sha HEX\n")
380
new_idx = r.add(sys.stdin.read())
382
elif cmd == 'add-delta':
383
new_idx = r.add(sys.stdin.read(), int(argv[2]))
391
sys.stderr.write("usage: revfile get IDX\n")
394
if idx < 0 or idx >= len(r):
395
sys.stderr.write("invalid index %r\n" % idx)
398
sys.stdout.write(r.get(idx))
399
elif cmd == 'find-sha':
401
s = unhexlify(argv[2])
403
sys.stderr.write("usage: revfile find-sha HEX\n")
407
if idx == _NO_RECORD:
408
sys.stderr.write("no such record\n")
414
sys.stderr.write("unknown command %r\n" % cmd)
418
if __name__ == '__main__':
420
sys.exit(main(sys.argv) or 0)