/brz/remove-bazaar

To get this branch, use:
bzr branch http://gegoxaren.bato24.eu/bzr/brz/remove-bazaar
198 by mbp at sourcefrog
- experimental compressed Revfile support
1
#! /usr/bin/env python
2
200 by mbp at sourcefrog
revfile: fix up __getitem__ to allow simple iteration
3
# (C) 2005 Canonical Ltd
198 by mbp at sourcefrog
- experimental compressed Revfile support
4
200 by mbp at sourcefrog
revfile: fix up __getitem__ to allow simple iteration
5
# based on an idea by Matt Mackall
198 by mbp at sourcefrog
- experimental compressed Revfile support
6
# modified to squish into bzr by Martin Pool
7
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.
12
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.
17
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
21
22
23
"""Packed file revision storage.
24
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.
28
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.
33
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.
36
37
The index file has a short header and then a sequence of fixed-length
38
records:
39
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
45
* uint32[3]   reserved
46
47
total 48 bytes.
48
199 by mbp at sourcefrog
- use -1 for no_base in revfile
49
The header is also 48 bytes for tidyness and easy calculation.
198 by mbp at sourcefrog
- experimental compressed Revfile support
50
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
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
58
sequentially.
59
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.
64
"""
65
 
66
201 by mbp at sourcefrog
Revfile: - get full text from a record- fix creation of files if they don't exist- protect against half-assed storage
67
# TODO: Something like pread() would make this slightly simpler and
68
# perhaps more efficient.
69
70
# TODO: Could also try to mmap things...
71
198 by mbp at sourcefrog
- experimental compressed Revfile support
72
73
import sys, zlib, struct, mdiff, stat, os, sha
204 by mbp at sourcefrog
Revfile:- new find-sha command and implementation- new _check_index helper
74
from binascii import hexlify, unhexlify
198 by mbp at sourcefrog
- experimental compressed Revfile support
75
76
factor = 10
77
78
_RECORDSIZE = 48
79
80
_HEADER = "bzr revfile v1\n"
81
_HEADER = _HEADER + ('\xff' * (_RECORDSIZE - len(_HEADER)))
204 by mbp at sourcefrog
Revfile:- new find-sha command and implementation- new _check_index helper
82
_NO_RECORD = 0xFFFFFFFFL
198 by mbp at sourcefrog
- experimental compressed Revfile support
83
201 by mbp at sourcefrog
Revfile: - get full text from a record- fix creation of files if they don't exist- protect against half-assed storage
84
# fields in the index record
85
I_SHA = 0
86
I_BASE = 1
87
I_FLAGS = 2
88
I_OFFSET = 3
89
I_LEN = 4
90
207 by mbp at sourcefrog
Revfile: compress data going into datafile if that would be worthwhile
91
FL_GZIP = 1
92
205 by mbp at sourcefrog
Revfile:- store and retrieve deltas!mdiff:- work on bytes not lines
93
198 by mbp at sourcefrog
- experimental compressed Revfile support
94
class RevfileError(Exception):
95
    pass
96
201 by mbp at sourcefrog
Revfile: - get full text from a record- fix creation of files if they don't exist- protect against half-assed storage
97
98
198 by mbp at sourcefrog
- experimental compressed Revfile support
99
class Revfile:
100
    def __init__(self, basename):
202 by mbp at sourcefrog
Revfile:
101
        # TODO: Option to open readonly
102
103
        # TODO: Lock file  while open
104
105
        # TODO: advise of random access
106
198 by mbp at sourcefrog
- experimental compressed Revfile support
107
        self.basename = basename
201 by mbp at sourcefrog
Revfile: - get full text from a record- fix creation of files if they don't exist- protect against half-assed storage
108
        
109
        idxname = basename + '.irev'
110
        dataname = basename + '.drev'
111
112
        idx_exists = os.path.exists(idxname)
113
        data_exists = os.path.exists(dataname)
