~bzr-pqm/bzr/bzr.dev

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.
224 by mbp at sourcefrog
doc
64
65
This performs pretty well except when trying to calculate deltas of
66
really large files.  For that the main thing would be to plug in
67
something faster than difflib, which is after all pure Python.
68
Another approach is to just store the gzipped full text of big files,
69
though perhaps that's too perverse?
198 by mbp at sourcefrog
- experimental compressed Revfile support
70
"""
71
 
72
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
73
# TODO: Something like pread() would make this slightly simpler and
74
# perhaps more efficient.
75
219 by mbp at sourcefrog
todo
76
# TODO: Could also try to mmap things...  Might be faster for the
77
# index in particular?
78
79
# TODO: Some kind of faster lookup of SHAs?  The bad thing is that probably means
80
# rewriting existing records, which is not so nice.
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
81
224 by mbp at sourcefrog
doc
82
# TODO: Something to check that regions identified in the index file
83
# completely butt up and do not overlap.  Strictly it's not a problem
84
# if there are gaps and that can happen if we're interrupted while
85
# writing to the datafile.  Overlapping would be very bad though.
86
87
198 by mbp at sourcefrog
- experimental compressed Revfile support
88
89
import sys, zlib, struct, mdiff, stat, os, sha
204 by mbp at sourcefrog
Revfile:- new find-sha command and implementation- new _check_index helper
90
from binascii import hexlify, unhexlify
198 by mbp at sourcefrog
- experimental compressed Revfile support
91
92
factor = 10
93
94
_RECORDSIZE = 48
95
96
_HEADER = "bzr revfile v1\n"
97
_HEADER = _HEADER + ('\xff' * (_RECORDSIZE - len(_HEADER)))
204 by mbp at sourcefrog
Revfile:- new find-sha command and implementation- new _check_index helper
98
_NO_RECORD = 0xFFFFFFFFL
198 by mbp at sourcefrog
- experimental compressed Revfile support
99
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
100
# fields in the index record
101
I_SHA = 0
102
I_BASE = 1
103
I_FLAGS = 2
104
I_OFFSET = 3
105
I_LEN = 4
106
207 by mbp at sourcefrog
Revfile: compress data going into datafile if that would be worthwhile
107
FL_GZIP = 1
108
220 by mbp at sourcefrog
limit the number of chained patches
109
# maximum number of patches in a row before recording a whole text.
227 by mbp at sourcefrog
increase patch chaining limit
110
CHAIN_LIMIT = 50
220 by mbp at sourcefrog
limit the number of chained patches
111
205 by mbp at sourcefrog
Revfile:- store and retrieve deltas!mdiff:- work on bytes not lines
112
198 by mbp at sourcefrog
- experimental compressed Revfile support
113
class RevfileError(Exception):
114
    pass
115
220 by mbp at sourcefrog
limit the number of chained patches
116
class LimitHitException(Exception):
117
    pass
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
118
198 by mbp at sourcefrog
- experimental compressed Revfile support
119
class Revfile:
229 by mbp at sourcefrog
Allow opening revision file read-only
120
    def __init__(self, basename, mode):
202 by mbp at sourcefrog
Revfile:
121
        # TODO: Lock file  while open
122
123
        # TODO: advise of random access
124
198 by mbp at sourcefrog
- experimental compressed Revfile support
125
        self.basename = basename
229 by mbp at sourcefrog
Allow opening revision file read-only
126
127
        if mode not in ['r', 'w']:
128
            raise RevfileError("invalid open mode %r" % mode)
129
        self.mode = mode
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
        idxname = basename + '.irev'
132
        dataname = basename + '.drev'
133
134
        idx_exists = os.path.exists(idxname)
135
        data_exists = os.path.exists(dataname)
136
137
        if idx_exists != data_exists:
138
            raise RevfileError("half-assed revfile")
139
        
140
        if not idx_exists:
229 by mbp at sourcefrog
Allow opening revision file read-only
141
            if mode == 'r':
142
                raise RevfileError("Revfile %r does not exist" % basename)
143
            
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
144
            self.idxfile = open(idxname, 'w+b')
145
            self.datafile = open(dataname, 'w+b')
146
            
198 by mbp at sourcefrog
- experimental compressed Revfile support
147
            print 'init empty file'
148
            self.idxfile.write(_HEADER)
149
            self.idxfile.flush()
150
        else:
229 by mbp at sourcefrog
Allow opening revision file read-only
151
            if mode == 'r':
152
                diskmode = 'rb'
153
            else:
154
                diskmode = 'r+b'
155
                
156
            self.idxfile = open(idxname, diskmode)
157
            self.datafile = open(dataname, diskmode)
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
158
            
198 by mbp at sourcefrog
- experimental compressed Revfile support
159
            h = self.idxfile.read(_RECORDSIZE)
160
            if h != _HEADER:
161
                raise RevfileError("bad header %r in index of %r"
162
                                   % (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
163
164
205 by mbp at sourcefrog
Revfile:- store and retrieve deltas!mdiff:- work on bytes not lines
165
    def _check_index(self, idx):
166
        if idx < 0 or idx > len(self):
167
            raise RevfileError("invalid index %r" % idx)
168
229 by mbp at sourcefrog
Allow opening revision file read-only
169
    def _check_write(self):
170
        if self.mode != 'w':
171
            raise RevfileError("%r is open readonly" % self.basename)
172
205 by mbp at sourcefrog
Revfile:- store and retrieve deltas!mdiff:- work on bytes not lines
173
174
    def find_sha(self, s):
175
        assert isinstance(s, str)
176
        assert len(s) == 20
177
        
178
        for idx, idxrec in enumerate(self):
179
            if idxrec[I_SHA] == s:
180
                return idx
181
        else:
217 by mbp at sourcefrog
Revfile: make compression optional, in case people are storing files they know won't compress
182
            return _NO_RECORD
183
184
185
186
    def _add_compressed(self, text_sha, data, base, compress):
187
        # well, maybe compress
188
        flags = 0
189
        if compress:
190
            data_len = len(data)
191
            if data_len > 50:
192
                # don't do compression if it's too small; it's unlikely to win
193
                # enough to be worthwhile
194
                compr_data = zlib.compress(data)
195
                compr_len = len(compr_data)
196
                if compr_len < data_len:
197
                    data = compr_data
198
                    flags = FL_GZIP
199
                    ##print '- compressed %d -> %d, %.1f%%' \
200
                    ##      % (data_len, compr_len, float(compr_len)/float(data_len) * 100.0)
201
        return self._add_raw(text_sha, data, base, flags)
202
        
203
204
205
    def _add_raw(self, text_sha, data, base, flags):
207 by mbp at sourcefrog
Revfile: compress data going into datafile if that would be worthwhile
206
        """Add pre-processed data, can be either full text or delta.
