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.
 
 
55
The iter method here will generally read through the whole index file
 
 
56
in one go.  With readahead in the kernel and python/libc (typically
 
 
57
128kB) this means that there should be no seeks and often only one
 
 
58
read() call to get everything into memory.
 
 
62
# TODO: Something like pread() would make this slightly simpler and
 
 
63
# perhaps more efficient.
 
 
65
# TODO: Could also try to mmap things...  Might be faster for the
 
 
66
# index in particular?
 
 
68
# TODO: Some kind of faster lookup of SHAs?  The bad thing is that probably means
 
 
69
# rewriting existing records, which is not so nice.
 
 
71
# TODO: Something to check that regions identified in the index file
 
 
72
# completely butt up and do not overlap.  Strictly it's not a problem
 
 
73
# if there are gaps and that can happen if we're interrupted while
 
 
74
# writing to the datafile.  Overlapping would be very bad though.
 
 
78
import sys, zlib, struct, mdiff, stat, os, sha
 
 
79
from binascii import hexlify, unhexlify
 
 
85
_HEADER = "bzr revfile v1\n"
 
 
86
_HEADER = _HEADER + ('\xff' * (_RECORDSIZE - len(_HEADER)))
 
 
87
_NO_RECORD = 0xFFFFFFFFL
 
 
89
# fields in the index record
 
 
98
# maximum number of patches in a row before recording a whole text.
 
 
102
class RevfileError(Exception):
 
 
105
class LimitHitException(Exception):
 
 
109
    def __init__(self, basename, mode):
 
 
110
        # TODO: Lock file  while open
 
 
112
        # TODO: advise of random access
 
 
114
        self.basename = basename
 
 
116
        if mode not in ['r', 'w']:
 
 
117
            raise RevfileError("invalid open mode %r" % mode)
 
 
120
        idxname = basename + '.irev'
 
 
121
        dataname = basename + '.drev'
 
 
123
        idx_exists = os.path.exists(idxname)
 
 
124
        data_exists = os.path.exists(dataname)
 
 
126
        if idx_exists != data_exists:
 
 
127
            raise RevfileError("half-assed revfile")
 
 
131
                raise RevfileError("Revfile %r does not exist" % basename)
 
 
133
            self.idxfile = open(idxname, 'w+b')
 
 
134
            self.datafile = open(dataname, 'w+b')
 
 
136
            print 'init empty file'
 
 
137
            self.idxfile.write(_HEADER)
 
 
145
            self.idxfile = open(idxname, diskmode)
 
 
146
            self.datafile = open(dataname, diskmode)
 
 
148
            h = self.idxfile.read(_RECORDSIZE)
 
 
150
                raise RevfileError("bad header %r in index of %r"
 
 
151
                                   % (h, self.basename))
 
 
154
    def _check_index(self, idx):
 
 
155
        if idx < 0 or idx > len(self):
 
 
156
            raise RevfileError("invalid index %r" % idx)
 
 
158
    def _check_write(self):
 
 
160
            raise RevfileError("%r is open readonly" % self.basename)
 
 
163
    def find_sha(self, s):
 
 
164
        assert isinstance(s, str)
 
 
167
        for idx, idxrec in enumerate(self):
 
 
168
            if idxrec[I_SHA] == s:
 
 
175
    def _add_compressed(self, text_sha, data, base, compress):
 
 
176
        # well, maybe compress
 
 
181
                # don't do compression if it's too small; it's unlikely to win
 
 
182
                # enough to be worthwhile
 
 
183
                compr_data = zlib.compress(data)
 
 
184
                compr_len = len(compr_data)
 
 
185
                if compr_len < data_len:
 
 
188
                    ##print '- compressed %d -> %d, %.1f%%' \
 
 
189
                    ##      % (data_len, compr_len, float(compr_len)/float(data_len) * 100.0)
 
 
190
        return self._add_raw(text_sha, data, base, flags)
 
 
194
    def _add_raw(self, text_sha, data, base, flags):
 
 
195
        """Add pre-processed data, can be either full text or delta.
 
 
197
        This does the compression if that makes sense."""
 
 
199
        self.datafile.seek(0, 2)        # to end
 
 
200
        self.idxfile.seek(0, 2)
 
 
201
        assert self.idxfile.tell() == _RECORDSIZE * (idx + 1)
 
 
202
        data_offset = self.datafile.tell()
 
 
204
        assert isinstance(data, str) # not unicode or anything weird
 
 