114
115
        if idx_exists != data_exists:
116
            raise RevfileError("half-assed revfile")
117
        
118
        if not idx_exists:
119
            self.idxfile = open(idxname, 'w+b')
120
            self.datafile = open(dataname, 'w+b')
121
            
198 by mbp at sourcefrog
- experimental compressed Revfile support
122
            print 'init empty file'
123
            self.idxfile.write(_HEADER)
124
            self.idxfile.flush()
125
        else:
201 by mbp at sourcefrog
Revfile: - get full text from a record- fix creation of files if they don't exist- protect against half-assed storage
126
            self.idxfile = open(idxname, 'r+b')
202 by mbp at sourcefrog
Revfile:
127
            self.datafile = open(dataname, 'r+b')
201 by mbp at sourcefrog
Revfile: - get full text from a record- fix creation of files if they don't exist- protect against half-assed storage
128
            
198 by mbp at sourcefrog
- experimental compressed Revfile support
129
            h = self.idxfile.read(_RECORDSIZE)
130
            if h != _HEADER:
131
                raise RevfileError("bad header %r in index of %r"
132
                                   % (h, self.basename))
201 by mbp at sourcefrog
Revfile: - get full text from a record- fix creation of files if they don't exist- protect against half-assed storage
133
134
205 by mbp at sourcefrog
Revfile:- store and retrieve deltas!mdiff:- work on bytes not lines
135
    def _check_index(self, idx):
136
        if idx < 0 or idx > len(self):
137
            raise RevfileError("invalid index %r" % idx)
138
139
140
    def find_sha(self, s):
141
        assert isinstance(s, str)
142
        assert len(s) == 20
143
        
144
        for idx, idxrec in enumerate(self):
145
            if idxrec[I_SHA] == s:
146
                return idx
147
        else:
148
            return _NO_RECORD        
149
150
207 by mbp at sourcefrog
Revfile: compress data going into datafile if that would be worthwhile
151
    def _add_common(self, text_sha, data, base):
152
        """Add pre-processed data, can be either full text or delta.
153
154
        This does the compression if that makes sense."""
155
156
        flags = 0
208 by mbp at sourcefrog
show compression ratio
157
        data_len = len(data)
158
        if data_len > 50:
207 by mbp at sourcefrog
Revfile: compress data going into datafile if that would be worthwhile
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)
208 by mbp at sourcefrog
show compression ratio
162
            compr_len = len(compr_data)
163
            if compr_len < data_len:
207 by mbp at sourcefrog
Revfile: compress data going into datafile if that would be worthwhile
164
                data = compr_data
165
                flags = FL_GZIP
208 by mbp at sourcefrog
show compression ratio
166
                print '- compressed %d -> %d, %.1f%%' \
167
                      % (data_len, compr_len, float(compr_len)/float(data_len) * 100.0)
207 by mbp at sourcefrog
Revfile: compress data going into datafile if that would be worthwhile
168
        
203 by mbp at sourcefrog
revfile:
169
        idx = len(self)
198 by mbp at sourcefrog
- experimental compressed Revfile support
170
        self.datafile.seek(0, 2)        # to end
171
        self.idxfile.seek(0, 2)
202 by mbp at sourcefrog
Revfile:
172
        assert self.idxfile.tell() == _RECORDSIZE * (idx + 1)
198 by mbp at sourcefrog
- experimental compressed Revfile support
173
        data_offset = self.datafile.tell()
174
205 by mbp at sourcefrog
Revfile:- store and retrieve deltas!mdiff:- work on bytes not lines
175
        assert isinstance(data, str) # not unicode or anything wierd
198 by mbp at sourcefrog
- experimental compressed Revfile support
176
205 by mbp at sourcefrog
Revfile:- store and retrieve deltas!mdiff:- work on bytes not lines
177
        self.datafile.write(data)