207
208
        This does the compression if that makes sense."""
203 by mbp at sourcefrog
revfile:
209
        idx = len(self)
198 by mbp at sourcefrog
- experimental compressed Revfile support
210
        self.datafile.seek(0, 2)        # to end
211
        self.idxfile.seek(0, 2)
202 by mbp at sourcefrog
Revfile:
212
        assert self.idxfile.tell() == _RECORDSIZE * (idx + 1)
198 by mbp at sourcefrog
- experimental compressed Revfile support
213
        data_offset = self.datafile.tell()
214
205 by mbp at sourcefrog
Revfile:- store and retrieve deltas!mdiff:- work on bytes not lines
215
        assert isinstance(data, str) # not unicode or anything wierd
198 by mbp at sourcefrog
- experimental compressed Revfile support
216
205 by mbp at sourcefrog
Revfile:- store and retrieve deltas!mdiff:- work on bytes not lines
217
        self.datafile.write(data)
198 by mbp at sourcefrog
- experimental compressed Revfile support
218
        self.datafile.flush()
219
205 by mbp at sourcefrog
Revfile:- store and retrieve deltas!mdiff:- work on bytes not lines
220
        assert isinstance(text_sha, str)
221
        entry = text_sha
222
        entry += struct.pack(">IIII12x", base, flags, data_offset, len(data))
198 by mbp at sourcefrog
- experimental compressed Revfile support
223
        assert len(entry) == _RECORDSIZE
224
225
        self.idxfile.write(entry)
226
        self.idxfile.flush()
227
228
        return idx
204 by mbp at sourcefrog
Revfile:- new find-sha command and implementation- new _check_index helper
229
        
205 by mbp at sourcefrog
Revfile:- store and retrieve deltas!mdiff:- work on bytes not lines
230
231
220 by mbp at sourcefrog
limit the number of chained patches
232
    def _add_full_text(self, text, text_sha, compress):
205 by mbp at sourcefrog
Revfile:- store and retrieve deltas!mdiff:- work on bytes not lines
233
        """Add a full text to the file.
