/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
74
from binascii import hexlify
75
76
factor = 10
77
78
_RECORDSIZE = 48
79
80
_HEADER = "bzr revfile v1\n"
81
_HEADER = _HEADER + ('\xff' * (_RECORDSIZE - len(_HEADER)))
199 by mbp at sourcefrog
- use -1 for no_base in revfile
82
_NO_BASE = 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
198 by mbp at sourcefrog
- experimental compressed Revfile support
91
class RevfileError(Exception):
92
    pass
93
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
94
95
198 by mbp at sourcefrog
- experimental compressed Revfile support
96
class Revfile:
97
    def __init__(self, basename):
98
        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
99
        
100
        idxname = basename + '.irev'
101
        dataname = basename + '.drev'
102
103
        idx_exists = os.path.exists(idxname)
104
        data_exists = os.path.exists(dataname)
105
106
        if idx_exists != data_exists:
107
            raise RevfileError("half-assed revfile")
108
        
109
        if not idx_exists:
110
            self.idxfile = open(idxname, 'w+b')
111
            self.datafile = open(dataname, 'w+b')
112
            
198 by mbp at sourcefrog
- experimental compressed Revfile support
113
            print 'init empty file'
114
            self.idxfile.write(_HEADER)
115
            self.idxfile.flush()
116
        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
117
            self.idxfile = open(idxname, 'r+b')
118
            self.dataname = open(dataname, 'r+b')
119
            
198 by mbp at sourcefrog
- experimental compressed Revfile support
120
            h = self.idxfile.read(_RECORDSIZE)
121
            if h != _HEADER:
122
                raise RevfileError("bad header %r in index of %r"
123
                                   % (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
124
125
198 by mbp at sourcefrog
- experimental compressed Revfile support
126
    def last_idx(self):
127
        """Return last index already present, or -1 if none."""
128
        l = os.fstat(self.idxfile.fileno())[stat.ST_SIZE]
129
        if l == 0:
130
            return -1
131
        if l % _RECORDSIZE:
132
            raise RevfileError("bad length %d on index of %r" % (l, self.basename))
133
        return (l / _RECORDSIZE) - 1
134
135
136
    def revision(self, rev):
137
        base = self.index[rev][0]
138
        start = self.index[base][1]
139
        end = self.index[rev][1] + self.index[rev][2]
140
        f = open(self.datafile())
141
142
        f.seek(start)
143
        data = f.read(end - start)
144
145
        last = self.index[base][2]
146
        text = zlib.decompress(data[:last])
147
148
        for r in range(base + 1, rev + 1):
149
            s = self.index[r][2]
150
            b = zlib.decompress(data[last:last + s])
151
            text = mdiff.bpatch(text, b)
152
            last = last + s
153
154
        return text    
155
156
157
    def add_full_text(self, t):
158
        """Add a full text to the file.
159
160
        This is not compressed against any reference version.
161
162
        Returns the index for that text."""
163
        idx = self.last_idx() + 1
164
        self.datafile.seek(0, 2)        # to end
165
        self.idxfile.seek(0, 2)
166
        assert self.idxfile.tell() == _RECORDSIZE * idx
167
        data_offset = self.datafile.tell()
168
169
        assert isinstance(t, str) # not unicode or anything wierd
170
171
        self.datafile.write(t)
172
        self.datafile.flush()
173
174
        entry = sha.new(t).digest()
199 by mbp at sourcefrog
- use -1 for no_base in revfile
175
        entry += struct.pack(">IIII12x", 0xFFFFFFFFL, 0, data_offset, len(t))
198 by mbp at sourcefrog
- experimental compressed Revfile support
176
        assert len(entry) == _RECORDSIZE
177
178
        self.idxfile.write(entry)
179
        self.idxfile.flush()
180
181
        return idx
182
183
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
184
    def _get_full_text(self, idx):
185
        idxrec = self[idx]
186
        assert idxrec[I_FLAGS] == 0
187
        assert idxrec[I_BASE] == _NO_BASE
188
189
        l = idxrec[I_LEN]
190
        if l == 0:
191
            return ''
192
193
        self.datafile.seek(idxrec[I_OFFSET])
194
195
        text = self.datafile.read(l)
196
        if len(text) != l:
197
            raise RevfileError("short read %d of %d "
198
                               "getting text for record %d in %r"
199
                               % (len(text), l, idx, self.basename))
200
        
201
        return text
202
203
198 by mbp at sourcefrog
- experimental compressed Revfile support
204
    def __len__(self):
205
        return int(self.last_idx())
206
200 by mbp at sourcefrog
revfile: fix up __getitem__ to allow simple iteration
207
198 by mbp at sourcefrog
- experimental compressed Revfile support
208
    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
209
        """Index by sequence id returns the index field"""
210
        self._seek_index(idx)
211
        return self._read_next_index()
212
213
214
    def _seek_index(self, idx):
198 by mbp at sourcefrog
- experimental compressed Revfile support
215
        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
216
        
217
218
    def _read_next_index(self):
198 by mbp at sourcefrog
- experimental compressed Revfile support
219
        rec = self.idxfile.read(_RECORDSIZE)
200 by mbp at sourcefrog
revfile: fix up __getitem__ to allow simple iteration
220
        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
221
            raise IndexError("end of index file")
200 by mbp at sourcefrog
revfile: fix up __getitem__ to allow simple iteration
222
        elif len(rec) != _RECORDSIZE:
198 by mbp at sourcefrog
- experimental compressed Revfile support
223
            raise RevfileError("short read of %d bytes getting index %d from %r"
224
                               % (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
225
        
199 by mbp at sourcefrog
- use -1 for no_base in revfile
226
        return struct.unpack(">20sIIII12x", rec)
198 by mbp at sourcefrog
- experimental compressed Revfile support
227
228
        
229
        
230
    def addrevision(self, text, changeset):
231
        t = self.tip()
232
        n = t + 1
233
234
        if not n % factor:
235
            data = zlib.compress(text)
236
            base = n
237
        else:
238
            prev = self.revision(t)
239
            data = zlib.compress(mdiff.bdiff(prev, text))
240
            base = self.index[t][0]
241
242
        offset = 0
243
        if t >= 0:
244
            offset = self.index[t][1] + self.index[t][2]
245
246
        self.index.append((base, offset, len(data), changeset))
247
        entry = struct.pack(">llll", base, offset, len(data), changeset)
248
249
        open(self.indexfile(), "a").write(entry)
250
        open(self.datafile(), "a").write(data)
251
199 by mbp at sourcefrog
- use -1 for no_base in revfile
252
    def dump(self, f=sys.stdout):
253
        f.write('%-8s %-40s %-8s %-8s %-8s %-8s\n' 
254
                % tuple('idx sha1 base flags offset len'.split()))
255
        f.write('-------- ---------------------------------------- ')
256
        f.write('-------- -------- -------- --------\n')
257
200 by mbp at sourcefrog
revfile: fix up __getitem__ to allow simple iteration
258
        for i, rec in enumerate(self):
199 by mbp at sourcefrog
- use -1 for no_base in revfile
259
            f.write("#%-7d %40s " % (i, hexlify(rec[0])))
260
            if rec[1] == _NO_BASE:
261
                f.write("(none)   ")
262
            else:
263
                f.write("#%-7d " % rec[1])
264
                
265
            f.write("%8x %8d %8d\n" % (rec[2], rec[3], rec[4]))
198 by mbp at sourcefrog
- experimental compressed Revfile support
266
        
267
268
269
def main(argv):
270
    r = Revfile("testrev")
271
    if len(argv) < 2:
272
        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
273
                         "       revfile add\n"
274
                         "       revfile get IDX\n")
198 by mbp at sourcefrog
- experimental compressed Revfile support
275
        sys.exit(1)
276
        
277
    if argv[1] == 'add':
278
        new_idx = r.add_full_text(sys.stdin.read())
279
        print 'added idx %d' % new_idx
280
    elif argv[1] == 'dump':
281
        r.dump()
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
    elif argv[1] == 'get':
283
        sys.stdout.write(r._get_full_text(int(argv[2])))
198 by mbp at sourcefrog
- experimental compressed Revfile support
284
    else:
285
        sys.stderr.write("unknown command %r\n" % argv[1])
286
        sys.exit(1)
287
    
288
289
if __name__ == '__main__':
290
    import sys
291
    main(sys.argv)