198 by mbp at sourcefrog
- experimental compressed Revfile support
178
        self.datafile.flush()
179
205 by mbp at sourcefrog
Revfile:- store and retrieve deltas!mdiff:- work on bytes not lines
180
        assert isinstance(text_sha, str)
181
        entry = text_sha
182
        entry += struct.pack(">IIII12x", base, flags, data_offset, len(data))
198 by mbp at sourcefrog
- experimental compressed Revfile support
183
        assert len(entry) == _RECORDSIZE
184
185
        self.idxfile.write(entry)
186
        self.idxfile.flush()
187
188
        return idx
204 by mbp at sourcefrog
Revfile:- new find-sha command and implementation- new _check_index helper
189
        
205 by mbp at sourcefrog
Revfile:- store and retrieve deltas!mdiff:- work on bytes not lines
190
191
206 by mbp at sourcefrog
new Revfile.add() dwim
192
    def _add_full_text(self, text, text_sha):
205 by mbp at sourcefrog
Revfile:- store and retrieve deltas!mdiff:- work on bytes not lines
193
        """Add a full text to the file.
194
195
        This is not compressed against any reference version.
196
197
        Returns the index for that text."""
207 by mbp at sourcefrog
Revfile: compress data going into datafile if that would be worthwhile
198
        return self._add_common(text_sha, text, _NO_RECORD)
206 by mbp at sourcefrog
new Revfile.add() dwim
199
200
201
    def _add_delta(self, text, text_sha, base):
204 by mbp at sourcefrog
Revfile:- new find-sha command and implementation- new _check_index helper
202
        """Add a text stored relative to a previous text."""
203
        self._check_index(base)
205 by mbp at sourcefrog
Revfile:- store and retrieve deltas!mdiff:- work on bytes not lines
204
        base_text = self.get(base)
205
        data = mdiff.bdiff(base_text, text)
213 by mbp at sourcefrog
Revfile: don't store deltas if they'd be larger than just storing the whole text
206
        
207
        # If the delta is larger than the text, we might as well just
208
        # store the text.  (OK, the delta might be more compressible,
209
        # but the overhead of applying it probably still makes it
214 by mbp at sourcefrog
doc
210
        # bad, and I don't want to compress both of them to find out.)
213 by mbp at sourcefrog
Revfile: don't store deltas if they'd be larger than just storing the whole text
211
        if len(data) >= len(text):
212
            return self._add_full_text(text, text_sha)
213
        else:
214
            return self._add_common(text_sha, data, base)
205 by mbp at sourcefrog
Revfile:- store and retrieve deltas!mdiff:- work on bytes not lines
215
216
206 by mbp at sourcefrog
new Revfile.add() dwim
217
    def add(self, text, base=_NO_RECORD):
215 by mbp at sourcefrog
Doc
218
        """Add a new text to the revfile.
219
220
        If the text is already present them its existing id is
221
        returned and the file is not changed.
222
223
        If a base index is specified, that text *may* be used for
224
        delta compression of the new text.  Delta compression will
225
        only be used if it would be a size win and if the existing
226
        base is not at too long of a delta chain already.
227
        """
228
        
206 by mbp at sourcefrog
new Revfile.add() dwim
229
        text_sha = sha.new(text).digest()
204 by mbp at sourcefrog
Revfile:- new find-sha command and implementation- new _check_index helper
230
206 by mbp at sourcefrog
new Revfile.add() dwim
231
        idx = self.find_sha(text_sha)
232
        if idx != _NO_RECORD:
215 by mbp at sourcefrog
Doc
233
            # TODO: Optional paranoid mode where we read out that record and make sure
234
            # it's the same, in case someone ever breaks SHA-1.
206 by mbp at sourcefrog
new Revfile.add() dwim
235
            return idx                  # already present
204 by mbp at sourcefrog
Revfile:- new find-sha command and implementation- new _check_index helper
236
        