234
235
        This is not compressed against any reference version.
236
237
        Returns the index for that text."""
217 by mbp at sourcefrog
Revfile: make compression optional, in case people are storing files they know won't compress
238
        return self._add_compressed(text_sha, text, _NO_RECORD, compress)
239
240
241
    def _add_delta(self, text, text_sha, base, compress):
204 by mbp at sourcefrog
Revfile:- new find-sha command and implementation- new _check_index helper
242
        """Add a text stored relative to a previous text."""
243
        self._check_index(base)
220 by mbp at sourcefrog
limit the number of chained patches
244
        
245
        try:
246
            base_text = self.get(base, recursion_limit=CHAIN_LIMIT)
247
        except LimitHitException:
248
            return self._add_full_text(text, text_sha, compress)
249
        
205 by mbp at sourcefrog
Revfile:- store and retrieve deltas!mdiff:- work on bytes not lines
250
        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
251
        
252
        # If the delta is larger than the text, we might as well just
253
        # store the text.  (OK, the delta might be more compressible,
254
        # but the overhead of applying it probably still makes it
214 by mbp at sourcefrog
doc
255
        # 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
256
        if len(data) >= len(text):
217 by mbp at sourcefrog
Revfile: make compression optional, in case people are storing files they know won't compress
257
            return self._add_full_text(text, text_sha, compress)
213 by mbp at sourcefrog
Revfile: don't store deltas if they'd be larger than just storing the whole text
258
        else:
217 by mbp at sourcefrog
Revfile: make compression optional, in case people are storing files they know won't compress
259
            return self._add_compressed(text_sha, data, base, compress)
260
261
262
    def add(self, text, base=_NO_RECORD, compress=True):
215 by mbp at sourcefrog
Doc
263
        """Add a new text to the revfile.
264
265
        If the text is already present them its existing id is
266
        returned and the file is not changed.
267
217 by mbp at sourcefrog
Revfile: make compression optional, in case people are storing files they know won't compress
268
        If compress is true then gzip compression will be used if it
269
        reduces the size.
270
215 by mbp at sourcefrog
Doc
271
        If a base index is specified, that text *may* be used for
272
        delta compression of the new text.  Delta compression will
273
        only be used if it would be a size win and if the existing
274
        base is not at too long of a delta chain already.
275
        """
229 by mbp at sourcefrog
Allow opening revision file read-only
276
        self._check_write()
277
        
206 by mbp at sourcefrog
new Revfile.add() dwim
278
        text_sha = sha.new(text).digest()
204 by mbp at sourcefrog
Revfile:- new find-sha command and implementation- new _check_index helper
279
206 by mbp at sourcefrog
new Revfile.add() dwim
280
        idx = self.find_sha(text_sha)
281
        if idx != _NO_RECORD:
215 by mbp at sourcefrog
Doc
282
            # TODO: Optional paranoid mode where we read out that record and make sure
283
            # it's the same, in case someone ever breaks SHA-1.
206 by mbp at sourcefrog
new Revfile.add() dwim
284
            return idx                  # already present
204 by mbp at sourcefrog
Revfile:- new find-sha command and implementation- new _check_index helper
285
        
206 by mbp at sourcefrog
new Revfile.add() dwim
286
        if base == _NO_RECORD:
217 by mbp at sourcefrog
Revfile: make compression optional, in case people are storing files they know won't compress
287
            return self._add_full_text(text, text_sha, compress)
206 by mbp at sourcefrog
new Revfile.add() dwim
288
        else:
217 by mbp at sourcefrog
Revfile: make compression optional, in case people are storing files they know won't compress
289
            return self._add_delta(text, text_sha, base, compress)
206 by mbp at sourcefrog
new Revfile.add() dwim
290
291
292
220 by mbp at sourcefrog
limit the number of chained patches
293
    def get(self, idx, recursion_limit=None):
294
        """Retrieve text of a previous revision.