206
        self.datafile.write(data)
 
 
207
        self.datafile.flush()
 
 
209
        assert isinstance(text_sha, str)
 
 
211
        entry += struct.pack(">IIII12x", base, flags, data_offset, len(data))
 
 
212
        assert len(entry) == _RECORDSIZE
 
 
214
        self.idxfile.write(entry)
 
 
221
    def _add_full_text(self, text, text_sha, compress):
 
 
222
        """Add a full text to the file.
 
 
224
        This is not compressed against any reference version.
 
 
226
        Returns the index for that text."""
 
 
227
        return self._add_compressed(text_sha, text, _NO_RECORD, compress)
 
 
230
    def _add_delta(self, text, text_sha, base, compress):
 
 
231
        """Add a text stored relative to a previous text."""
 
 
232
        self._check_index(base)
 
 
235
            base_text = self.get(base, recursion_limit=CHAIN_LIMIT)
 
 
236
        except LimitHitException:
 
 
237
            return self._add_full_text(text, text_sha, compress)
 
 
239
        data = mdiff.bdiff(base_text, text)
 
 
241
        # If the delta is larger than the text, we might as well just
 
 
242
        # store the text.  (OK, the delta might be more compressible,
 
 
243
        # but the overhead of applying it probably still makes it
 
 
244
        # bad, and I don't want to compress both of them to find out.)
 
 
245
        if len(data) >= len(text):
 
 
246
            return self._add_full_text(text, text_sha, compress)
 
 
248
            return self._add_compressed(text_sha, data, base, compress)
 
 
251
    def add(self, text, base=_NO_RECORD, compress=True):
 
 
252
        """Add a new text to the revfile.
 
 
254
        If the text is already present them its existing id is
 
 
255
        returned and the file is not changed.
 
 
257
        If compress is true then gzip compression will be used if it
 
 
260
        If a base index is specified, that text *may* be used for
 
 
261
        delta compression of the new text.  Delta compression will
 
 
262
        only be used if it would be a size win and if the existing
 
 
263
        base is not at too long of a delta chain already.
 
 
267
        text_sha = sha.new(text).digest()
 
 
269
        idx = self.find_sha(text_sha)
 
 
270
        if idx != _NO_RECORD:
 
 
271
            # TODO: Optional paranoid mode where we read out that record and make sure
 
 
272
            # it's the same, in case someone ever breaks SHA-1.
 
 
273
            return idx                  # already present
 
 
275
        if base == _NO_RECORD:
 
 
276
            return self._add_full_text(text, text_sha, compress)
 
 
278
            return self._add_delta(text, text_sha, base, compress)
 
 
282
    def get(self, idx, recursion_limit=None):
 
 
283
        """Retrieve text of a previous revision.
 
 
285
        If recursion_limit is an integer then walk back at most that
 
 
286
        many revisions and then raise LimitHitException, indicating
 
 
287
        that we ought to record a new file text instead of another
 
 
288
        delta.  Don't use this when trying to get out an existing
 
 
292
        base = idxrec[I_BASE]
 
 
293
        if base == _NO_RECORD:
 
 
294
            text = self._get_full_text(idx, idxrec)
 
 
296
            text = self._get_patched(idx, idxrec, recursion_limit)
 
 
298
        if sha.new(text).digest() != idxrec[I_SHA]:
 
 