206 by mbp at sourcefrog
new Revfile.add() dwim
237
        if base == _NO_RECORD:
238
            return self._add_full_text(text, text_sha)
239
        else:
207 by mbp at sourcefrog
Revfile: compress data going into datafile if that would be worthwhile
240
            return self._add_delta(text, text_sha, base)
206 by mbp at sourcefrog
new Revfile.add() dwim
241
242
243
205 by mbp at sourcefrog
Revfile:- store and retrieve deltas!mdiff:- work on bytes not lines
244
    def get(self, idx):
201 by mbp at sourcefrog
Revfile: - get full text from a record- fix creation of files if they don't exist- protect against half-assed storage
245
        idxrec = self[idx]
205 by mbp at sourcefrog
Revfile:- store and retrieve deltas!mdiff:- work on bytes not lines
246
        base = idxrec[I_BASE]
247
        if base == _NO_RECORD:
248
            text = self._get_full_text(idx, idxrec)
249
        else:
250
            text = self._get_patched(idx, idxrec)
251
252
        if sha.new(text).digest() != idxrec[I_SHA]:
253
            raise RevfileError("corrupt SHA-1 digest on record %d"
254
                               % idx)
255
256
        return text
257
258
259
260
    def _get_raw(self, idx, idxrec):
209 by mbp at sourcefrog
Revfile: handle decompression
261
        flags = idxrec[I_FLAGS]
262
        if flags & ~FL_GZIP:
263
            raise RevfileError("unsupported index flags %#x on index %d"
264
                               % (flags, idx))
265
        
201 by mbp at sourcefrog
Revfile: - get full text from a record- fix creation of files if they don't exist- protect against half-assed storage
266
        l = idxrec[I_LEN]
267
        if l == 0:
268
            return ''
269
270
        self.datafile.seek(idxrec[I_OFFSET])
271
205 by mbp at sourcefrog
Revfile:- store and retrieve deltas!mdiff:- work on bytes not lines
272
        data = self.datafile.read(l)
273
        if len(data) != l:
201 by mbp at sourcefrog
Revfile: - get full text from a record- fix creation of files if they don't exist- protect against half-assed storage
274
            raise RevfileError("short read %d of %d "
275
                               "getting text for record %d in %r"
205 by mbp at sourcefrog
Revfile:- store and retrieve deltas!mdiff:- work on bytes not lines
276
                               % (len(data), l, idx, self.basename))
204 by mbp at sourcefrog
Revfile:- new find-sha command and implementation- new _check_index helper
277
209 by mbp at sourcefrog
Revfile: handle decompression
278
        if flags & FL_GZIP:
279
            data = zlib.decompress(data)
280
205 by mbp at sourcefrog
Revfile:- store and retrieve deltas!mdiff:- work on bytes not lines
281
        return data
201 by mbp at sourcefrog
Revfile: - get full text from a record- fix creation of files if they don't exist- protect against half-assed storage
282
        
205 by mbp at sourcefrog
Revfile:- store and retrieve deltas!mdiff:- work on bytes not lines
283
284
    def _get_full_text(self, idx, idxrec):
285
        assert idxrec[I_BASE] == _NO_RECORD
286
287
        text = self._get_raw(idx, idxrec)
288
289
        return text
290
291
292
    def _get_patched(self, idx, idxrec):
293
        base = idxrec[I_BASE]
294
        assert base >= 0
295
        assert base < idx    # no loops!
296
297
        base_text = self.get(base)
298
        patch = self._get_raw(idx, idxrec)
299
300
        text = mdiff.bpatch(base_text, patch)
301
302
        return text
303
201 by mbp at sourcefrog
Revfile: - get full text from a record- fix creation of files if they don't exist- protect against half-assed storage
304
305
198 by mbp at sourcefrog
- experimental compressed Revfile support
306
    def __len__(self):
203 by mbp at sourcefrog
revfile:
307
        """Return number of revisions."""
