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