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>
5 # This program is free software; you can redistribute it and/or
6 # modify it under the terms of the GNU General Public License
7 # as published by the Free Software Foundation; version 2
8 # of the License or (at your option) a later version.
10 # This program is distributed in the hope that it will be useful,
11 # but WITHOUT ANY WARRANTY; without even the implied warranty of
12 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 # GNU General Public License for more details.
15 # You should have received a copy of the GNU General Public License
16 # along with this program; if not, write to the Free Software
17 # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
20 """Classes for dealing with packed git objects.
22 A pack is a compact representation of a bunch of objects, stored
23 using deltas where possible.
25 They have two parts, the pack file, which stores the data, and an index
26 that tells you where the data is.
28 To find an object you look in all of the index files 'til you find a
29 match for the object name. You then use the pointer got from this as
30 a pointer in to the corresponding packfile.
33 from collections import defaultdict
35 from itertools import imap, izip
49 from errors import ApplyDeltaError
51 supports_mmap_offset = (sys.version_info[0] >= 3 or
52 (sys.version_info[0] == 2 and sys.version_info[1] >= 6))
55 def take_msb_bytes(map, offset):
57 while len(ret) == 0 or ret[-1] & 0x80:
58 ret.append(ord(map[offset]))
63 def read_zlib(data, offset, dec_size):
64 obj = zlib.decompressobj()
67 while obj.unused_data == "":
69 add = data[base:base+1024]
73 x += obj.decompress(add)
74 assert len(x) == dec_size
75 comp_len = fed-len(obj.unused_data)
83 return sha.hexdigest()
86 MAX_MMAP_SIZE = 256 * 1024 * 1024
88 def simple_mmap(f, offset, size, access=mmap.ACCESS_READ):
89 """Simple wrapper for mmap() which always supports the offset parameter.
91 :param f: File object.
92 :param offset: Offset in the file, from the beginning of the file.
93 :param size: Size of the mmap'ed area
94 :param access: Access mechanism.
97 if offset+size > MAX_MMAP_SIZE and not supports_mmap_offset:
98 raise AssertionError("%s is larger than 256 meg, and this version "
99 "of Python does not support the offset argument to mmap().")
100 if supports_mmap_offset:
101 return mmap.mmap(f.fileno(), size, access=access, offset=offset)
103 class ArraySkipper(object):
105 def __init__(self, array, offset):
109 def __getslice__(self, i, j):
110 return self.array[i+self.offset:j+self.offset]
112 def __getitem__(self, i):
113 return self.array[i+self.offset]
116 return len(self.array) - self.offset
119 return str(self.array[self.offset:])
121 mem = mmap.mmap(f.fileno(), size+offset, access=access)
124 return ArraySkipper(mem, offset)
127 def resolve_object(offset, type, obj, get_ref, get_offset):
128 """Resolve an object, possibly resolving deltas when necessary."""
129 if not type in (6, 7): # Not a delta
132 if type == 6: # offset delta
133 (delta_offset, delta) = obj
134 assert isinstance(delta_offset, int)
135 assert isinstance(delta, str)
136 offset = offset-delta_offset
137 type, base_obj = get_offset(offset)
138 assert isinstance(type, int)
139 elif type == 7: # ref delta
140 (basename, delta) = obj
141 assert isinstance(basename, str) and len(basename) == 20
142 assert isinstance(delta, str)
143 type, base_obj = get_ref(basename)
144 assert isinstance(type, int)
145 type, base_text = resolve_object(offset, type, base_obj, get_ref, get_offset)
146 return type, apply_delta(base_text, delta)
149 class PackIndex(object):
150 """An index in to a packfile.
152 Given a sha id of an object a pack index can tell you the location in the
153 packfile of that object if it has it.
155 To do the loop it opens the file, and indexes first 256 4 byte groups
156 with the first byte of the sha id. The value in the four byte group indexed
157 is the end of the group that shares the same starting byte. Subtract one
158 from the starting byte and index again to find the start of the group.
159 The values are sorted by sha id within the group, so do the math to find
160 the start and end offset and then bisect in to find if the value is present.
163 def __init__(self, filename):
164 """Create a pack index object.
166 Provide it with the name of the index file to consider, and it will map
167 it whenever required.
169 self._filename = filename
170 # Take the size now, so it can be checked each time we map the file to
171 # ensure that it hasn't changed.
172 self._size = os.path.getsize(filename)
173 self._file = open(filename, 'r')
174 self._contents = simple_mmap(self._file, 0, self._size)
175 if self._contents[:4] != '\377tOc':
177 self._fan_out_table = self._read_fan_out_table(0)
179 (self.version, ) = struct.unpack_from(">L", self._contents, 4)
180 assert self.version in (2,), "Version was %d" % self.version
181 self._fan_out_table = self._read_fan_out_table(8)
182 self._name_table_offset = 8 + 0x100 * 4
183 self._crc32_table_offset = self._name_table_offset + 20 * len(self)
184 self._pack_offset_table_offset = self._crc32_table_offset + 4 * len(self)
186 def __eq__(self, other):
187 if type(self) != type(other):
190 if self._fan_out_table != other._fan_out_table:
193 for (name1, _, _), (name2, _, _) in izip(self.iterentries(), other.iterentries()):
202 """Return the number of entries in this pack index."""
203 return self._fan_out_table[-1]
205 def _unpack_entry(self, i):
206 """Unpack the i-th entry in the index file.
208 :return: Tuple with object name (SHA), offset in pack file and
209 CRC32 checksum (if known)."""
210 if self.version == 1:
211 (offset, name) = struct.unpack_from(">L20s", self._contents,
212 (0x100 * 4) + (i * 24))
213 return (name, offset, None)
215 return (self._unpack_name(i), self._unpack_offset(i),
216 self._unpack_crc32_checksum(i))
218 def _unpack_name(self, i):
219 if self.version == 1:
220 return self._unpack_entry(i)[0]
222 return struct.unpack_from("20s", self._contents,
223 self._name_table_offset + i * 20)[0]
225 def _unpack_offset(self, i):
226 if self.version == 1:
227 return self._unpack_entry(i)[1]
229 return struct.unpack_from(">L", self._contents,
230 self._pack_offset_table_offset + i * 4)[0]
232 def _unpack_crc32_checksum(self, i):
233 if self.version == 1:
236 return struct.unpack_from(">L", self._contents,
237 self._crc32_table_offset + i * 4)[0]
240 return imap(sha_to_hex, self._itersha())
243 for i in range(len(self)):
244 yield self._unpack_name(i)
246 def objects_sha1(self):
247 return iter_sha1(self._itersha())
249 def iterentries(self):
250 """Iterate over the entries in this pack index.
252 Will yield tuples with object name, offset in packfile and crc32 checksum.
254 for i in range(len(self)):
255 yield self._unpack_entry(i)
257 def _read_fan_out_table(self, start_offset):
259 for i in range(0x100):
260 ret.append(struct.unpack(">L", self._contents[start_offset+i*4:start_offset+(i+1)*4])[0])
264 """Check that the stored checksum matches the actual checksum."""
265 return self.calculate_checksum() == self.get_stored_checksums()[1]
267 def calculate_checksum(self):
268 f = open(self._filename, 'r')
270 return hashlib.sha1(self._contents[:-20]).digest()
274 def get_stored_checksums(self):
275 """Return the SHA1 checksums stored for the corresponding packfile and
276 this header file itself."""
277 return str(self._contents[-40:-20]), str(self._contents[-20:])
279 def object_index(self, sha):
280 """Return the index in to the corresponding packfile for the object.
282 Given the name of an object it will return the offset that object lives
283 at within the corresponding pack file. If the pack file doesn't have the
284 object then None will be returned.
286 size = os.path.getsize(self._filename)
287 assert size == self._size, "Pack index %s has changed size, I don't " \
288 "like that" % self._filename
290 sha = hex_to_sha(sha)
291 return self._object_index(sha)
293 def _object_index(self, sha):
294 """See object_index"""
299 start = self._fan_out_table[idx-1]
300 end = self._fan_out_table[idx]
304 file_sha = self._unpack_name(i)
310 return self._unpack_offset(i)
314 def read_pack_header(f):
316 assert header[:4] == "PACK"
317 (version,) = struct.unpack_from(">L", header, 4)
318 assert version in (2, 3), "Version was %d" % version
319 (num_objects,) = struct.unpack_from(">L", header, 8)
320 return (version, num_objects)
323 def read_pack_tail(f):
327 def unpack_object(map):
328 bytes = take_msb_bytes(map, 0)
329 type = (bytes[0] >> 4) & 0x07
330 size = bytes[0] & 0x0f
331 for i, byte in enumerate(bytes[1:]):
332 size += (byte & 0x7f) << ((i * 7) + 4)
333 raw_base = len(bytes)
334 if type == 6: # offset delta
335 bytes = take_msb_bytes(map, raw_base)
336 assert not (bytes[-1] & 0x80)
337 delta_base_offset = bytes[0] & 0x7f
338 for byte in bytes[1:]:
339 delta_base_offset += 1
340 delta_base_offset <<= 7
341 delta_base_offset += (byte & 0x7f)
343 uncomp, comp_len = read_zlib(map, raw_base, size)
344 assert size == len(uncomp)
345 return type, (delta_base_offset, uncomp), comp_len+raw_base
346 elif type == 7: # ref delta
347 basename = map[raw_base:raw_base+20]
348 uncomp, comp_len = read_zlib(map, raw_base+20, size)
349 assert size == len(uncomp)
350 return type, (basename, uncomp), comp_len+raw_base+20
352 uncomp, comp_len = read_zlib(map, raw_base, size)
353 assert len(uncomp) == size
354 return type, uncomp, comp_len+raw_base
357 class PackData(object):
358 """The data contained in a packfile.
360 Pack files can be accessed both sequentially for exploding a pack, and
361 directly with the help of an index to retrieve a specific object.
363 The objects within are either complete or a delta aginst another.
365 The header is variable length. If the MSB of each byte is set then it
366 indicates that the subsequent byte is still part of the header.
367 For the first byte the next MS bits are the type, which tells you the type
368 of object, and whether it is a delta. The LS byte is the lowest bits of the
369 size. For each subsequent byte the LS 7 bits are the next MS bits of the
370 size, i.e. the last byte of the header contains the MS bits of the size.
372 For the complete objects the data is stored as zlib deflated data.
373 The size in the header is the uncompressed object size, so to uncompress
374 you need to just keep feeding data to zlib until you get an object back,
375 or it errors on bad data. This is done here by just giving the complete
376 buffer from the start of the deflated object on. This is bad, but until I
377 get mmap sorted out it will have to do.
379 Currently there are no integrity checks done. Also no attempt is made to try
380 and detect the delta case, or a request for an object at the wrong position.
381 It will all just throw a zlib or KeyError.
384 def __init__(self, filename):
385 """Create a PackData object that represents the pack in the given filename.
387 The file must exist and stay readable until the object is disposed of. It
388 must also stay the same size. It will be mapped whenever needed.
390 Currently there is a restriction on the size of the pack as the python
391 mmap implementation is flawed.
393 self._filename = filename
394 assert os.path.exists(filename), "%s is not a packfile" % filename
395 self._size = os.path.getsize(filename)
396 self._header_size = 12
397 assert self._size >= self._header_size, "%s is too small for a packfile (%d < %d)" % (filename, self._size, self._header_size)
400 def _read_header(self):
401 f = open(self._filename, 'rb')
403 (version, self._num_objects) = \
405 f.seek(self._size-20)
406 (self._stored_checksum,) = read_pack_tail(f)
411 """Returns the number of objects in this pack."""
412 return self._num_objects
414 def calculate_checksum(self):
415 f = open(self._filename, 'rb')
417 map = simple_mmap(f, 0, self._size)
418 return hashlib.sha1(map[:-20]).digest()
422 def iterobjects(self):
423 offset = self._header_size
424 f = open(self._filename, 'rb')
425 for i in range(len(self)):
426 map = simple_mmap(f, offset, self._size-offset)
427 (type, obj, total_size) = unpack_object(map)
428 yield offset, type, obj
432 def iterentries(self, ext_resolve_ref=None):
435 postponed = defaultdict(list)
436 class Postpone(Exception):
437 """Raised to postpone delta resolving."""
439 def get_ref_text(sha):
444 return ext_resolve_ref(sha)
447 raise Postpone, (sha, )
448 todo = list(self.iterobjects())
450 (offset, type, obj) = todo.pop(0)
451 at[offset] = (type, obj)
452 assert isinstance(offset, int)
453 assert isinstance(type, int)
454 assert isinstance(obj, tuple) or isinstance(obj, str)
456 type, obj = resolve_object(offset, type, obj, get_ref_text,
458 except Postpone, (sha, ):
459 postponed[sha].append((offset, type, obj))
461 shafile = ShaFile.from_raw_string(type, obj)
462 sha = shafile.sha().digest()
463 found[sha] = (type, obj)
464 yield sha, offset, shafile.crc32()
465 todo += postponed.get(sha, [])
467 raise KeyError([sha_to_hex(h) for h in postponed.keys()])
469 def sorted_entries(self, resolve_ext_ref=None):
470 ret = list(self.iterentries(resolve_ext_ref))
474 def create_index_v1(self, filename, resolve_ext_ref=None):
475 entries = self.sorted_entries(resolve_ext_ref)
476 write_pack_index_v1(filename, entries, self.calculate_checksum())
478 def create_index_v2(self, filename, resolve_ext_ref=None):
479 entries = self.sorted_entries(resolve_ext_ref)
480 write_pack_index_v2(filename, entries, self.calculate_checksum())
482 def get_stored_checksum(self):
483 return self._stored_checksum
486 return (self.calculate_checksum() == self.get_stored_checksum())
488 def get_object_at(self, offset):
489 """Given an offset in to the packfile return the object that is there.
491 Using the associated index the location of an object can be looked up, and
492 then the packfile can be asked directly for that object using this
495 assert isinstance(offset, long) or isinstance(offset, int),\
496 "offset was %r" % offset
497 assert offset >= self._header_size
498 size = os.path.getsize(self._filename)
499 assert size == self._size, "Pack data %s has changed size, I don't " \
500 "like that" % self._filename
501 f = open(self._filename, 'rb')
503 map = simple_mmap(f, offset, size-offset)
504 return unpack_object(map)[:2]
509 class SHA1Writer(object):
511 def __init__(self, f):
513 self.sha1 = hashlib.sha1("")
515 def write(self, data):
516 self.sha1.update(data)
520 sha = self.sha1.digest()
521 assert len(sha) == 20
526 sha = self.write_sha()
534 def write_pack_object(f, type, object):
535 """Write pack object to a file.
537 :param f: File to write to
538 :param o: Object to write
541 if type == 6: # ref delta
542 (delta_base_offset, object) = object
543 elif type == 7: # offset delta
544 (basename, object) = object
546 c = (type << 4) | (size & 15)
549 f.write(chr(c | 0x80))
553 if type == 6: # offset delta
554 ret = [delta_base_offset & 0x7f]
555 delta_base_offset >>= 7
556 while delta_base_offset:
557 delta_base_offset -= 1
558 ret.insert(0, 0x80 | (delta_base_offset & 0x7f))
559 delta_base_offset >>= 7
560 f.write("".join([chr(x) for x in ret]))
561 elif type == 7: # ref delta
562 assert len(basename) == 20
564 f.write(zlib.compress(object))
568 def write_pack(filename, objects, num_objects):
569 f = open(filename + ".pack", 'w')
571 entries, data_sum = write_pack_data(f, objects, num_objects)
575 write_pack_index_v2(filename + ".idx", entries, data_sum)
578 def write_pack_data(f, objects, num_objects, window=10):
579 """Write a new pack file.
581 :param filename: The filename of the new pack file.
582 :param objects: List of objects to write (tuples with object and path)
583 :return: List with (name, offset, crc32 checksum) entries, pack checksum
585 recency = list(objects)
586 # FIXME: Somehow limit delta depth
587 # FIXME: Make thin-pack optional (its not used when cloning a pack)
588 # Build a list of objects ordered by the magic Linus heuristic
589 # This helps us find good objects to diff against us
591 for obj, path in recency:
592 magic.append( (obj.type, path, 1, -len(obj.as_raw_string()[1]), obj) )
594 # Build a map of objects and their index in magic - so we can find preceeding objects
597 for i in range(len(magic)):
598 offs[magic[i][4]] = i
602 f.write("PACK") # Pack header
603 f.write(struct.pack(">L", 2)) # Pack version
604 f.write(struct.pack(">L", num_objects)) # Number of objects in pack
605 for o, path in recency:
606 sha1 = o.sha().digest()
608 orig_t, raw = o.as_raw_string()
611 #for i in range(offs[o]-window, window):
612 # if i < 0 or i >= len(offs): continue
614 # if b.type != orig_t: continue
615 # _, base = b.as_raw_string()
616 # delta = create_delta(base, raw)
617 # if len(delta) < len(winner):
619 # t = 6 if magic[i][2] == 1 else 7
620 offset = write_pack_object(f, t, winner)
621 entries.append((sha1, offset, crc32))
622 return entries, f.write_sha()
625 def write_pack_index_v1(filename, entries, pack_checksum):
626 """Write a new pack index file.
628 :param filename: The filename of the new pack index file.
629 :param entries: List of tuples with object name (sha), offset_in_pack, and
631 :param pack_checksum: Checksum of the pack file.
633 f = open(filename, 'w')
635 fan_out_table = defaultdict(lambda: 0)
636 for (name, offset, entry_checksum) in entries:
637 fan_out_table[ord(name[0])] += 1
639 for i in range(0x100):
640 f.write(struct.pack(">L", fan_out_table[i]))
641 fan_out_table[i+1] += fan_out_table[i]
642 for (name, offset, entry_checksum) in entries:
643 f.write(struct.pack(">L20s", offset, name))
644 assert len(pack_checksum) == 20
645 f.write(pack_checksum)
649 def create_delta(base_buf, target_buf):
650 """Use python difflib to work out how to transform base_buf to target_buf"""
651 assert isinstance(base_buf, str)
652 assert isinstance(target_buf, str)
655 def encode_size(size):
665 out_buf += encode_size(len(base_buf))
666 out_buf += encode_size(len(target_buf))
667 # write out delta opcodes
668 seq = difflib.SequenceMatcher(a=base_buf, b=target_buf)
669 for opcode, i1, i2, j1, j2 in seq.get_opcodes():
670 # Git patch opcodes don't care about deletes!
671 #if opcode == "replace" or opcode == "delete":
673 if opcode == "equal":
674 # If they are equal, unpacker will use data from base_buf
675 # Write out an opcode that says what range to use
681 scratch += chr(o >> i)
686 scratch += chr(s >> i)
690 if opcode == "replace" or opcode == "insert":
691 # If we are replacing a range or adding one, then we just
692 # output it to the stream (prefixed by its size)
697 out_buf += target_buf[o:o+127]
701 out_buf += target_buf[o:o+s]
705 def apply_delta(src_buf, delta):
706 """Based on the similar function in git's patch-delta.c."""
707 assert isinstance(src_buf, str), "was %r" % (src_buf,)
708 assert isinstance(delta, str)
711 delta_length = len(delta)
712 def pop(delta, index):
715 return ord(ret), index
716 def get_delta_header_size(delta, index):
720 cmd, index = pop(delta, index)
721 size |= (cmd & ~0x80) << i
726 src_size, index = get_delta_header_size(delta, index)
727 dest_size, index = get_delta_header_size(delta, index)
728 assert src_size == len(src_buf), "%d vs %d" % (src_size, len(src_buf))
729 while index < delta_length:
730 cmd, index = pop(delta, index)
735 x, index = pop(delta, index)
736 cp_off |= x << (i * 8)
739 if cmd & (1 << (4+i)):
740 x, index = pop(delta, index)
741 cp_size |= x << (i * 8)
744 if (cp_off + cp_size < cp_size or
745 cp_off + cp_size > src_size or
746 cp_size > dest_size):
748 out += src_buf[cp_off:cp_off+cp_size]
750 out += delta[index:index+cmd]
753 raise ApplyDeltaError("Invalid opcode 0")
755 if index != delta_length:
756 raise ApplyDeltaError("delta not empty: %r" % delta[index:])
758 if dest_size != len(out):
759 raise ApplyDeltaError("dest size incorrect")
764 def write_pack_index_v2(filename, entries, pack_checksum):
765 """Write a new pack index file.
767 :param filename: The filename of the new pack index file.
768 :param entries: List of tuples with object name (sha), offset_in_pack, and
770 :param pack_checksum: Checksum of the pack file.
772 f = open(filename, 'w')
774 f.write('\377tOc') # Magic!
775 f.write(struct.pack(">L", 2))
776 fan_out_table = defaultdict(lambda: 0)
777 for (name, offset, entry_checksum) in entries:
778 fan_out_table[ord(name[0])] += 1
780 for i in range(0x100):
781 f.write(struct.pack(">L", fan_out_table[i]))
782 fan_out_table[i+1] += fan_out_table[i]
783 for (name, offset, entry_checksum) in entries:
785 for (name, offset, entry_checksum) in entries:
786 f.write(struct.pack(">l", entry_checksum))
787 for (name, offset, entry_checksum) in entries:
788 # FIXME: handle if MSBit is set in offset
789 f.write(struct.pack(">L", offset))
790 # FIXME: handle table for pack files > 8 Gb
791 assert len(pack_checksum) == 20
792 f.write(pack_checksum)
798 def __init__(self, basename):
799 self._basename = basename
800 self._data_path = self._basename + ".pack"
801 self._idx_path = self._basename + ".idx"
806 return self.idx.objects_sha1()
810 if self._data is None:
811 self._data = PackData(self._data_path)
812 assert len(self.idx) == len(self._data)
813 assert self.idx.get_stored_checksums()[0] == self._data.get_stored_checksum()
818 if self._idx is None:
819 self._idx = PackIndex(self._idx_path)
823 if self._data is not None:
827 def __eq__(self, other):
828 return type(self) == type(other) and self.idx == other.idx
831 """Number of entries in this pack."""
835 return "Pack(%r)" % self._basename
838 """Iterate over all the sha1s of the objects in this pack."""
839 return iter(self.idx)
842 return self.idx.check() and self.data.check()
844 def get_stored_checksum(self):
845 return self.data.get_stored_checksum()
847 def __contains__(self, sha1):
848 """Check whether this pack contains a particular SHA1."""
849 return (self.idx.object_index(sha1) is not None)
851 def get_raw(self, sha1, resolve_ref=None):
852 offset = self.idx.object_index(sha1)
856 type, obj = self.data.get_object_at(offset)
857 assert isinstance(offset, int)
858 return resolve_object(offset, type, obj, resolve_ref,
859 self.data.get_object_at)
861 def __getitem__(self, sha1):
862 """Retrieve the specified SHA1."""
863 type, uncomp = self.get_raw(sha1)
864 return ShaFile.from_raw_string(type, uncomp)
866 def iterobjects(self, get_raw=None):
870 for offset, type, obj in self.data.iterobjects():
871 assert isinstance(offset, int)
872 yield ShaFile.from_raw_string(
873 *resolve_object(offset, type, obj,
875 self.data.get_object_at))
878 def load_packs(path):
879 if not os.path.exists(path):
881 for name in os.listdir(path):
882 if name.startswith("pack-") and name.endswith(".pack"):
883 yield Pack(os.path.join(path, name[:-len(".pack")]))