1
# pack.py -- For dealing wih packed git objects.
2
# Copyright (C) 2007 James Westby <jw+debian@jameswestby.net>
3
# Copryight (C) 2008 Jelmer Vernooij <jelmer@samba.org>
4
# The code is loosely based on that in the sha1_file.c file from git itself,
5
# which is Copyright (C) Linus Torvalds, 2005 and distributed under the
8
# This program is free software; you can redistribute it and/or
9
# modify it under the terms of the GNU General Public License
10
# as published by the Free Software Foundation; version 2
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., 51 Franklin Street, Fifth Floor, Boston,
23
"""Classes for dealing with packed git objects.
25
A pack is a compact representation of a bunch of objects, stored
26
using deltas where possible.
28
They have two parts, the pack file, which stores the data, and an index
29
that tells you where the data is.
31
To find an object you look in all of the index files 'til you find a
32
match for the object name. You then use the pointer got from this as
33
a pointer in to the corresponding packfile.
36
from collections import defaultdict
38
from itertools import izip
48
from errors import ApplyDeltaError
50
supports_mmap_offset = (sys.version_info[0] >= 3 or
51
(sys.version_info[0] == 2 and sys.version_info[1] >= 6))
54
def take_msb_bytes(map, offset):
56
while len(ret) == 0 or ret[-1] & 0x80:
57
ret.append(ord(map[offset]))
62
def read_zlib(data, offset, dec_size):
63
obj = zlib.decompressobj()
66
while obj.unused_data == "":
68
add = data[base:base+1024]
70
x += obj.decompress(add)
71
assert len(x) == dec_size
72
comp_len = fed-len(obj.unused_data)
77
"""Convert a hex string to a binary sha string."""
79
for i in range(0, len(hex), 2):
80
ret += chr(int(hex[i:i+2], 16))
84
"""Convert a binary sha string to a hex sha string."""
87
ret += "%02x" % ord(i)
90
MAX_MMAP_SIZE = 256 * 1024 * 1024
92
def simple_mmap(f, offset, size, access=mmap.ACCESS_READ):
93
"""Simple wrapper for mmap() which always supports the offset parameter.
95
:param f: File object.
96
:param offset: Offset in the file, from the beginning of the file.
97
:param size: Size of the mmap'ed area
98
:param access: Access mechanism.
101
if offset+size > MAX_MMAP_SIZE and not supports_mmap_offset:
102
raise AssertionError("%s is larger than 256 meg, and this version "
103
"of Python does not support the offset argument to mmap().")
104
if supports_mmap_offset:
105
return mmap.mmap(f.fileno(), size, access=access, offset=offset)
107
class ArraySkipper(object):
109
def __init__(self, array, offset):
113
def __getslice__(self, i, j):
114
return self.array[i+self.offset:j+self.offset]
116
def __getitem__(self, i):
117
return self.array[i+self.offset]
120
return len(self.array) - self.offset
123
return str(self.array[self.offset:])
125
mem = mmap.mmap(f.fileno(), size+offset, access=access)
128
return ArraySkipper(mem, offset)
131
def resolve_object(offset, type, obj, get_ref, get_offset):
132
"""Resolve an object, possibly resolving deltas when necessary."""
133
if not type in (6, 7): # Not a delta
136
if type == 6: # offset delta
137
(delta_offset, delta) = obj
138
assert isinstance(delta_offset, int)
139
assert isinstance(delta, str)
140
offset = offset-delta_offset
141
type, base_obj = get_offset(offset)
142
assert isinstance(type, int)
143
elif type == 7: # ref delta
144
(basename, delta) = obj
145
assert isinstance(basename, str) and len(basename) == 20
146
assert isinstance(delta, str)
147
type, base_obj= get_ref(basename)
148
assert isinstance(type, int)
149
type, base_text = resolve_object(offset, type, base_obj, get_ref, get_offset)
150
return type, apply_delta(base_text, delta)
153
class PackIndex(object):
154
"""An index in to a packfile.
156
Given a sha id of an object a pack index can tell you the location in the
157
packfile of that object if it has it.
159
To do the loop it opens the file, and indexes first 256 4 byte groups
160
with the first byte of the sha id. The value in the four byte group indexed
161
is the end of the group that shares the same starting byte. Subtract one
162
from the starting byte and index again to find the start of the group.
163
The values are sorted by sha id within the group, so do the math to find
164
the start and end offset and then bisect in to find if the value is present.
167
def __init__(self, filename):
168
"""Create a pack index object.
170
Provide it with the name of the index file to consider, and it will map
171
it whenever required.
173
self._filename = filename
174
# Take the size now, so it can be checked each time we map the file to
175
# ensure that it hasn't changed.
176
self._size = os.path.getsize(filename)
177
self._file = open(filename, 'r')
178
self._contents = simple_mmap(self._file, 0, self._size)
179
if self._contents[:4] != '\377tOc':
181
self._fan_out_table = self._read_fan_out_table(0)
183
(self.version, ) = struct.unpack_from(">L", self._contents, 4)
184
assert self.version in (2,), "Version was %d" % self.version
185
self._fan_out_table = self._read_fan_out_table(8)
186
self._name_table_offset = 8 + 0x100 * 4
187
self._crc32_table_offset = self._name_table_offset + 20 * len(self)
188
self._pack_offset_table_offset = self._crc32_table_offset + 4 * len(self)
190
def __eq__(self, other):
191
if type(self) != type(other):
194
if self._fan_out_table != other._fan_out_table:
197
for (name1, _, _), (name2, _, _) in izip(self.iterentries(), other.iterentries()):
206
"""Return the number of entries in this pack index."""
207
return self._fan_out_table[-1]
209
def _unpack_entry(self, i):
210
"""Unpack the i-th entry in the index file.
212
:return: Tuple with object name (SHA), offset in pack file and
213
CRC32 checksum (if known)."""
214
if self.version == 1:
215
(offset, name) = struct.unpack_from(">L20s", self._contents,
216
(0x100 * 4) + (i * 24))
217
return (name, offset, None)
219
return (self._unpack_name(i), self._unpack_offset(i),
220
self._unpack_crc32_checksum(i))
222
def _unpack_name(self, i):
223
if self.version == 1:
224
return self._unpack_entry(i)[0]
226
return struct.unpack_from("20s", self._contents,
227
self._name_table_offset + i * 20)[0]
229
def _unpack_offset(self, i):
230
if self.version == 1:
231
return self._unpack_entry(i)[1]
233
return struct.unpack_from(">L", self._contents,
234
self._pack_offset_table_offset + i * 4)[0]
236
def _unpack_crc32_checksum(self, i):
237
if self.version == 1:
240
return struct.unpack_from(">L", self._contents,
241
self._crc32_table_offset + i * 4)[0]
244
for i in range(len(self)):
245
yield sha_to_hex(self._unpack_name(i))
247
def iterentries(self):
248
"""Iterate over the entries in this pack index.
250
Will yield tuples with object name, offset in packfile and crc32 checksum.
252
for i in range(len(self)):
253
yield self._unpack_entry(i)
255
def _read_fan_out_table(self, start_offset):
257
for i in range(0x100):
258
ret.append(struct.unpack(">L", self._contents[start_offset+i*4:start_offset+(i+1)*4])[0])
262
"""Check that the stored checksum matches the actual checksum."""
263
return self.calculate_checksum() == self.get_stored_checksums()[1]
265
def calculate_checksum(self):
266
f = open(self._filename, 'r')
268
return hashlib.sha1(self._contents[:-20]).digest()
272
def get_stored_checksums(self):
273
"""Return the SHA1 checksums stored for the corresponding packfile and
274
this header file itself."""
275
return str(self._contents[-40:-20]), str(self._contents[-20:])
277
def object_index(self, sha):
278
"""Return the index in to the corresponding packfile for the object.
280
Given the name of an object it will return the offset that object lives
281
at within the corresponding pack file. If the pack file doesn't have the
282
object then None will be returned.
284
size = os.path.getsize(self._filename)
285
assert size == self._size, "Pack index %s has changed size, I don't " \
286
"like that" % self._filename
288
sha = hex_to_sha(sha)
289
return self._object_index(sha)
291
def _object_index(self, sha):
292
"""See object_index"""
297
start = self._fan_out_table[idx-1]
298
end = self._fan_out_table[idx]
302
file_sha = self._unpack_name(i)
308
return self._unpack_offset(i)
312
class PackData(object):
313
"""The data contained in a packfile.
315
Pack files can be accessed both sequentially for exploding a pack, and
316
directly with the help of an index to retrieve a specific object.
318
The objects within are either complete or a delta aginst another.
320
The header is variable length. If the MSB of each byte is set then it
321
indicates that the subsequent byte is still part of the header.
322
For the first byte the next MS bits are the type, which tells you the type
323
of object, and whether it is a delta. The LS byte is the lowest bits of the
324
size. For each subsequent byte the LS 7 bits are the next MS bits of the
325
size, i.e. the last byte of the header contains the MS bits of the size.
327
For the complete objects the data is stored as zlib deflated data.
328
The size in the header is the uncompressed object size, so to uncompress
329
you need to just keep feeding data to zlib until you get an object back,
330
or it errors on bad data. This is done here by just giving the complete
331
buffer from the start of the deflated object on. This is bad, but until I
332
get mmap sorted out it will have to do.
334
Currently there are no integrity checks done. Also no attempt is made to try
335
and detect the delta case, or a request for an object at the wrong position.
336
It will all just throw a zlib or KeyError.
339
def __init__(self, filename):
340
"""Create a PackData object that represents the pack in the given filename.
342
The file must exist and stay readable until the object is disposed of. It
343
must also stay the same size. It will be mapped whenever needed.
345
Currently there is a restriction on the size of the pack as the python
346
mmap implementation is flawed.
348
self._filename = filename
349
assert os.path.exists(filename), "%s is not a packfile" % filename
350
self._size = os.path.getsize(filename)
351
self._header_size = self._read_header()
353
def _read_header(self):
354
f = open(self._filename, 'rb')
357
f.seek(self._size-20)
358
self._stored_checksum = f.read(20)
361
assert header[:4] == "PACK"
362
(version,) = struct.unpack_from(">L", header, 4)
363
assert version in (2, 3), "Version was %d" % version
364
(self._num_objects,) = struct.unpack_from(">L", header, 8)
365
return 12 # Header size
368
"""Returns the number of objects in this pack."""
369
return self._num_objects
371
def calculate_checksum(self):
372
f = open(self._filename, 'rb')
374
map = simple_mmap(f, 0, self._size)
375
return hashlib.sha1(map[:-20]).digest()
379
def iterobjects(self):
380
offset = self._header_size
381
f = open(self._filename, 'rb')
382
for i in range(len(self)):
383
map = simple_mmap(f, offset, self._size-offset)
384
(type, obj, total_size) = self._unpack_object(map)
385
yield offset, type, obj
389
def iterentries(self):
391
postponed = list(self.iterobjects())
393
(offset, type, obj) = postponed.pop(0)
394
assert isinstance(offset, int)
395
assert isinstance(type, int)
396
assert isinstance(obj, tuple) or isinstance(obj, str)
398
type, obj = resolve_object(offset, type, obj, found.__getitem__,
401
postponed.append((offset, type, obj))
403
shafile = ShaFile.from_raw_string(type, obj)
404
sha = shafile.sha().digest()
405
found[sha] = (type, obj)
406
yield sha, offset, shafile.crc32()
408
def create_index_v1(self, filename):
409
entries = list(self.iterentries())
410
write_pack_index_v1(filename, entries, self.calculate_checksum())
412
def create_index_v2(self, filename):
413
entries = list(self.iterentries())
414
write_pack_index_v1(filename, entries, self.calculate_checksum())
416
def get_stored_checksum(self):
417
return self._stored_checksum
420
return (self.calculate_checksum() == self.get_stored_checksum())
422
def get_object_at(self, offset):
423
"""Given an offset in to the packfile return the object that is there.
425
Using the associated index the location of an object can be looked up, and
426
then the packfile can be asked directly for that object using this
429
assert isinstance(offset, long) or isinstance(offset, int),\
430
"offset was %r" % offset
431
assert offset >= self._header_size
432
size = os.path.getsize(self._filename)
433
assert size == self._size, "Pack data %s has changed size, I don't " \
434
"like that" % self._filename
435
f = open(self._filename, 'rb')
437
map = simple_mmap(f, offset, size-offset)
438
return self._unpack_object(map)[:2]
442
def _unpack_object(self, map):
443
bytes = take_msb_bytes(map, 0)
444
type = (bytes[0] >> 4) & 0x07
445
size = bytes[0] & 0x0f
446
for i, byte in enumerate(bytes[1:]):
447
size += (byte & 0x7f) << ((i * 7) + 4)
448
raw_base = len(bytes)
449
if type == 6: # offset delta
450
bytes = take_msb_bytes(map, raw_base)
451
assert not (bytes[-1] & 0x80)
452
delta_base_offset = bytes[0] & 0x7f
453
for byte in bytes[1:]:
454
delta_base_offset += 1
455
delta_base_offset <<= 7
456
delta_base_offset += (byte & 0x7f)
458
uncomp, comp_len = read_zlib(map, raw_base, size)
459
assert size == len(uncomp)
460
return type, (delta_base_offset, uncomp), comp_len+raw_base
461
elif type == 7: # ref delta
462
basename = map[raw_base:raw_base+20]
463
uncomp, comp_len = read_zlib(map, raw_base+20, size)
464
assert size == len(uncomp)
465
return type, (basename, uncomp), comp_len+raw_base+20
467
uncomp, comp_len = read_zlib(map, raw_base, size)
468
assert len(uncomp) == size
469
return type, uncomp, comp_len+raw_base
472
class SHA1Writer(object):
474
def __init__(self, f):
476
self.sha1 = hashlib.sha1("")
478
def write(self, data):
479
self.sha1.update(data)
483
sha = self.sha1.digest()
484
assert len(sha) == 20
493
def write_pack_object(f, type, object):
494
"""Write pack object to a file.
496
:param f: File to write to
497
:param o: Object to write
500
if type == 6: # ref delta
501
(delta_base_offset, object) = object
502
elif type == 7: # offset delta
503
(basename, object) = object
505
c = (type << 4) | (size & 15)
508
f.write(chr(c | 0x80))
512
if type == 6: # offset delta
513
ret = [delta_base_offset & 0x7f]
514
delta_base_offset >>= 7
515
while delta_base_offset:
516
delta_base_offset -= 1
517
ret.insert(0, 0x80 | (delta_base_offset & 0x7f))
518
delta_base_offset >>= 7
519
f.write("".join([chr(x) for x in ret]))
520
elif type == 7: # ref delta
521
assert len(basename) == 20
523
f.write(zlib.compress(object))
527
def write_pack(filename, objects):
528
entries, data_sum = write_pack_data(filename + ".pack", objects)
529
write_pack_index_v2(filename + ".idx", entries, data_sum)
532
def write_pack_data(filename, objects):
533
"""Write a new pack file.
535
:param filename: The filename of the new pack file.
536
:param objects: List of objects to write.
537
:return: List with (name, offset, crc32 checksum) entries, pack checksum
539
f = open(filename, 'w')
542
f.write("PACK") # Pack header
543
f.write(struct.pack(">L", 2)) # Pack version
544
f.write(struct.pack(">L", len(objects))) # Number of objects in pack
546
sha1 = o.sha().digest()
549
t, o = o.as_raw_string()
550
offset = write_pack_object(f, t, o)
551
entries.append((sha1, offset, crc32))
552
return entries, f.close()
555
def write_pack_index_v1(filename, entries, pack_checksum):
556
"""Write a new pack index file.
558
:param filename: The filename of the new pack index file.
559
:param entries: List of tuples with object name (sha), offset_in_pack, and
561
:param pack_checksum: Checksum of the pack file.
565
entries = sorted(entries)
566
f = open(filename, 'w')
568
fan_out_table = defaultdict(lambda: 0)
569
for (name, offset, entry_checksum) in entries:
570
fan_out_table[ord(name[0])] += 1
572
for i in range(0x100):
573
f.write(struct.pack(">L", fan_out_table[i]))
574
fan_out_table[i+1] += fan_out_table[i]
575
for (name, offset, entry_checksum) in entries:
576
f.write(struct.pack(">L20s", offset, name))
577
assert len(pack_checksum) == 20
578
f.write(pack_checksum)
582
def apply_delta(src_buf, delta):
583
"""Based on the similar function in git's patch-delta.c."""
584
assert isinstance(src_buf, str), "was %r" % (src_buf,)
585
assert isinstance(delta, str)
590
return ord(ret), delta
591
def get_delta_header_size(delta):
595
cmd, delta = pop(delta)
596
size |= (cmd & ~0x80) << i
601
src_size, delta = get_delta_header_size(delta)
602
dest_size, delta = get_delta_header_size(delta)
603
assert src_size == len(src_buf)
605
cmd, delta = pop(delta)
610
x, delta = pop(delta)
611
cp_off |= x << (i * 8)
614
if cmd & (1 << (4+i)):
615
x, delta = pop(delta)
616
cp_size |= x << (i * 8)
619
if (cp_off + cp_size < cp_size or
620
cp_off + cp_size > src_size or
621
cp_size > dest_size):
623
out += src_buf[cp_off:cp_off+cp_size]
628
raise ApplyDeltaError("Invalid opcode 0")
631
raise ApplyDeltaError("delta not empty: %r" % delta)
633
if dest_size != len(out):
634
raise ApplyDeltaError("dest size incorrect")
639
def write_pack_index_v2(filename, entries, pack_checksum):
640
"""Write a new pack index file.
642
:param filename: The filename of the new pack index file.
643
:param entries: List of tuples with object name (sha), offset_in_pack, and
645
:param pack_checksum: Checksum of the pack file.
648
entries = sorted(entries)
649
f = open(filename, 'w')
652
f.write(struct.pack(">L", 2))
653
fan_out_table = defaultdict(lambda: 0)
654
for (name, offset, entry_checksum) in entries:
655
fan_out_table[ord(name[0])] += 1
657
for i in range(0x100):
658
f.write(struct.pack(">L", fan_out_table[i]))
659
fan_out_table[i+1] += fan_out_table[i]
660
for (name, offset, entry_checksum) in entries:
662
for (name, offset, entry_checksum) in entries:
663
f.write(struct.pack(">L", entry_checksum))
664
for (name, offset, entry_checksum) in entries:
665
# FIXME: handle if MSBit is set in offset
666
f.write(struct.pack(">L", offset))
667
# FIXME: handle table for pack files > 8 Gb
668
assert len(pack_checksum) == 20
669
f.write(pack_checksum)
675
def __init__(self, basename):
676
self._basename = basename
677
self._idx = PackIndex(basename + ".idx")
681
if self._data is None:
682
self._data = PackData(self._basename + ".pack")
683
assert len(self._idx) == len(self._data)
684
assert self._idx.get_stored_checksums()[0] == self._data.get_stored_checksum()
688
if self._data is not None:
692
def __eq__(self, other):
693
return type(self) == type(other) and self._idx == other._idx
696
"""Number of entries in this pack."""
697
return len(self._idx)
700
return "Pack(%r)" % self._basename
703
"""Iterate over all the sha1s of the objects in this pack."""
704
return iter(self._idx)
707
return self._idx.check() and self._get_data().check()
709
def get_stored_checksum(self):
710
return self._get_data().get_stored_checksum()
712
def __contains__(self, sha1):
713
"""Check whether this pack contains a particular SHA1."""
714
return (self._idx.object_index(sha1) is not None)
716
def _get_text(self, sha1):
717
offset = self._idx.object_index(sha1)
721
type, obj = self._get_data().get_object_at(offset)
722
assert isinstance(offset, int)
723
return resolve_object(offset, type, obj, self._get_text,
724
self._get_data().get_object_at)
726
def __getitem__(self, sha1):
727
"""Retrieve the specified SHA1."""
728
type, uncomp = self._get_text(sha1)
729
return ShaFile.from_raw_string(type, uncomp)
731
def iterobjects(self):
732
for offset, type, obj in self._get_data().iterobjects():
733
assert isinstance(offset, int)
734
yield ShaFile.from_raw_string(
735
*resolve_object(offset, type, obj, self._get_text,
736
self._get_data().get_object_at))
739
def load_packs(path):
740
for name in os.listdir(path):
741
if name.endswith(".pack"):
742
yield Pack(os.path.join(path, name.rstrip(".pack")))