295
296
        If recursion_limit is an integer then walk back at most that
297
        many revisions and then raise LimitHitException, indicating
298
        that we ought to record a new file text instead of another
299
        delta.  Don't use this when trying to get out an existing
300
        revision."""
301
        
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
302
        idxrec = self[idx]
205 by mbp at sourcefrog
Revfile:- store and retrieve deltas!mdiff:- work on bytes not lines
303
        base = idxrec[I_BASE]
304
        if base == _NO_RECORD:
305
            text = self._get_full_text(idx, idxrec)
306
        else:
220 by mbp at sourcefrog
limit the number of chained patches
307
            text = self._get_patched(idx, idxrec, recursion_limit)
205 by mbp at sourcefrog
Revfile:- store and retrieve deltas!mdiff:- work on bytes not lines
308
309
        if sha.new(text).digest() != idxrec[I_SHA]:
310
            raise RevfileError("corrupt SHA-1 digest on record %d"
311
                               % idx)
312
313
        return text
314
315
316
317
    def _get_raw(self, idx, idxrec):
209 by mbp at sourcefrog
Revfile: handle decompression
318
        flags = idxrec[I_FLAGS]
319
        if flags & ~FL_GZIP:
320
            raise RevfileError("unsupported index flags %#x on index %d"
321
                               % (flags, idx))
322
        
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
323
        l = idxrec[I_LEN]
324
        if l == 0:
325
            return ''
326
327
        self.datafile.seek(idxrec[I_OFFSET])
328
205 by mbp at sourcefrog
Revfile:- store and retrieve deltas!mdiff:- work on bytes not lines
329
        data = self.datafile.read(l)
330
        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
331
            raise RevfileError("short read %d of %d "
332
                               "getting text for record %d in %r"
205 by mbp at sourcefrog
Revfile:- store and retrieve deltas!mdiff:- work on bytes not lines
333
                               % (len(data), l, idx, self.basename))
204 by mbp at sourcefrog
Revfile:- new find-sha command and implementation- new _check_index helper
334
209 by mbp at sourcefrog
Revfile: handle decompression
335
        if flags & FL_GZIP:
336
            data = zlib.decompress(data)
337
205 by mbp at sourcefrog
Revfile:- store and retrieve deltas!mdiff:- work on bytes not lines
338
        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
339
        
205 by mbp at sourcefrog
Revfile:- store and retrieve deltas!mdiff:- work on bytes not lines
340
341
    def _get_full_text(self, idx, idxrec):
342
        assert idxrec[I_BASE] == _NO_RECORD
343
344
        text = self._get_raw(idx, idxrec)
345
346
        return text
347
348
220 by mbp at sourcefrog
limit the number of chained patches
349
    def _get_patched(self, idx, idxrec, recursion_limit):
205 by mbp at sourcefrog
Revfile:- store and retrieve deltas!mdiff:- work on bytes not lines
350
        base = idxrec[I_BASE]
351
        assert base >= 0
352
        assert base < idx    # no loops!
353
220 by mbp at sourcefrog
limit the number of chained patches
354
        if recursion_limit == None:
355
            sub_limit = None
356
        else:
357
            sub_limit = recursion_limit - 1
358
            if sub_limit < 0:
359
                raise LimitHitException()
360
            
361
        base_text = self.get(base, sub_limit)
205 by mbp at sourcefrog
Revfile:- store and retrieve deltas!mdiff:- work on bytes not lines
362
        patch = self._get_raw(idx, idxrec)
363
364
        text = mdiff.bpatch(base_text, patch)
365
366
        return text
367
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
368
369
198 by mbp at sourcefrog
- experimental compressed Revfile support
370
    def __len__(self):
203 by mbp at sourcefrog
revfile:
371
        """Return number of revisions."""
372
        l = os.fstat(self.idxfile.fileno())[stat.ST_SIZE]
373
        if l % _RECORDSIZE:
374
            raise RevfileError("bad length %d on index of %r" % (l, self.basename))
375
        if l < _RECORDSIZE:
376
            raise RevfileError("no header present in index of %r" % (self.basename))
377
        return int(l / _RECORDSIZE) - 1
198 by mbp at sourcefrog
- experimental compressed Revfile support
378
200 by mbp at sourcefrog
revfile: fix up __getitem__ to allow simple iteration
379
198 by mbp at sourcefrog
- experimental compressed Revfile support
380
    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
381
        """Index by sequence id returns the index field"""
204 by mbp at sourcefrog
Revfile:- new find-sha command and implementation- new _check_index helper
382
        ## 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
383
        self._seek_index(idx)
230 by mbp at sourcefrog
Revfile: better __iter__ method that reads the whole index file in one go!
384
        idxrec = self._read_next_index()
385
        if idxrec == None:
386
            raise IndexError()
387
        else:
388
            return idxrec
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
389
390
391
    def _seek_index(self, idx):
205 by mbp at sourcefrog
Revfile:- store and retrieve deltas!mdiff:- work on bytes not lines
392
        if idx < 0:
393
            raise RevfileError("invalid index %r" % idx)
198 by mbp at sourcefrog
- experimental compressed Revfile support
394
        self.idxfile.seek((idx + 1) * _RECORDSIZE)
230 by mbp at sourcefrog
Revfile: better __iter__ method that reads the whole index file in one go!
395
396
397
398
    def __iter__(self):
399
        """Read back all index records.
