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 imap, izip
52 from errors import ApplyDeltaError
54 supports_mmap_offset = (sys.version_info[0] >= 3 or
55 (sys.version_info[0] == 2 and sys.version_info[1] >= 6))
58 def take_msb_bytes(map, offset):
60 while len(ret) == 0 or ret[-1] & 0x80:
61 ret.append(ord(map[offset]))
66 def read_zlib(data, offset, dec_size):
67 obj = zlib.decompressobj()
70 while obj.unused_data == "":
72 add = data[base:base+1024]
74 x += obj.decompress(add)
75 assert len(x) == dec_size
76 comp_len = fed-len(obj.unused_data)
84 return sha.hexdigest()
87 MAX_MMAP_SIZE = 256 * 1024 * 1024
89 def simple_mmap(f, offset, size, access=mmap.ACCESS_READ):
90 """Simple wrapper for mmap() which always supports the offset parameter.
92 :param f: File object.
93 :param offset: Offset in the file, from the beginning of the file.
94 :param size: Size of the mmap'ed area
95 :param access: Access mechanism.
98 if offset+size > MAX_MMAP_SIZE and not supports_mmap_offset:
99 raise AssertionError("%s is larger than 256 meg, and this version "
100 "of Python does not support the offset argument to mmap().")
101 if supports_mmap_offset:
102 return mmap.mmap(f.fileno(), size, access=access, offset=offset)
104 class ArraySkipper(object):
106 def __init__(self, array, offset):
110 def __getslice__(self, i, j):
111 return self.array[i+self.offset:j+self.offset]
113 def __getitem__(self, i):
114 return self.array[i+self.offset]
117 return len(self.array) - self.offset
120 return str(self.array[self.offset:])
122 mem = mmap.mmap(f.fileno(), size+offset, access=access)
125 return ArraySkipper(mem, offset)
128 def resolve_object(offset, type, obj, get_ref, get_offset):
129 """Resolve an object, possibly resolving deltas when necessary."""
130 if not type in (6, 7): # Not a delta
133 if type == 6: # offset delta
134 (delta_offset, delta) = obj
135 assert isinstance(delta_offset, int)
136 assert isinstance(delta, str)
137 offset = offset-delta_offset
138 type, base_obj = get_offset(offset)
139 assert isinstance(type, int)
140 elif type == 7: # ref delta
141 (basename, delta) = obj
142 assert isinstance(basename, str) and len(basename) == 20
143 assert isinstance(delta, str)
144 type, base_obj = get_ref(basename)
145 assert isinstance(type, int)
146 type, base_text = resolve_object(offset, type, base_obj, get_ref, get_offset)
147 return type, apply_delta(base_text, delta)
150 class PackIndex(object):
151 """An index in to a packfile.
153 Given a sha id of an object a pack index can tell you the location in the
154 packfile of that object if it has it.
156 To do the loop it opens the file, and indexes first 256 4 byte groups
157 with the first byte of the sha id. The value in the four byte group indexed
158 is the end of the group that shares the same starting byte. Subtract one
159 from the starting byte and index again to find the start of the group.
160 The values are sorted by sha id within the group, so do the math to find
161 the start and end offset and then bisect in to find if the value is present.
164 def __init__(self, filename):
165 """Create a pack index object.
167 Provide it with the name of the index file to consider, and it will map
168 it whenever required.
170 self._filename = filename
171 # Take the size now, so it can be checked each time we map the file to
172 # ensure that it hasn't changed.
173 self._size = os.path.getsize(filename)
174 self._file = open(filename, 'r')
175 self._contents = simple_mmap(self._file, 0, self._size)
176 if self._contents[:4] != '\377tOc':
178 self._fan_out_table = self._read_fan_out_table(0)
180 (self.version, ) = struct.unpack_from(">L", self._contents, 4)
181 assert self.version in (2,), "Version was %d" % self.version
182 self._fan_out_table = self._read_fan_out_table(8)
183 self._name_table_offset = 8 + 0x100 * 4
184 self._crc32_table_offset = self._name_table_offset + 20 * len(self)
185 self._pack_offset_table_offset = self._crc32_table_offset + 4 * len(self)
187 def __eq__(self, other):
188 if type(self) != type(other):
191 if self._fan_out_table != other._fan_out_table:
194 for (name1, _, _), (name2, _, _) in izip(self.iterentries(), other.iterentries()):
203 """Return the number of entries in this pack index."""
204 return self._fan_out_table[-1]
206 def _unpack_entry(self, i):
207 """Unpack the i-th entry in the index file.
209 :return: Tuple with object name (SHA), offset in pack file and
210 CRC32 checksum (if known)."""
211 if self.version == 1:
212 (offset, name) = struct.unpack_from(">L20s", self._contents,
213 (0x100 * 4) + (i * 24))
214 return (name, offset, None)
216 return (self._unpack_name(i), self._unpack_offset(i),
217 self._unpack_crc32_checksum(i))
219 def _unpack_name(self, i):
220 if self.version == 1:
221 return self._unpack_entry(i)[0]
223 return struct.unpack_from("20s", self._contents,
224 self._name_table_offset + i * 20)[0]
226 def _unpack_offset(self, i):
227 if self.version == 1:
228 return self._unpack_entry(i)[1]
230 return struct.unpack_from(">L", self._contents,
231 self._pack_offset_table_offset + i * 4)[0]
233 def _unpack_crc32_checksum(self, i):
234 if self.version == 1:
237 return struct.unpack_from(">L", self._contents,
238 self._crc32_table_offset + i * 4)[0]
241 return imap(sha_to_hex, self._itersha())
244 for i in range(len(self)):
245 yield self._unpack_name(i)
247 def objects_sha1(self):
248 return iter_sha1(self._itersha())
250 def iterentries(self):
251 """Iterate over the entries in this pack index.
253 Will yield tuples with object name, offset in packfile and crc32 checksum.
255 for i in range(len(self)):
256 yield self._unpack_entry(i)
258 def _read_fan_out_table(self, start_offset):
260 for i in range(0x100):
261 ret.append(struct.unpack(">L", self._contents[start_offset+i*4:start_offset+(i+1)*4])[0])
265 """Check that the stored checksum matches the actual checksum."""
266 return self.calculate_checksum() == self.get_stored_checksums()[1]
268 def calculate_checksum(self):
269 f = open(self._filename, 'r')
271 return hashlib.sha1(self._contents[:-20]).digest()
275 def get_stored_checksums(self):
276 """Return the SHA1 checksums stored for the corresponding packfile and
277 this header file itself."""
278 return str(self._contents[-40:-20]), str(self._contents[-20:])
280 def object_index(self, sha):
281 """Return the index in to the corresponding packfile for the object.
283 Given the name of an object it will return the offset that object lives
284 at within the corresponding pack file. If the pack file doesn't have the
285 object then None will be returned.
287 size = os.path.getsize(self._filename)
288 assert size == self._size, "Pack index %s has changed size, I don't " \
289 "like that" % self._filename
291 sha = hex_to_sha(sha)
292 return self._object_index(sha)
294 def _object_index(self, sha):
295 """See object_index"""
300 start = self._fan_out_table[idx-1]
301 end = self._fan_out_table[idx]
305 file_sha = self._unpack_name(i)
311 return self._unpack_offset(i)
315 def read_pack_header(f):
317 assert header[:4] == "PACK"
318 (version,) = struct.unpack_from(">L", header, 4)
319 assert version in (2, 3), "Version was %d" % version
320 (num_objects,) = struct.unpack_from(">L", header, 8)
321 return (version, num_objects)
324 def read_pack_tail(f):
328 def unpack_object(map):
329 bytes = take_msb_bytes(map, 0)
330 type = (bytes[0] >> 4) & 0x07
331 size = bytes[0] & 0x0f
332 for i, byte in enumerate(bytes[1:]):
333 size += (byte & 0x7f) << ((i * 7) + 4)
334 raw_base = len(bytes)
335 if type == 6: # offset delta
336 bytes = take_msb_bytes(map, raw_base)
337 assert not (bytes[-1] & 0x80)
338 delta_base_offset = bytes[0] & 0x7f
339 for byte in bytes[1:]:
340 delta_base_offset += 1
341 delta_base_offset <<= 7
342 delta_base_offset += (byte & 0x7f)
344 uncomp, comp_len = read_zlib(map, raw_base, size)
345 assert size == len(uncomp)
346 return type, (delta_base_offset, uncomp), comp_len+raw_base
347 elif type == 7: # ref delta
348 basename = map[raw_base:raw_base+20]
349 uncomp, comp_len = read_zlib(map, raw_base+20, size)
350 assert size == len(uncomp)
351 return type, (basename, uncomp), comp_len+raw_base+20
353 uncomp, comp_len = read_zlib(map, raw_base, size)
354 assert len(uncomp) == size
355 return type, uncomp, comp_len+raw_base
358 class PackData(object):
359 """The data contained in a packfile.
361 Pack files can be accessed both sequentially for exploding a pack, and
362 directly with the help of an index to retrieve a specific object.
364 The objects within are either complete or a delta aginst another.
366 The header is variable length. If the MSB of each byte is set then it
367 indicates that the subsequent byte is still part of the header.
368 For the first byte the next MS bits are the type, which tells you the type
369 of object, and whether it is a delta. The LS byte is the lowest bits of the
370 size. For each subsequent byte the LS 7 bits are the next MS bits of the
371 size, i.e. the last byte of the header contains the MS bits of the size.
373 For the complete objects the data is stored as zlib deflated data.
374 The size in the header is the uncompressed object size, so to uncompress
375 you need to just keep feeding data to zlib until you get an object back,
376 or it errors on bad data. This is done here by just giving the complete
377 buffer from the start of the deflated object on. This is bad, but until I
378 get mmap sorted out it will have to do.
380 Currently there are no integrity checks done. Also no attempt is made to try
381 and detect the delta case, or a request for an object at the wrong position.
382 It will all just throw a zlib or KeyError.
385 def __init__(self, filename):
386 """Create a PackData object that represents the pack in the given filename.
388 The file must exist and stay readable until the object is disposed of. It
389 must also stay the same size. It will be mapped whenever needed.
391 Currently there is a restriction on the size of the pack as the python
392 mmap implementation is flawed.
394 self._filename = filename
395 assert os.path.exists(filename), "%s is not a packfile" % filename
396 self._size = os.path.getsize(filename)
397 self._header_size = 12
398 assert self._size >= self._header_size, "%s is too small for a packfile" % filename
401 def _read_header(self):
402 f = open(self._filename, 'rb')
404 (version, self._num_objects) = \
406 f.seek(self._size-20)
407 (self._stored_checksum,) = read_pack_tail(f)
412 """Returns the number of objects in this pack."""
413 return self._num_objects
415 def calculate_checksum(self):
416 f = open(self._filename, 'rb')
418 map = simple_mmap(f, 0, self._size)
419 return hashlib.sha1(map[:-20]).digest()
423 def iterobjects(self):
424 offset = self._header_size
425 f = open(self._filename, 'rb')
426 for i in range(len(self)):
427 map = simple_mmap(f, offset, self._size-offset)
428 (type, obj, total_size) = unpack_object(map)
429 yield offset, type, obj
433 def iterentries(self, ext_resolve_ref=None):
436 postponed = defaultdict(list)
437 class Postpone(Exception):
438 """Raised to postpone delta resolving."""
440 def get_ref_text(sha):
445 return ext_resolve_ref(sha)
448 raise Postpone, (sha, )
449 todo = list(self.iterobjects())
451 (offset, type, obj) = todo.pop(0)
452 at[offset] = (type, obj)
453 assert isinstance(offset, int)
454 assert isinstance(type, int)
455 assert isinstance(obj, tuple) or isinstance(obj, str)
457 type, obj = resolve_object(offset, type, obj, get_ref_text,
459 except Postpone, (sha, ):
460 postponed[sha].append((offset, type, obj))
462 shafile = ShaFile.from_raw_string(type, obj)
463 sha = shafile.sha().digest()
464 found[sha] = (type, obj)
465 yield sha, offset, shafile.crc32()
466 todo += postponed.get(sha, [])
468 raise KeyError([sha_to_hex(h) for h in postponed.keys()])
470 def sorted_entries(self, resolve_ext_ref=None):
471 ret = list(self.iterentries(resolve_ext_ref))
475 def create_index_v1(self, filename):
476 entries = self.sorted_entries()
477 write_pack_index_v1(filename, entries, self.calculate_checksum())
479 def create_index_v2(self, filename):
480 entries = self.sorted_entries()
481 write_pack_index_v2(filename, entries, self.calculate_checksum())
483 def get_stored_checksum(self):
484 return self._stored_checksum
487 return (self.calculate_checksum() == self.get_stored_checksum())
489 def get_object_at(self, offset):
490 """Given an offset in to the packfile return the object that is there.
492 Using the associated index the location of an object can be looked up, and
493 then the packfile can be asked directly for that object using this
496 assert isinstance(offset, long) or isinstance(offset, int),\
497 "offset was %r" % offset
498 assert offset >= self._header_size
499 size = os.path.getsize(self._filename)
500 assert size == self._size, "Pack data %s has changed size, I don't " \
501 "like that" % self._filename
502 f = open(self._filename, 'rb')
504 map = simple_mmap(f, offset, size-offset)
505 return unpack_object(map)[:2]
510 class SHA1Writer(object):
512 def __init__(self, f):
514 self.sha1 = hashlib.sha1("")
516 def write(self, data):
517 self.sha1.update(data)
521 sha = self.sha1.digest()
522 assert len(sha) == 20
527 sha = self.write_sha()
535 def write_pack_object(f, type, object):
536 """Write pack object to a file.
538 :param f: File to write to
539 :param o: Object to write
542 if type == 6: # ref delta
543 (delta_base_offset, object) = object
544 elif type == 7: # offset delta
545 (basename, object) = object
547 c = (type << 4) | (size & 15)
550 f.write(chr(c | 0x80))
554 if type == 6: # offset delta
555 ret = [delta_base_offset & 0x7f]
556 delta_base_offset >>= 7
557 while delta_base_offset:
558 delta_base_offset -= 1
559 ret.insert(0, 0x80 | (delta_base_offset & 0x7f))
560 delta_base_offset >>= 7
561 f.write("".join([chr(x) for x in ret]))
562 elif type == 7: # ref delta
563 assert len(basename) == 20
565 f.write(zlib.compress(object))
569 def write_pack(filename, objects, num_objects):
570 f = open(filename + ".pack", 'w')
572 entries, data_sum = write_pack_data(f, objects, num_objects)
576 write_pack_index_v2(filename + ".idx", entries, data_sum)
579 def write_pack_data(f, objects, num_objects, window=10):
580 """Write a new pack file.
582 :param filename: The filename of the new pack file.
583 :param objects: List of objects to write.
584 :return: List with (name, offset, crc32 checksum) entries, pack checksum
586 recency = list(objects)
587 # FIXME: Somehow limit delta depth
588 # FIXME: Make thin-pack optional (its not used when cloning a pack)
589 # Build a list of objects ordered by the magic Linus heuristic
590 # This helps us find good objects to diff against us
593 magic.append( (o._num_type, "filename", 1, -len(o.as_raw_string()[1]), o) )
595 # Build a map of objects and their index in magic - so we can find preceeding objects
598 for i in range(len(magic)):
599 offs[magic[i][4]] = i
603 f.write("PACK") # Pack header
604 f.write(struct.pack(">L", 2)) # Pack version
605 f.write(struct.pack(">L", num_objects)) # Number of objects in pack
607 sha1 = o.sha().digest()
609 orig_t, raw = o.as_raw_string()
612 #for i in range(offs[o]-window, window):
613 # if i < 0 or i >= len(offs): continue
615 # if b._num_type != orig_t: continue
616 # _, base = b.as_raw_string()
617 # delta = create_delta(base, raw)
618 # if len(delta) < len(winner):
620 # t = 6 if magic[i][2] == 1 else 7
621 offset = write_pack_object(f, t, winner)
622 entries.append((sha1, offset, crc32))
623 return entries, f.write_sha()
626 def write_pack_index_v1(filename, entries, pack_checksum):
627 """Write a new pack index file.
629 :param filename: The filename of the new pack index file.
630 :param entries: List of tuples with object name (sha), offset_in_pack, and
632 :param pack_checksum: Checksum of the pack file.
634 f = open(filename, 'w')
636 fan_out_table = defaultdict(lambda: 0)
637 for (name, offset, entry_checksum) in entries:
638 fan_out_table[ord(name[0])] += 1
640 for i in range(0x100):
641 f.write(struct.pack(">L", fan_out_table[i]))
642 fan_out_table[i+1] += fan_out_table[i]
643 for (name, offset, entry_checksum) in entries:
644 f.write(struct.pack(">L20s", offset, name))
645 assert len(pack_checksum) == 20
646 f.write(pack_checksum)
650 def create_delta(base_buf, target_buf):
651 """Use python difflib to work out how to transform base_buf to target_buf"""
652 assert isinstance(base_buf, str)
653 assert isinstance(target_buf, str)
656 def encode_size(size):
666 out_buf += encode_size(len(base_buf))
667 out_buf += encode_size(len(target_buf))
668 # write out delta opcodes
669 seq = difflib.SequenceMatcher(a=base_buf, b=target_buf)
670 for opcode, i1, i2, j1, j2 in seq.get_opcodes():
671 # Git patch opcodes don't care about deletes!
672 #if opcode == "replace" or opcode == "delete":
674 if opcode == "equal":
675 # If they are equal, unpacker will use data from base_buf
676 # Write out an opcode that says what range to use
682 scratch += chr(o >> i)
687 scratch += chr(s >> i)
691 if opcode == "replace" or opcode == "insert":
692 # If we are replacing a range or adding one, then we just
693 # output it to the stream (prefixed by its size)
698 out_buf += target_buf[o:o+127]
702 out_buf += target_buf[o:o+s]
706 def apply_delta(src_buf, delta):
707 """Based on the similar function in git's patch-delta.c."""
708 assert isinstance(src_buf, str), "was %r" % (src_buf,)
709 assert isinstance(delta, str)
714 return ord(ret), delta
715 def get_delta_header_size(delta):
719 cmd, delta = pop(delta)
720 size |= (cmd & ~0x80) << i
725 src_size, delta = get_delta_header_size(delta)
726 dest_size, delta = get_delta_header_size(delta)
727 assert src_size == len(src_buf), "%d vs %d" % (src_size, len(src_buf))
729 cmd, delta = pop(delta)
734 x, delta = pop(delta)
735 cp_off |= x << (i * 8)
738 if cmd & (1 << (4+i)):
739 x, delta = pop(delta)
740 cp_size |= x << (i * 8)
743 if (cp_off + cp_size < cp_size or
744 cp_off + cp_size > src_size or
745 cp_size > dest_size):
747 out += src_buf[cp_off:cp_off+cp_size]
752 raise ApplyDeltaError("Invalid opcode 0")
755 raise ApplyDeltaError("delta not empty: %r" % delta)
757 if dest_size != len(out):
758 raise ApplyDeltaError("dest size incorrect")
763 def write_pack_index_v2(filename, entries, pack_checksum):
764 """Write a new pack index file.
766 :param filename: The filename of the new pack index file.
767 :param entries: List of tuples with object name (sha), offset_in_pack, and
769 :param pack_checksum: Checksum of the pack file.
771 f = open(filename, 'w')
773 f.write('\377tOc') # Magic!
774 f.write(struct.pack(">L", 2))
775 fan_out_table = defaultdict(lambda: 0)
776 for (name, offset, entry_checksum) in entries:
777 fan_out_table[ord(name[0])] += 1
779 for i in range(0x100):
780 f.write(struct.pack(">L", fan_out_table[i]))
781 fan_out_table[i+1] += fan_out_table[i]
782 for (name, offset, entry_checksum) in entries:
784 for (name, offset, entry_checksum) in entries:
785 f.write(struct.pack(">l", entry_checksum))
786 for (name, offset, entry_checksum) in entries:
787 # FIXME: handle if MSBit is set in offset
788 f.write(struct.pack(">L", offset))
789 # FIXME: handle table for pack files > 8 Gb
790 assert len(pack_checksum) == 20
791 f.write(pack_checksum)
797 def __init__(self, basename):
798 self._basename = basename
799 self._data_path = self._basename + ".pack"
800 self._idx_path = self._basename + ".idx"
805 return self.idx.objects_sha1()
809 if self._data is None:
810 self._data = PackData(self._data_path)
811 assert len(self.idx) == len(self._data)
812 assert self.idx.get_stored_checksums()[0] == self._data.get_stored_checksum()
817 if self._idx is None:
818 self._idx = PackIndex(self._idx_path)
822 if self._data is not None:
826 def __eq__(self, other):
827 return type(self) == type(other) and self.idx == other.idx
830 """Number of entries in this pack."""
834 return "Pack(%r)" % self._basename
837 """Iterate over all the sha1s of the objects in this pack."""
838 return iter(self.idx)
841 return self.idx.check() and self.data.check()
843 def get_stored_checksum(self):
844 return self.data.get_stored_checksum()
846 def __contains__(self, sha1):
847 """Check whether this pack contains a particular SHA1."""
848 return (self.idx.object_index(sha1) is not None)
850 def get_raw(self, sha1, resolve_ref=None):
851 if resolve_ref is None:
852 resolve_ref = self.get_raw
853 offset = self.idx.object_index(sha1)
857 type, obj = self.data.get_object_at(offset)
858 assert isinstance(offset, int)
859 return resolve_object(offset, type, obj, resolve_ref,
860 self.data.get_object_at)
862 def __getitem__(self, sha1):
863 """Retrieve the specified SHA1."""
864 type, uncomp = self.get_raw(sha1)
865 return ShaFile.from_raw_string(type, uncomp)
867 def iterobjects(self):
868 for offset, type, obj in self.data.iterobjects():
869 assert isinstance(offset, int)
870 yield ShaFile.from_raw_string(
871 *resolve_object(offset, type, obj, self.get_raw,
872 self.data.get_object_at))
875 def load_packs(path):
876 if not os.path.exists(path):
878 for name in os.listdir(path):
879 if name.startswith("pack-") and name.endswith(".pack"):
880 yield Pack(os.path.join(path, name[:-len(".pack")]))