308
        l = os.fstat(self.idxfile.fileno())[stat.ST_SIZE]
309
        if l % _RECORDSIZE:
310
            raise RevfileError("bad length %d on index of %r" % (l, self.basename))
311
        if l < _RECORDSIZE:
312
            raise RevfileError("no header present in index of %r" % (self.basename))
313
        return int(l / _RECORDSIZE) - 1
198 by mbp at sourcefrog
- experimental compressed Revfile support
314
200 by mbp at sourcefrog
revfile: fix up __getitem__ to allow simple iteration
315
198 by mbp at sourcefrog
- experimental compressed Revfile support
316
    def __getitem__(self, idx):
201 by mbp at sourcefrog
Revfile: - get full text from a record- fix creation of files if they don't exist- protect against half-assed storage
317
        """Index by sequence id returns the index field"""
204 by mbp at sourcefrog
Revfile:- new find-sha command and implementation- new _check_index helper
318
        ## TODO: Can avoid seek if we just moved there...
201 by mbp at sourcefrog
Revfile: - get full text from a record- fix creation of files if they don't exist- protect against half-assed storage
319
        self._seek_index(idx)
320
        return self._read_next_index()
321
322
323
    def _seek_index(self, idx):
205 by mbp at sourcefrog
Revfile:- store and retrieve deltas!mdiff:- work on bytes not lines
324
        if idx < 0:
325
            raise RevfileError("invalid index %r" % idx)
198 by mbp at sourcefrog
- experimental compressed Revfile support
326
        self.idxfile.seek((idx + 1) * _RECORDSIZE)
201 by mbp at sourcefrog
Revfile: - get full text from a record- fix creation of files if they don't exist- protect against half-assed storage
327
        
328
329
    def _read_next_index(self):
198 by mbp at sourcefrog
- experimental compressed Revfile support
330
        rec = self.idxfile.read(_RECORDSIZE)
200 by mbp at sourcefrog
revfile: fix up __getitem__ to allow simple iteration
331
        if not rec:
201 by mbp at sourcefrog
Revfile: - get full text from a record- fix creation of files if they don't exist- protect against half-assed storage
332
            raise IndexError("end of index file")
200 by mbp at sourcefrog
revfile: fix up __getitem__ to allow simple iteration
333
        elif len(rec) != _RECORDSIZE:
198 by mbp at sourcefrog
- experimental compressed Revfile support
334
            raise RevfileError("short read of %d bytes getting index %d from %r"
335
                               % (len(rec), idx, self.basename))
201 by mbp at sourcefrog
Revfile: - get full text from a record- fix creation of files if they don't exist- protect against half-assed storage
336
        
199 by mbp at sourcefrog
- use -1 for no_base in revfile
337
        return struct.unpack(">20sIIII12x", rec)
198 by mbp at sourcefrog
- experimental compressed Revfile support
338
339
        
199 by mbp at sourcefrog
- use -1 for no_base in revfile
340
    def dump(self, f=sys.stdout):
341
        f.write('%-8s %-40s %-8s %-8s %-8s %-8s\n' 
342
                % tuple('idx sha1 base flags offset len'.split()))
343
        f.write('-------- ---------------------------------------- ')
344
        f.write('-------- -------- -------- --------\n')
345
200 by mbp at sourcefrog
revfile: fix up __getitem__ to allow simple iteration
346
        for i, rec in enumerate(self):
199 by mbp at sourcefrog
- use -1 for no_base in revfile
347
            f.write("#%-7d %40s " % (i, hexlify(rec[0])))
204 by mbp at sourcefrog
Revfile:- new find-sha command and implementation- new _check_index helper
348
            if rec[1] == _NO_RECORD:
199 by mbp at sourcefrog
- use -1 for no_base in revfile
349
                f.write("(none)   ")
350
            else:
351
                f.write("#%-7d " % rec[1])