299
            raise RevfileError("corrupt SHA-1 digest on record %d"
 
 
306
    def _get_raw(self, idx, idxrec):
 
 
307
        flags = idxrec[I_FLAGS]
 
 
309
            raise RevfileError("unsupported index flags %#x on index %d"
 
 
316
        self.datafile.seek(idxrec[I_OFFSET])
 
 
318
        data = self.datafile.read(l)
 
 
320
            raise RevfileError("short read %d of %d "
 
 
321
                               "getting text for record %d in %r"
 
 
322
                               % (len(data), l, idx, self.basename))
 
 
325
            data = zlib.decompress(data)
 
 
330
    def _get_full_text(self, idx, idxrec):
 
 
331
        assert idxrec[I_BASE] == _NO_RECORD
 
 
333
        text = self._get_raw(idx, idxrec)
 
 
338
    def _get_patched(self, idx, idxrec, recursion_limit):
 
 
339
        base = idxrec[I_BASE]
 
 
341
        assert base < idx    # no loops!
 
 
343
        if recursion_limit == None:
 
 
346
            sub_limit = recursion_limit - 1
 
 
348
                raise LimitHitException()
 
 
350
        base_text = self.get(base, sub_limit)
 
 
351
        patch = self._get_raw(idx, idxrec)
 
 
353
        text = mdiff.bpatch(base_text, patch)
 
 
360
        """Return number of revisions."""
 
 
361
        l = os.fstat(self.idxfile.fileno())[stat.ST_SIZE]
 
 
363
            raise RevfileError("bad length %d on index of %r" % (l, self.basename))
 
 
365
            raise RevfileError("no header present in index of %r" % (self.basename))
 
 
366
        return int(l / _RECORDSIZE) - 1
 
 
369
    def __getitem__(self, idx):
 
 
370
        """Index by sequence id returns the index field"""
 
 
371
        ## TODO: Can avoid seek if we just moved there...
 
 
372
        self._seek_index(idx)
 
 
373
        idxrec = self._read_next_index()
 
 
380
    def _seek_index(self, idx):
 
 
382
            raise RevfileError("invalid index %r" % idx)
 
 
383
        self.idxfile.seek((idx + 1) * _RECORDSIZE)
 
 
388
        """Read back all index records.
 
 
390
        Do not seek the index file while this is underway!"""
 
 
391
        sys.stderr.write(" ** iter called ** \n")
 
 
394
            idxrec = self._read_next_index()
 
 
400
    def _read_next_index(self):
 
 
401
        rec = self.idxfile.read(_RECORDSIZE)
 
 
404
        elif len(rec) != _RECORDSIZE:
 
 
405
            raise RevfileError("short read of %d bytes getting index %d from %r"
 
 
406
                               % (len(rec), idx, self.basename))
 
 
408
        return struct.unpack(">20sIIII12x", rec)
 
 
411
    def dump(self, f=sys.stdout):
 
 
412
        f.write('%-8s %-40s %-8s %-8s %-8s %-8s\n' 
 
 
413
                % tuple('idx sha1 base flags offset len'.split()))
 
 
414
        f.write('-------- ---------------------------------------- ')
 
 
415
        f.write('-------- -------- -------- --------\n')
 
 
417
        for i, rec in enumerate(self):
 
 
418
            f.write("#%-7d %40s " % (i, hexlify(rec[0])))
 
 
419
            if rec[1] == _NO_RECORD:
 
 
422
                f.write("#%-7d " % rec[1])
 
 
424
            f.write("%8x %8d %8d\n" % (rec[2], rec[3], rec[4]))
 
 
427
    def total_text_size(self):
 
 
428
        """Return the sum of sizes of all file texts.
 
 
430
        This is how much space they would occupy if they were stored without
 
 
431
        delta and gzip compression.
 
 
433
        As a side effect this completely validates the Revfile, checking that all
 
 
434
        texts can be reproduced with the correct SHA-1."""
 
 
436
        for idx in range(len(self)):
 
 
437
            t += len(self.get(idx))
 
 
446
        sys.stderr.write("usage: revfile dump\n"
 
 
448
                         "       revfile add-delta BASE\n"
 
 
450
                         "       revfile find-sha HEX\n"
 
 
451
                         "       revfile total-text-size\n"
 
 
456
        return Revfile('testrev', 'w')
 
 
459
        return Revfile('testrev', 'r')
 
 
462
        print rw().add(sys.stdin.read())
 
 
463
    elif cmd == 'add-delta':
 
 
464
        print rw().add(sys.stdin.read(), int(argv[2]))
 
 
471
            sys.stderr.write("usage: revfile get IDX\n")
 
 
474
        if idx < 0 or idx >= len(r):
 
 
475
            sys.stderr.write("invalid index %r\n" % idx)
 
 
478
        sys.stdout.write(ro().get(idx))
 
 
479
    elif cmd == 'find-sha':
 
 
481
            s = unhexlify(argv[2])
 
 
483
            sys.stderr.write("usage: revfile find-sha HEX\n")
 
 
486
        idx = ro().find_sha(s)
 
 
487
        if idx == _NO_RECORD:
 
 
488
            sys.stderr.write("no such record\n")
 
 
492
    elif cmd == 'total-text-size':
 
 
493
        print ro().total_text_size()
 
 
497
        sys.stderr.write("unknown command %r\n" % cmd)
 
 
501
if __name__ == '__main__':
 
 
503
    sys.exit(main(sys.argv) or 0)