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]
71 x += obj.decompress(add)
72 assert len(x) == dec_size
73 comp_len = fed-len(obj.unused_data)
81 return sha.hexdigest()
84 MAX_MMAP_SIZE = 256 * 1024 * 1024
86 def simple_mmap(f, offset, size, access=mmap.ACCESS_READ):
87 """Simple wrapper for mmap() which always supports the offset parameter.
89 :param f: File object.
90 :param offset: Offset in the file, from the beginning of the file.
91 :param size: Size of the mmap'ed area
92 :param access: Access mechanism.
95 if offset+size > MAX_MMAP_SIZE and not supports_mmap_offset:
96 raise AssertionError("%s is larger than 256 meg, and this version "
97 "of Python does not support the offset argument to mmap().")
98 if supports_mmap_offset:
99 return mmap.mmap(f.fileno(), size, access=access, offset=offset)
101 class ArraySkipper(object):
103 def __init__(self, array, offset):
107 def __getslice__(self, i, j):
108 return self.array[i+self.offset:j+self.offset]
110 def __getitem__(self, i):
111 return self.array[i+self.offset]
114 return len(self.array) - self.offset
117 return str(self.array[self.offset:])
119 mem = mmap.mmap(f.fileno(), size+offset, access=access)
122 return ArraySkipper(mem, offset)
125 def resolve_object(offset, type, obj, get_ref, get_offset):
126 """Resolve an object, possibly resolving deltas when necessary."""
127 if not type in (6, 7): # Not a delta
130 if type == 6: # offset delta
131 (delta_offset, delta) = obj
132 assert isinstance(delta_offset, int)
133 assert isinstance(delta, str)
134 offset = offset-delta_offset
135 type, base_obj = get_offset(offset)
136 assert isinstance(type, int)
137 elif type == 7: # ref delta
138 (basename, delta) = obj
139 assert isinstance(basename, str) and len(basename) == 20
140 assert isinstance(delta, str)
141 type, base_obj = get_ref(basename)
142 assert isinstance(type, int)
143 type, base_text = resolve_object(offset, type, base_obj, get_ref, get_offset)
144 return type, apply_delta(base_text, delta)
147 class PackIndex(object):
148 """An index in to a packfile.
150 Given a sha id of an object a pack index can tell you the location in the
151 packfile of that object if it has it.
153 To do the loop it opens the file, and indexes first 256 4 byte groups
154 with the first byte of the sha id. The value in the four byte group indexed
155 is the end of the group that shares the same starting byte. Subtract one
156 from the starting byte and index again to find the start of the group.
157 The values are sorted by sha id within the group, so do the math to find
158 the start and end offset and then bisect in to find if the value is present.
161 def __init__(self, filename):
162 """Create a pack index object.
164 Provide it with the name of the index file to consider, and it will map
165 it whenever required.
167 self._filename = filename
168 # Take the size now, so it can be checked each time we map the file to
169 # ensure that it hasn't changed.
170 self._size = os.path.getsize(filename)
171 self._file = open(filename, 'r')
172 self._contents = simple_mmap(self._file, 0, self._size)
173 if self._contents[:4] != '\377tOc':
175 self._fan_out_table = self._read_fan_out_table(0)
177 (self.version, ) = struct.unpack_from(">L", self._contents, 4)
178 assert self.version in (2,), "Version was %d" % self.version
179 self._fan_out_table = self._read_fan_out_table(8)
180 self._name_table_offset = 8 + 0x100 * 4
181 self._crc32_table_offset = self._name_table_offset + 20 * len(self)
182 self._pack_offset_table_offset = self._crc32_table_offset + 4 * len(self)
184 def __eq__(self, other):
185 if type(self) != type(other):
188 if self._fan_out_table != other._fan_out_table:
191 for (name1, _, _), (name2, _, _) in izip(self.iterentries(), other.iterentries()):
200 """Return the number of entries in this pack index."""
201 return self._fan_out_table[-1]
203 def _unpack_entry(self, i):
204 """Unpack the i-th entry in the index file.
206 :return: Tuple with object name (SHA), offset in pack file and
207 CRC32 checksum (if known)."""
208 if self.version == 1:
209 (offset, name) = struct.unpack_from(">L20s", self._contents,
210 (0x100 * 4) + (i * 24))
211 return (name, offset, None)
213 return (self._unpack_name(i), self._unpack_offset(i),
214 self._unpack_crc32_checksum(i))
216 def _unpack_name(self, i):
217 if self.version == 1:
218 return self._unpack_entry(i)[0]
220 return struct.unpack_from("20s", self._contents,
221 self._name_table_offset + i * 20)[0]
223 def _unpack_offset(self, i):
224 if self.version == 1:
225 return self._unpack_entry(i)[1]
227 return struct.unpack_from(">L", self._contents,
228 self._pack_offset_table_offset + i * 4)[0]
230 def _unpack_crc32_checksum(self, i):
231 if self.version == 1:
234 return struct.unpack_from(">L", self._contents,
235 self._crc32_table_offset + i * 4)[0]
238 return imap(sha_to_hex, self._itersha())
241 for i in range(len(self)):
242 yield self._unpack_name(i)
244 def objects_sha1(self):
245 return iter_sha1(self._itersha())
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 def read_pack_header(f):
314 assert header[:4] == "PACK"
315 (version,) = struct.unpack_from(">L", header, 4)
316 assert version in (2, 3), "Version was %d" % version
317 (num_objects,) = struct.unpack_from(">L", header, 8)
318 return (version, num_objects)
321 def read_pack_tail(f):
325 def unpack_object(map):
326 bytes = take_msb_bytes(map, 0)
327 type = (bytes[0] >> 4) & 0x07
328 size = bytes[0] & 0x0f
329 for i, byte in enumerate(bytes[1:]):
330 size += (byte & 0x7f) << ((i * 7) + 4)
331 raw_base = len(bytes)
332 if type == 6: # offset delta
333 bytes = take_msb_bytes(map, raw_base)
334 assert not (bytes[-1] & 0x80)
335 delta_base_offset = bytes[0] & 0x7f
336 for byte in bytes[1:]:
337 delta_base_offset += 1
338 delta_base_offset <<= 7
339 delta_base_offset += (byte & 0x7f)
341 uncomp, comp_len = read_zlib(map, raw_base, size)
342 assert size == len(uncomp)
343 return type, (delta_base_offset, uncomp), comp_len+raw_base
344 elif type == 7: # ref delta
345 basename = map[raw_base:raw_base+20]
346 uncomp, comp_len = read_zlib(map, raw_base+20, size)
347 assert size == len(uncomp)
348 return type, (basename, uncomp), comp_len+raw_base+20
350 uncomp, comp_len = read_zlib(map, raw_base, size)
351 assert len(uncomp) == size
352 return type, uncomp, comp_len+raw_base
355 class PackData(object):
356 """The data contained in a packfile.
358 Pack files can be accessed both sequentially for exploding a pack, and
359 directly with the help of an index to retrieve a specific object.
361 The objects within are either complete or a delta aginst another.
363 The header is variable length. If the MSB of each byte is set then it
364 indicates that the subsequent byte is still part of the header.
365 For the first byte the next MS bits are the type, which tells you the type
366 of object, and whether it is a delta. The LS byte is the lowest bits of the
367 size. For each subsequent byte the LS 7 bits are the next MS bits of the
368 size, i.e. the last byte of the header contains the MS bits of the size.
370 For the complete objects the data is stored as zlib deflated data.
371 The size in the header is the uncompressed object size, so to uncompress
372 you need to just keep feeding data to zlib until you get an object back,
373 or it errors on bad data. This is done here by just giving the complete
374 buffer from the start of the deflated object on. This is bad, but until I
375 get mmap sorted out it will have to do.
377 Currently there are no integrity checks done. Also no attempt is made to try
378 and detect the delta case, or a request for an object at the wrong position.
379 It will all just throw a zlib or KeyError.
382 def __init__(self, filename):
383 """Create a PackData object that represents the pack in the given filename.
385 The file must exist and stay readable until the object is disposed of. It
386 must also stay the same size. It will be mapped whenever needed.
388 Currently there is a restriction on the size of the pack as the python
389 mmap implementation is flawed.
391 self._filename = filename
392 assert os.path.exists(filename), "%s is not a packfile" % filename
393 self._size = os.path.getsize(filename)
394 self._header_size = 12
395 assert self._size >= self._header_size, "%s is too small for a packfile" % filename
398 def _read_header(self):
399 f = open(self._filename, 'rb')
401 (version, self._num_objects) = \
403 f.seek(self._size-20)
404 (self._stored_checksum,) = read_pack_tail(f)
409 """Returns the number of objects in this pack."""
410 return self._num_objects
412 def calculate_checksum(self):
413 f = open(self._filename, 'rb')
415 map = simple_mmap(f, 0, self._size)
416 return hashlib.sha1(map[:-20]).digest()
420 def iterobjects(self):
421 offset = self._header_size
422 f = open(self._filename, 'rb')
423 for i in range(len(self)):
424 map = simple_mmap(f, offset, self._size-offset)
425 (type, obj, total_size) = unpack_object(map)
426 yield offset, type, obj
430 def iterentries(self, ext_resolve_ref=None):
433 postponed = defaultdict(list)
434 class Postpone(Exception):
435 """Raised to postpone delta resolving."""
437 def get_ref_text(sha):
442 return ext_resolve_ref(sha)
445 raise Postpone, (sha, )
446 todo = list(self.iterobjects())
448 (offset, type, obj) = todo.pop(0)
449 at[offset] = (type, obj)
450 assert isinstance(offset, int)
451 assert isinstance(type, int)
452 assert isinstance(obj, tuple) or isinstance(obj, str)
454 type, obj = resolve_object(offset, type, obj, get_ref_text,
456 except Postpone, (sha, ):
457 postponed[sha].append((offset, type, obj))
459 shafile = ShaFile.from_raw_string(type, obj)
460 sha = shafile.sha().digest()
461 found[sha] = (type, obj)
462 yield sha, offset, shafile.crc32()
463 todo += postponed.get(sha, [])
465 raise KeyError([sha_to_hex(h) for h in postponed.keys()])
467 def sorted_entries(self, resolve_ext_ref=None):
468 ret = list(self.iterentries(resolve_ext_ref))
472 def create_index_v1(self, filename):
473 entries = self.sorted_entries()
474 write_pack_index_v1(filename, entries, self.calculate_checksum())
476 def create_index_v2(self, filename):
477 entries = self.sorted_entries()
478 write_pack_index_v2(filename, entries, self.calculate_checksum())
480 def get_stored_checksum(self):
481 return self._stored_checksum
484 return (self.calculate_checksum() == self.get_stored_checksum())
486 def get_object_at(self, offset):
487 """Given an offset in to the packfile return the object that is there.
489 Using the associated index the location of an object can be looked up, and
490 then the packfile can be asked directly for that object using this
493 assert isinstance(offset, long) or isinstance(offset, int),\
494 "offset was %r" % offset
495 assert offset >= self._header_size
496 size = os.path.getsize(self._filename)
497 assert size == self._size, "Pack data %s has changed size, I don't " \
498 "like that" % self._filename
499 f = open(self._filename, 'rb')
501 map = simple_mmap(f, offset, size-offset)
502 return unpack_object(map)[:2]
507 class SHA1Writer(object):
509 def __init__(self, f):
511 self.sha1 = hashlib.sha1("")
513 def write(self, data):
514 self.sha1.update(data)
518 sha = self.sha1.digest()
519 assert len(sha) == 20
524 sha = self.write_sha()
532 def write_pack_object(f, type, object):
533 """Write pack object to a file.
535 :param f: File to write to
536 :param o: Object to write
539 if type == 6: # ref delta
540 (delta_base_offset, object) = object
541 elif type == 7: # offset delta
542 (basename, object) = object
544 c = (type << 4) | (size & 15)
547 f.write(chr(c | 0x80))
551 if type == 6: # offset delta
552 ret = [delta_base_offset & 0x7f]
553 delta_base_offset >>= 7
554 while delta_base_offset:
555 delta_base_offset -= 1
556 ret.insert(0, 0x80 | (delta_base_offset & 0x7f))
557 delta_base_offset >>= 7
558 f.write("".join([chr(x) for x in ret]))
559 elif type == 7: # ref delta
560 assert len(basename) == 20
562 f.write(zlib.compress(object))
566 def write_pack(filename, objects, num_objects):
567 f = open(filename + ".pack", 'w')
569 entries, data_sum = write_pack_data(f, objects, num_objects)
573 write_pack_index_v2(filename + ".idx", entries, data_sum)
576 def write_pack_data(f, objects, num_objects, window=10):
577 """Write a new pack file.
579 :param filename: The filename of the new pack file.
580 :param objects: List of objects to write.
581 :return: List with (name, offset, crc32 checksum) entries, pack checksum
583 recency = list(objects)
584 # FIXME: Somehow limit delta depth
585 # FIXME: Make thin-pack optional (its not used when cloning a pack)
586 # Build a list of objects ordered by the magic Linus heuristic
587 # This helps us find good objects to diff against us
589 for obj, path in recency:
590 magic.append( (obj.type, path, 1, -len(obj.as_raw_string()[1]), obj) )
592 # Build a map of objects and their index in magic - so we can find preceeding objects
595 for i in range(len(magic)):
596 offs[magic[i][4]] = i
600 f.write("PACK") # Pack header
601 f.write(struct.pack(">L", 2)) # Pack version
602 f.write(struct.pack(">L", num_objects)) # Number of objects in pack
603 for o, path in recency:
604 sha1 = o.sha().digest()
606 orig_t, raw = o.as_raw_string()
609 #for i in range(offs[o]-window, window):
610 # if i < 0 or i >= len(offs): continue
612 # if b.type != orig_t: continue
613 # _, base = b.as_raw_string()
614 # delta = create_delta(base, raw)
615 # if len(delta) < len(winner):
617 # t = 6 if magic[i][2] == 1 else 7
618 offset = write_pack_object(f, t, winner)
619 entries.append((sha1, offset, crc32))
620 return entries, f.write_sha()
623 def write_pack_index_v1(filename, entries, pack_checksum):
624 """Write a new pack index file.
626 :param filename: The filename of the new pack index file.
627 :param entries: List of tuples with object name (sha), offset_in_pack, and
629 :param pack_checksum: Checksum of the pack file.
631 f = open(filename, 'w')
633 fan_out_table = defaultdict(lambda: 0)
634 for (name, offset, entry_checksum) in entries:
635 fan_out_table[ord(name[0])] += 1
637 for i in range(0x100):
638 f.write(struct.pack(">L", fan_out_table[i]))
639 fan_out_table[i+1] += fan_out_table[i]
640 for (name, offset, entry_checksum) in entries:
641 f.write(struct.pack(">L20s", offset, name))
642 assert len(pack_checksum) == 20
643 f.write(pack_checksum)
647 def create_delta(base_buf, target_buf):
648 """Use python difflib to work out how to transform base_buf to target_buf"""
649 assert isinstance(base_buf, str)
650 assert isinstance(target_buf, str)
653 def encode_size(size):
663 out_buf += encode_size(len(base_buf))
664 out_buf += encode_size(len(target_buf))
665 # write out delta opcodes
666 seq = difflib.SequenceMatcher(a=base_buf, b=target_buf)
667 for opcode, i1, i2, j1, j2 in seq.get_opcodes():
668 # Git patch opcodes don't care about deletes!
669 #if opcode == "replace" or opcode == "delete":
671 if opcode == "equal":
672 # If they are equal, unpacker will use data from base_buf
673 # Write out an opcode that says what range to use
679 scratch += chr(o >> i)
684 scratch += chr(s >> i)
688 if opcode == "replace" or opcode == "insert":
689 # If we are replacing a range or adding one, then we just
690 # output it to the stream (prefixed by its size)
695 out_buf += target_buf[o:o+127]
699 out_buf += target_buf[o:o+s]
703 def apply_delta(src_buf, delta):
704 """Based on the similar function in git's patch-delta.c."""
705 assert isinstance(src_buf, str), "was %r" % (src_buf,)
706 assert isinstance(delta, str)
711 return ord(ret), delta
712 def get_delta_header_size(delta):
716 cmd, delta = pop(delta)
717 size |= (cmd & ~0x80) << i
722 src_size, delta = get_delta_header_size(delta)
723 dest_size, delta = get_delta_header_size(delta)
724 assert src_size == len(src_buf), "%d vs %d" % (src_size, len(src_buf))
726 cmd, delta = pop(delta)
731 x, delta = pop(delta)
732 cp_off |= x << (i * 8)
735 if cmd & (1 << (4+i)):
736 x, delta = pop(delta)
737 cp_size |= x << (i * 8)
740 if (cp_off + cp_size < cp_size or
741 cp_off + cp_size > src_size or
742 cp_size > dest_size):
744 out += src_buf[cp_off:cp_off+cp_size]
749 raise ApplyDeltaError("Invalid opcode 0")
752 raise ApplyDeltaError("delta not empty: %r" % delta)
754 if dest_size != len(out):
755 raise ApplyDeltaError("dest size incorrect")
760 def write_pack_index_v2(filename, entries, pack_checksum):
761 """Write a new pack index file.
763 :param filename: The filename of the new pack index file.
764 :param entries: List of tuples with object name (sha), offset_in_pack, and
766 :param pack_checksum: Checksum of the pack file.
768 f = open(filename, 'w')
770 f.write('\377tOc') # Magic!
771 f.write(struct.pack(">L", 2))
772 fan_out_table = defaultdict(lambda: 0)
773 for (name, offset, entry_checksum) in entries:
774 fan_out_table[ord(name[0])] += 1
776 for i in range(0x100):
777 f.write(struct.pack(">L", fan_out_table[i]))
778 fan_out_table[i+1] += fan_out_table[i]
779 for (name, offset, entry_checksum) in entries:
781 for (name, offset, entry_checksum) in entries:
782 f.write(struct.pack(">l", entry_checksum))
783 for (name, offset, entry_checksum) in entries:
784 # FIXME: handle if MSBit is set in offset
785 f.write(struct.pack(">L", offset))
786 # FIXME: handle table for pack files > 8 Gb
787 assert len(pack_checksum) == 20
788 f.write(pack_checksum)
794 def __init__(self, basename):
795 self._basename = basename
796 self._data_path = self._basename + ".pack"
797 self._idx_path = self._basename + ".idx"
802 return self.idx.objects_sha1()
806 if self._data is None:
807 self._data = PackData(self._data_path)
808 assert len(self.idx) == len(self._data)
809 assert self.idx.get_stored_checksums()[0] == self._data.get_stored_checksum()
814 if self._idx is None:
815 self._idx = PackIndex(self._idx_path)
819 if self._data is not None:
823 def __eq__(self, other):
824 return type(self) == type(other) and self.idx == other.idx
827 """Number of entries in this pack."""
831 return "Pack(%r)" % self._basename
834 """Iterate over all the sha1s of the objects in this pack."""
835 return iter(self.idx)
838 return self.idx.check() and self.data.check()
840 def get_stored_checksum(self):
841 return self.data.get_stored_checksum()
843 def __contains__(self, sha1):
844 """Check whether this pack contains a particular SHA1."""
845 return (self.idx.object_index(sha1) is not None)
847 def get_raw(self, sha1, resolve_ref=None):
848 offset = self.idx.object_index(sha1)
852 type, obj = self.data.get_object_at(offset)
853 assert isinstance(offset, int)
854 return resolve_object(offset, type, obj, resolve_ref,
855 self.data.get_object_at)
857 def __getitem__(self, sha1):
858 """Retrieve the specified SHA1."""
859 type, uncomp = self.get_raw(sha1)
860 return ShaFile.from_raw_string(type, uncomp)
862 def iterobjects(self, get_raw=None):
866 for offset, type, obj in self.data.iterobjects():
867 assert isinstance(offset, int)
868 yield ShaFile.from_raw_string(
869 *resolve_object(offset, type, obj,
871 self.data.get_object_at))
874 def load_packs(path):
875 if not os.path.exists(path):
877 for name in os.listdir(path):
878 if name.startswith("pack-") and name.endswith(".pack"):
879 yield Pack(os.path.join(path, name[:-len(".pack")]))