352
                
353
            f.write("%8x %8d %8d\n" % (rec[2], rec[3], rec[4]))
198 by mbp at sourcefrog
- experimental compressed Revfile support
354
        
355
356
357
def main(argv):
358
    r = Revfile("testrev")
203 by mbp at sourcefrog
revfile:
359
360
    try:
361
        cmd = argv[1]
362
    except IndexError:
198 by mbp at sourcefrog
- experimental compressed Revfile support
363
        sys.stderr.write("usage: revfile dump\n"
201 by mbp at sourcefrog
Revfile: - get full text from a record- fix creation of files if they don't exist- protect against half-assed storage
364
                         "       revfile add\n"
205 by mbp at sourcefrog
Revfile:- store and retrieve deltas!mdiff:- work on bytes not lines
365
                         "       revfile add-delta BASE\n"
204 by mbp at sourcefrog
Revfile:- new find-sha command and implementation- new _check_index helper
366
                         "       revfile get IDX\n"
367
                         "       revfile find-sha HEX\n")
203 by mbp at sourcefrog
revfile:
368
        return 1
198 by mbp at sourcefrog
- experimental compressed Revfile support
369
        
203 by mbp at sourcefrog
revfile:
370
371
    if cmd == 'add':
206 by mbp at sourcefrog
new Revfile.add() dwim
372
        new_idx = r.add(sys.stdin.read())
198 by mbp at sourcefrog
- experimental compressed Revfile support
373
        print 'added idx %d' % new_idx
205 by mbp at sourcefrog
Revfile:- store and retrieve deltas!mdiff:- work on bytes not lines
374
    elif cmd == 'add-delta':
207 by mbp at sourcefrog
Revfile: compress data going into datafile if that would be worthwhile
375
        new_idx = r.add(sys.stdin.read(), int(argv[2]))
205 by mbp at sourcefrog
Revfile:- store and retrieve deltas!mdiff:- work on bytes not lines
376
        print 'added idx %d' % new_idx
203 by mbp at sourcefrog
revfile:
377
    elif cmd == 'dump':
198 by mbp at sourcefrog
- experimental compressed Revfile support
378
        r.dump()
203 by mbp at sourcefrog
revfile:
379
    elif cmd == 'get':
202 by mbp at sourcefrog
Revfile:
380
        try:
203 by mbp at sourcefrog
revfile:
381
            idx = int(argv[2])
202 by mbp at sourcefrog
Revfile:
382
        except IndexError:
203 by mbp at sourcefrog
revfile:
383
            sys.stderr.write("usage: revfile get IDX\n")
384
            return 1
385
386
        if idx < 0 or idx >= len(r):
387
            sys.stderr.write("invalid index %r\n" % idx)
388
            return 1
389
205 by mbp at sourcefrog
Revfile:- store and retrieve deltas!mdiff:- work on bytes not lines
390
        sys.stdout.write(r.get(idx))
204 by mbp at sourcefrog
Revfile:- new find-sha command and implementation- new _check_index helper
391
    elif cmd == 'find-sha':
392
        try:
393
            s = unhexlify(argv[2])
394
        except IndexError:
395
            sys.stderr.write("usage: revfile find-sha HEX\n")
396
            return 1
397
398
        idx = r.find_sha(s)
399
        if idx == _NO_RECORD:
400
            sys.stderr.write("no such record\n")
401
            return 1
402
        else:
403
            print idx
404
            
198 by mbp at sourcefrog
- experimental compressed Revfile support
405
    else:
203 by mbp at sourcefrog
revfile:
406
        sys.stderr.write("unknown command %r\n" % cmd)
407
        return 1
198 by mbp at sourcefrog
- experimental compressed Revfile support
408
    
409
410
if __name__ == '__main__':
411
    import sys
203 by mbp at sourcefrog
revfile:
412
    sys.exit(main(sys.argv) or 0)