400
401
        Do not seek the index file while this is underway!"""
402
        sys.stderr.write(" ** iter called ** \n")
403
        self._seek_index(0)
404
        while True:
405
            idxrec = self._read_next_index()
406
            if not idxrec:
407
                break
408
            yield idxrec
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
409
        
410
411
    def _read_next_index(self):
198 by mbp at sourcefrog
- experimental compressed Revfile support
412
        rec = self.idxfile.read(_RECORDSIZE)
200 by mbp at sourcefrog
revfile: fix up __getitem__ to allow simple iteration
413
        if not rec:
230 by mbp at sourcefrog
Revfile: better __iter__ method that reads the whole index file in one go!
414
            return None
200 by mbp at sourcefrog
revfile: fix up __getitem__ to allow simple iteration
415
        elif len(rec) != _RECORDSIZE:
198 by mbp at sourcefrog
- experimental compressed Revfile support
416
            raise RevfileError("short read of %d bytes getting index %d from %r"
417
                               % (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
418
        
199 by mbp at sourcefrog
- use -1 for no_base in revfile
419
        return struct.unpack(">20sIIII12x", rec)
198 by mbp at sourcefrog
- experimental compressed Revfile support
420
421
        
199 by mbp at sourcefrog
- use -1 for no_base in revfile
422
    def dump(self, f=sys.stdout):
423
        f.write('%-8s %-40s %-8s %-8s %-8s %-8s\n' 
424
                % tuple('idx sha1 base flags offset len'.split()))
425
        f.write('-------- ---------------------------------------- ')
426
        f.write('-------- -------- -------- --------\n')
427
200 by mbp at sourcefrog
revfile: fix up __getitem__ to allow simple iteration
428
        for i, rec in enumerate(self):
199 by mbp at sourcefrog
- use -1 for no_base in revfile
429
            f.write("#%-7d %40s " % (i, hexlify(rec[0])))
204 by mbp at sourcefrog
Revfile:- new find-sha command and implementation- new _check_index helper
430
            if rec[1] == _NO_RECORD:
199 by mbp at sourcefrog
- use -1 for no_base in revfile
431
                f.write("(none)   ")
432
            else:
433
                f.write("#%-7d " % rec[1])
434
                
435
            f.write("%8x %8d %8d\n" % (rec[2], rec[3], rec[4]))
222 by mbp at sourcefrog
refactor total_text_size
436
223 by mbp at sourcefrog
doc
437
222 by mbp at sourcefrog
refactor total_text_size
438
    def total_text_size(self):
223 by mbp at sourcefrog
doc
439
        """Return the sum of sizes of all file texts.
440
441
        This is how much space they would occupy if they were stored without
442
        delta and gzip compression.
443
444
        As a side effect this completely validates the Revfile, checking that all
445
        texts can be reproduced with the correct SHA-1."""
222 by mbp at sourcefrog
refactor total_text_size
446
        t = 0L
447
        for idx in range(len(self)):
448
            t += len(self.get(idx))
449
        return t
198 by mbp at sourcefrog
- experimental compressed Revfile support
450
        
451
452
453
def main(argv):
203 by mbp at sourcefrog
revfile:
454
    try:
455
        cmd = argv[1]
456
    except IndexError:
198 by mbp at sourcefrog
- experimental compressed Revfile support
457
        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
458
                         "       revfile add\n"
205 by mbp at sourcefrog
Revfile:- store and retrieve deltas!mdiff:- work on bytes not lines
459
                         "       revfile add-delta BASE\n"
204 by mbp at sourcefrog
Revfile:- new find-sha command and implementation- new _check_index helper
460
                         "       revfile get IDX\n"
221 by mbp at sourcefrog
Revfile: new command total-text-size
461
                         "       revfile find-sha HEX\n"
226 by mbp at sourcefrog
revf: new command 'last'
462
                         "       revfile total-text-size\n"
463
                         "       revfile last\n")
203 by mbp at sourcefrog
revfile:
464
        return 1
218 by mbp at sourcefrog
todo
465
229 by mbp at sourcefrog
Allow opening revision file read-only
466
    def rw():
467
        return Revfile('testrev', 'w')
468
469
    def ro():
470
        return Revfile('testrev', 'r')
471
203 by mbp at sourcefrog
revfile:
472
    if cmd == 'add':
229 by mbp at sourcefrog
Allow opening revision file read-only
473
        print rw().add(sys.stdin.read())
205 by mbp at sourcefrog
Revfile:- store and retrieve deltas!mdiff:- work on bytes not lines
474
    elif cmd == 'add-delta':
229 by mbp at sourcefrog
Allow opening revision file read-only
475
        print rw().add(sys.stdin.read(), int(argv[2]))
203 by mbp at sourcefrog
revfile:
476
    elif cmd == 'dump':
229 by mbp at sourcefrog
Allow opening revision file read-only
477
        ro().dump()
203 by mbp at sourcefrog
revfile:
478
    elif cmd == 'get':
202 by mbp at sourcefrog
Revfile:
479
        try:
203 by mbp at sourcefrog
revfile:
480
            idx = int(argv[2])
202 by mbp at sourcefrog
Revfile:
481
        except IndexError:
203 by mbp at sourcefrog
revfile:
482
            sys.stderr.write("usage: revfile get IDX\n")
483
            return 1
484
485
        if idx < 0 or idx >= len(r):
486
            sys.stderr.write("invalid index %r\n" % idx)
487
            return 1
488
229 by mbp at sourcefrog
Allow opening revision file read-only
489
        sys.stdout.write(ro().get(idx))
204 by mbp at sourcefrog
Revfile:- new find-sha command and implementation- new _check_index helper
490
    elif cmd == 'find-sha':
491
        try:
492
            s = unhexlify(argv[2])
493
        except IndexError:
494
            sys.stderr.write("usage: revfile find-sha HEX\n")
495
            return 1
496
229 by mbp at sourcefrog
Allow opening revision file read-only
497
        idx = ro().find_sha(s)
204 by mbp at sourcefrog
Revfile:- new find-sha command and implementation- new _check_index helper
498
        if idx == _NO_RECORD:
499
            sys.stderr.write("no such record\n")
500
            return 1
501
        else:
502
            print idx
221 by mbp at sourcefrog
Revfile: new command total-text-size
503
    elif cmd == 'total-text-size':
229 by mbp at sourcefrog
Allow opening revision file read-only
504
        print ro().total_text_size()
226 by mbp at sourcefrog
revf: new command 'last'
505
    elif cmd == 'last':
229 by mbp at sourcefrog
Allow opening revision file read-only
506
        print len(ro())-1
198 by mbp at sourcefrog
- experimental compressed Revfile support
507
    else:
203 by mbp at sourcefrog
revfile:
508
        sys.stderr.write("unknown command %r\n" % cmd)
509
        return 1
198 by mbp at sourcefrog
- experimental compressed Revfile support
510
    
511
512
if __name__ == '__main__':
513
    import sys
203 by mbp at sourcefrog
revfile:
514
    sys.exit(main(sys.argv) or 0)