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.
34 from collections import defaultdict
36 from misc import defaultdict
38 from itertools import chain, imap, izip
43 from struct import unpack_from
45 from dulwich.misc import unpack_from
50 from dulwich.errors import (
54 from dulwich.lru_cache import (
57 from dulwich.objects import (
62 from dulwich.misc import make_sha
64 supports_mmap_offset = (sys.version_info[0] >= 3 or
65 (sys.version_info[0] == 2 and sys.version_info[1] >= 6))
68 def take_msb_bytes(map, offset):
70 while len(ret) == 0 or ret[-1] & 0x80:
71 ret.append(ord(map[offset]))
76 def read_zlib(data, offset, dec_size):
77 obj = zlib.decompressobj()
80 while obj.unused_data == "":
82 add = data[base:base+1024]
86 ret.append(obj.decompress(add))
88 assert len(x) == dec_size
89 comp_len = fed-len(obj.unused_data)
94 """Return the hexdigest of the SHA1 over a set of names."""
98 return sha1.hexdigest()
101 def simple_mmap(f, offset, size, access=mmap.ACCESS_READ):
102 """Simple wrapper for mmap() which always supports the offset parameter.
104 :param f: File object.
105 :param offset: Offset in the file, from the beginning of the file.
106 :param size: Size of the mmap'ed area
107 :param access: Access mechanism.
108 :return: MMAP'd area.
110 if supports_mmap_offset:
111 return mmap.mmap(f.fileno(), size, access=access, offset=offset), 0
113 mem = mmap.mmap(f.fileno(), size+offset, access=access)
117 def load_pack_index(filename):
118 f = open(filename, 'r')
119 if f.read(4) == '\377tOc':
120 version = struct.unpack(">L", f.read(4))[0]
123 return PackIndex2(filename, file=f)
125 raise KeyError("Unknown pack index format %d" % version)
128 return PackIndex1(filename, file=f)
131 def bisect_find_sha(start, end, sha, unpack_name):
135 file_sha = unpack_name(i)
136 x = cmp(file_sha, sha)
146 class PackIndex(object):
147 """An index in to a packfile.
149 Given a sha id of an object a pack index can tell you the location in the
150 packfile of that object if it has it.
152 To do the loop it opens the file, and indexes first 256 4 byte groups
153 with the first byte of the sha id. The value in the four byte group indexed
154 is the end of the group that shares the same starting byte. Subtract one
155 from the starting byte and index again to find the start of the group.
156 The values are sorted by sha id within the group, so do the math to find
157 the start and end offset and then bisect in to find if the value is present.
160 def __init__(self, filename, file=None):
161 """Create a pack index object.
163 Provide it with the name of the index file to consider, and it will map
164 it whenever required.
166 self._filename = filename
167 # Take the size now, so it can be checked each time we map the file to
168 # ensure that it hasn't changed.
169 self._size = os.path.getsize(filename)
171 self._file = open(filename, 'r')
174 self._contents, map_offset = simple_mmap(self._file, 0, self._size)
175 assert map_offset == 0
177 def __eq__(self, other):
178 if not isinstance(other, PackIndex):
181 if self._fan_out_table != other._fan_out_table:
184 for (name1, _, _), (name2, _, _) in izip(self.iterentries(), other.iterentries()):
193 """Return the number of entries in this pack index."""
194 return self._fan_out_table[-1]
196 def _unpack_entry(self, i):
197 """Unpack the i-th entry in the index file.
199 :return: Tuple with object name (SHA), offset in pack file and
200 CRC32 checksum (if known)."""
201 raise NotImplementedError(self._unpack_entry)
203 def _unpack_name(self, i):
204 """Unpack the i-th name from the index file."""
205 raise NotImplementedError(self._unpack_name)
207 def _unpack_offset(self, i):
208 """Unpack the i-th object offset from the index file."""
209 raise NotImplementedError(self._unpack_offset)
211 def _unpack_crc32_checksum(self, i):
212 """Unpack the crc32 checksum for the i-th object from the index file."""
213 raise NotImplementedError(self._unpack_crc32_checksum)
216 return imap(sha_to_hex, self._itersha())
219 for i in range(len(self)):
220 yield self._unpack_name(i)
222 def objects_sha1(self):
223 """Return the hex SHA1 over all the shas of all objects in this pack.
225 :note: This is used for the filename of the pack.
227 return iter_sha1(self._itersha())
229 def iterentries(self):
230 """Iterate over the entries in this pack index.
232 Will yield tuples with object name, offset in packfile and crc32 checksum.
234 for i in range(len(self)):
235 yield self._unpack_entry(i)
237 def _read_fan_out_table(self, start_offset):
239 for i in range(0x100):
240 ret.append(struct.unpack(">L", self._contents[start_offset+i*4:start_offset+(i+1)*4])[0])
244 """Check that the stored checksum matches the actual checksum."""
245 return self.calculate_checksum() == self.get_stored_checksum()
247 def calculate_checksum(self):
248 return make_sha(self._contents[:-20]).digest()
250 def get_pack_checksum(self):
251 """Return the SHA1 checksum stored for the corresponding packfile."""
252 return str(self._contents[-40:-20])
254 def get_stored_checksum(self):
255 """Return the SHA1 checksum stored for this index."""
256 return str(self._contents[-20:])
258 def object_index(self, sha):
259 """Return the index in to the corresponding packfile for the object.
261 Given the name of an object it will return the offset that object lives
262 at within the corresponding pack file. If the pack file doesn't have the
263 object then None will be returned.
266 sha = hex_to_sha(sha)
267 return self._object_index(sha)
269 def _object_index(self, sha):
272 :param sha: A *binary* SHA string. (20 characters long)_
274 assert len(sha) == 20
279 start = self._fan_out_table[idx-1]
280 end = self._fan_out_table[idx]
281 i = bisect_find_sha(start, end, sha, self._unpack_name)
284 return self._unpack_offset(i)
288 class PackIndex1(PackIndex):
289 """Version 1 Pack Index."""
291 def __init__(self, filename, file=None):
292 PackIndex.__init__(self, filename, file)
294 self._fan_out_table = self._read_fan_out_table(0)
296 def _unpack_entry(self, i):
297 (offset, name) = unpack_from(">L20s", self._contents,
298 (0x100 * 4) + (i * 24))
299 return (name, offset, None)
301 def _unpack_name(self, i):
302 offset = (0x100 * 4) + (i * 24) + 4
303 return self._contents[offset:offset+20]
305 def _unpack_offset(self, i):
306 offset = (0x100 * 4) + (i * 24)
307 return unpack_from(">L", self._contents, offset)[0]
309 def _unpack_crc32_checksum(self, i):
310 # Not stored in v1 index files
314 class PackIndex2(PackIndex):
315 """Version 2 Pack Index."""
317 def __init__(self, filename, file=None):
318 PackIndex.__init__(self, filename, file)
319 assert self._contents[:4] == '\377tOc', "Not a v2 pack index file"
320 (self.version, ) = unpack_from(">L", self._contents, 4)
321 assert self.version == 2, "Version was %d" % self.version
322 self._fan_out_table = self._read_fan_out_table(8)
323 self._name_table_offset = 8 + 0x100 * 4
324 self._crc32_table_offset = self._name_table_offset + 20 * len(self)
325 self._pack_offset_table_offset = self._crc32_table_offset + 4 * len(self)
327 def _unpack_entry(self, i):
328 return (self._unpack_name(i), self._unpack_offset(i),
329 self._unpack_crc32_checksum(i))
331 def _unpack_name(self, i):
332 offset = self._name_table_offset + i * 20
333 return self._contents[offset:offset+20]
335 def _unpack_offset(self, i):
336 offset = self._pack_offset_table_offset + i * 4
337 return unpack_from(">L", self._contents, offset)[0]
339 def _unpack_crc32_checksum(self, i):
340 return unpack_from(">L", self._contents,
341 self._crc32_table_offset + i * 4)[0]
345 def read_pack_header(f):
347 assert header[:4] == "PACK"
348 (version,) = unpack_from(">L", header, 4)
349 assert version in (2, 3), "Version was %d" % version
350 (num_objects,) = unpack_from(">L", header, 8)
351 return (version, num_objects)
354 def read_pack_tail(f):
358 def unpack_object(map, offset=0):
359 bytes = take_msb_bytes(map, offset)
360 type = (bytes[0] >> 4) & 0x07
361 size = bytes[0] & 0x0f
362 for i, byte in enumerate(bytes[1:]):
363 size += (byte & 0x7f) << ((i * 7) + 4)
364 raw_base = len(bytes)
365 if type == 6: # offset delta
366 bytes = take_msb_bytes(map, raw_base + offset)
367 assert not (bytes[-1] & 0x80)
368 delta_base_offset = bytes[0] & 0x7f
369 for byte in bytes[1:]:
370 delta_base_offset += 1
371 delta_base_offset <<= 7
372 delta_base_offset += (byte & 0x7f)
374 uncomp, comp_len = read_zlib(map, offset + raw_base, size)
375 assert size == len(uncomp)
376 return type, (delta_base_offset, uncomp), comp_len+raw_base
377 elif type == 7: # ref delta
378 basename = map[offset+raw_base:offset+raw_base+20]
379 uncomp, comp_len = read_zlib(map, offset+raw_base+20, size)
380 assert size == len(uncomp)
381 return type, (basename, uncomp), comp_len+raw_base+20
383 uncomp, comp_len = read_zlib(map, offset+raw_base, size)
384 assert len(uncomp) == size
385 return type, uncomp, comp_len+raw_base
388 def compute_object_size((num, obj)):
391 assert isinstance(obj, str)
395 class PackData(object):
396 """The data contained in a packfile.
398 Pack files can be accessed both sequentially for exploding a pack, and
399 directly with the help of an index to retrieve a specific object.
401 The objects within are either complete or a delta aginst another.
403 The header is variable length. If the MSB of each byte is set then it
404 indicates that the subsequent byte is still part of the header.
405 For the first byte the next MS bits are the type, which tells you the type
406 of object, and whether it is a delta. The LS byte is the lowest bits of the
407 size. For each subsequent byte the LS 7 bits are the next MS bits of the
408 size, i.e. the last byte of the header contains the MS bits of the size.
410 For the complete objects the data is stored as zlib deflated data.
411 The size in the header is the uncompressed object size, so to uncompress
412 you need to just keep feeding data to zlib until you get an object back,
413 or it errors on bad data. This is done here by just giving the complete
414 buffer from the start of the deflated object on. This is bad, but until I
415 get mmap sorted out it will have to do.
417 Currently there are no integrity checks done. Also no attempt is made to try
418 and detect the delta case, or a request for an object at the wrong position.
419 It will all just throw a zlib or KeyError.
422 def __init__(self, filename):
423 """Create a PackData object that represents the pack in the given filename.
425 The file must exist and stay readable until the object is disposed of. It
426 must also stay the same size. It will be mapped whenever needed.
428 Currently there is a restriction on the size of the pack as the python
429 mmap implementation is flawed.
431 self._filename = filename
432 assert os.path.exists(filename), "%s is not a packfile" % filename
433 self._size = os.path.getsize(filename)
434 self._header_size = 12
435 assert self._size >= self._header_size, "%s is too small for a packfile (%d < %d)" % (filename, self._size, self._header_size)
436 self._file = open(self._filename, 'rb')
438 self._offset_cache = LRUSizeCache(1024*1024*20,
439 compute_size=compute_object_size)
444 def _read_header(self):
445 (version, self._num_objects) = read_pack_header(self._file)
446 self._file.seek(self._size-20)
447 (self._stored_checksum,) = read_pack_tail(self._file)
450 """Returns the number of objects in this pack."""
451 return self._num_objects
453 def calculate_checksum(self):
454 """Calculate the checksum for this pack."""
455 map, map_offset = simple_mmap(self._file, 0, self._size - 20)
457 return make_sha(map[map_offset:self._size-20]).digest()
461 def resolve_object(self, offset, type, obj, get_ref, get_offset=None):
462 """Resolve an object, possibly resolving deltas when necessary.
464 :return: Tuple with object type and contents.
466 if type not in (6, 7): # Not a delta
469 if get_offset is None:
470 get_offset = self.get_object_at
472 if type == 6: # offset delta
473 (delta_offset, delta) = obj
474 assert isinstance(delta_offset, int)
475 assert isinstance(delta, str)
476 base_offset = offset-delta_offset
477 type, base_obj = get_offset(base_offset)
478 assert isinstance(type, int)
479 elif type == 7: # ref delta
480 (basename, delta) = obj
481 assert isinstance(basename, str) and len(basename) == 20
482 assert isinstance(delta, str)
483 type, base_obj = get_ref(basename)
484 assert isinstance(type, int)
485 # Can't be a ofs delta, as we wouldn't know the base offset
488 type, base_text = self.resolve_object(base_offset, type, base_obj, get_ref)
489 if base_offset is not None:
490 self._offset_cache[base_offset] = type, base_text
491 ret = (type, apply_delta(base_text, delta))
494 def iterobjects(self, progress=None):
495 offset = self._header_size
497 map, _ = simple_mmap(self._file, 0, self._size)
500 (type, obj, total_size) = unpack_object(map, offset)
501 crc32 = zlib.crc32(map[offset:offset+total_size]) & 0xffffffff
502 yield offset, type, obj, crc32
509 def iterentries(self, ext_resolve_ref=None, progress=None):
511 postponed = defaultdict(list)
512 class Postpone(Exception):
513 """Raised to postpone delta resolving."""
515 def get_ref_text(sha):
516 assert len(sha) == 20
521 return ext_resolve_ref(sha)
524 raise Postpone, (sha, )
526 todo = chain(self.iterobjects(progress=progress), extra)
527 for (offset, type, obj, crc32) in todo:
528 assert isinstance(offset, int)
529 assert isinstance(type, int)
530 assert isinstance(obj, tuple) or isinstance(obj, str)
532 type, obj = self.resolve_object(offset, type, obj, get_ref_text)
533 except Postpone, (sha, ):
534 postponed[sha].append((offset, type, obj))
536 shafile = ShaFile.from_raw_string(type, obj)
537 sha = shafile.sha().digest()
538 found[sha] = (type, obj)
539 yield sha, offset, crc32
540 extra.extend(postponed.get(sha, []))
542 raise KeyError([sha_to_hex(h) for h in postponed.keys()])
544 def sorted_entries(self, resolve_ext_ref=None, progress=None):
545 ret = list(self.iterentries(resolve_ext_ref, progress=progress))
549 def create_index_v1(self, filename, resolve_ext_ref=None, progress=None):
550 entries = self.sorted_entries(resolve_ext_ref, progress=progress)
551 write_pack_index_v1(filename, entries, self.calculate_checksum())
553 def create_index_v2(self, filename, resolve_ext_ref=None, progress=None):
554 entries = self.sorted_entries(resolve_ext_ref, progress=progress)
555 write_pack_index_v2(filename, entries, self.calculate_checksum())
557 def get_stored_checksum(self):
558 return self._stored_checksum
561 return (self.calculate_checksum() == self.get_stored_checksum())
563 def get_object_at(self, offset):
564 """Given an offset in to the packfile return the object that is there.
566 Using the associated index the location of an object can be looked up, and
567 then the packfile can be asked directly for that object using this
570 if offset in self._offset_cache:
571 return self._offset_cache[offset]
572 assert isinstance(offset, long) or isinstance(offset, int),\
573 "offset was %r" % offset
574 assert offset >= self._header_size
575 map, map_offset = simple_mmap(self._file, offset, self._size-offset)
577 ret = unpack_object(map, map_offset)[:2]
583 class SHA1Writer(object):
585 def __init__(self, f):
587 self.sha1 = make_sha("")
589 def write(self, data):
590 self.sha1.update(data)
594 sha = self.sha1.digest()
595 assert len(sha) == 20
600 sha = self.write_sha()
608 def write_pack_object(f, type, object):
609 """Write pack object to a file.
611 :param f: File to write to
612 :param o: Object to write
613 :return: Tuple with offset at which the object was written, and crc32
617 if type == 6: # ref delta
618 (delta_base_offset, object) = object
619 elif type == 7: # offset delta
620 (basename, object) = object
622 c = (type << 4) | (size & 15)
625 packed_data_hdr += (chr(c | 0x80))
628 packed_data_hdr += chr(c)
629 if type == 6: # offset delta
630 ret = [delta_base_offset & 0x7f]
631 delta_base_offset >>= 7
632 while delta_base_offset:
633 delta_base_offset -= 1
634 ret.insert(0, 0x80 | (delta_base_offset & 0x7f))
635 delta_base_offset >>= 7
636 packed_data_hdr += "".join([chr(x) for x in ret])
637 elif type == 7: # ref delta
638 assert len(basename) == 20
639 packed_data_hdr += basename
640 packed_data = packed_data_hdr + zlib.compress(object)
642 return (f.tell(), (zlib.crc32(packed_data) & 0xffffffff))
645 def write_pack(filename, objects, num_objects):
646 f = open(filename + ".pack", 'w')
648 entries, data_sum = write_pack_data(f, objects, num_objects)
652 write_pack_index_v2(filename + ".idx", entries, data_sum)
655 def write_pack_data(f, objects, num_objects, window=10):
656 """Write a new pack file.
658 :param filename: The filename of the new pack file.
659 :param objects: List of objects to write (tuples with object and path)
660 :return: List with (name, offset, crc32 checksum) entries, pack checksum
662 recency = list(objects)
663 # FIXME: Somehow limit delta depth
664 # FIXME: Make thin-pack optional (its not used when cloning a pack)
665 # Build a list of objects ordered by the magic Linus heuristic
666 # This helps us find good objects to diff against us
668 for obj, path in recency:
669 magic.append( (obj.type, path, 1, -len(obj.as_raw_string()[1]), obj) )
671 # Build a map of objects and their index in magic - so we can find preceeding objects
674 for i in range(len(magic)):
675 offs[magic[i][4]] = i
679 f.write("PACK") # Pack header
680 f.write(struct.pack(">L", 2)) # Pack version
681 f.write(struct.pack(">L", num_objects)) # Number of objects in pack
682 for o, path in recency:
683 sha1 = o.sha().digest()
684 orig_t, raw = o.as_raw_string()
687 #for i in range(offs[o]-window, window):
688 # if i < 0 or i >= len(offs): continue
690 # if b.type != orig_t: continue
691 # _, base = b.as_raw_string()
692 # delta = create_delta(base, raw)
693 # if len(delta) < len(winner):
695 # t = 6 if magic[i][2] == 1 else 7
696 offset, crc32 = write_pack_object(f, t, winner)
697 entries.append((sha1, offset, crc32))
698 return entries, f.write_sha()
701 def write_pack_index_v1(filename, entries, pack_checksum):
702 """Write a new pack index file.
704 :param filename: The filename of the new pack index file.
705 :param entries: List of tuples with object name (sha), offset_in_pack, and
707 :param pack_checksum: Checksum of the pack file.
709 f = open(filename, 'w')
711 fan_out_table = defaultdict(lambda: 0)
712 for (name, offset, entry_checksum) in entries:
713 fan_out_table[ord(name[0])] += 1
715 for i in range(0x100):
716 f.write(struct.pack(">L", fan_out_table[i]))
717 fan_out_table[i+1] += fan_out_table[i]
718 for (name, offset, entry_checksum) in entries:
719 f.write(struct.pack(">L20s", offset, name))
720 assert len(pack_checksum) == 20
721 f.write(pack_checksum)
725 def create_delta(base_buf, target_buf):
726 """Use python difflib to work out how to transform base_buf to target_buf"""
727 assert isinstance(base_buf, str)
728 assert isinstance(target_buf, str)
731 def encode_size(size):
741 out_buf += encode_size(len(base_buf))
742 out_buf += encode_size(len(target_buf))
743 # write out delta opcodes
744 seq = difflib.SequenceMatcher(a=base_buf, b=target_buf)
745 for opcode, i1, i2, j1, j2 in seq.get_opcodes():
746 # Git patch opcodes don't care about deletes!
747 #if opcode == "replace" or opcode == "delete":
749 if opcode == "equal":
750 # If they are equal, unpacker will use data from base_buf
751 # Write out an opcode that says what range to use
757 scratch += chr(o >> i)
762 scratch += chr(s >> i)
766 if opcode == "replace" or opcode == "insert":
767 # If we are replacing a range or adding one, then we just
768 # output it to the stream (prefixed by its size)
773 out_buf += target_buf[o:o+127]
777 out_buf += target_buf[o:o+s]
781 def apply_delta(src_buf, delta):
782 """Based on the similar function in git's patch-delta.c.
784 :param src_buf: Source buffer
785 :param delta: Delta instructions
787 assert isinstance(src_buf, str), "was %r" % (src_buf,)
788 assert isinstance(delta, str)
791 delta_length = len(delta)
792 def get_delta_header_size(delta, index):
796 cmd = ord(delta[index])
798 size |= (cmd & ~0x80) << i
803 src_size, index = get_delta_header_size(delta, index)
804 dest_size, index = get_delta_header_size(delta, index)
805 assert src_size == len(src_buf), "%d vs %d" % (src_size, len(src_buf))
806 while index < delta_length:
807 cmd = ord(delta[index])
813 x = ord(delta[index])
815 cp_off |= x << (i * 8)
818 if cmd & (1 << (4+i)):
819 x = ord(delta[index])
821 cp_size |= x << (i * 8)
824 if (cp_off + cp_size < cp_size or
825 cp_off + cp_size > src_size or
826 cp_size > dest_size):
828 out.append(src_buf[cp_off:cp_off+cp_size])
830 out.append(delta[index:index+cmd])
833 raise ApplyDeltaError("Invalid opcode 0")
835 if index != delta_length:
836 raise ApplyDeltaError("delta not empty: %r" % delta[index:])
839 if dest_size != len(out):
840 raise ApplyDeltaError("dest size incorrect")
845 def write_pack_index_v2(filename, entries, pack_checksum):
846 """Write a new pack index file.
848 :param filename: The filename of the new pack index file.
849 :param entries: List of tuples with object name (sha), offset_in_pack, and
851 :param pack_checksum: Checksum of the pack file.
853 f = open(filename, 'w')
855 f.write('\377tOc') # Magic!
856 f.write(struct.pack(">L", 2))
857 fan_out_table = defaultdict(lambda: 0)
858 for (name, offset, entry_checksum) in entries:
859 fan_out_table[ord(name[0])] += 1
861 for i in range(0x100):
862 f.write(struct.pack(">L", fan_out_table[i]))
863 fan_out_table[i+1] += fan_out_table[i]
864 for (name, offset, entry_checksum) in entries:
866 for (name, offset, entry_checksum) in entries:
867 f.write(struct.pack(">L", entry_checksum))
868 for (name, offset, entry_checksum) in entries:
869 # FIXME: handle if MSBit is set in offset
870 f.write(struct.pack(">L", offset))
871 # FIXME: handle table for pack files > 8 Gb
872 assert len(pack_checksum) == 20
873 f.write(pack_checksum)
879 def __init__(self, basename):
880 self._basename = basename
881 self._data_path = self._basename + ".pack"
882 self._idx_path = self._basename + ".idx"
887 def from_objects(self, data, idx):
894 """The SHA over the SHAs of the objects in this pack."""
895 return self.idx.objects_sha1()
899 if self._data is None:
900 self._data = PackData(self._data_path)
901 assert len(self.idx) == len(self._data)
902 idx_stored_checksum = self.idx.get_pack_checksum()
903 data_stored_checksum = self._data.get_stored_checksum()
904 if idx_stored_checksum != data_stored_checksum:
905 raise ChecksumMismatch(sha_to_hex(idx_stored_checksum),
906 sha_to_hex(data_stored_checksum))
911 if self._idx is None:
912 self._idx = load_pack_index(self._idx_path)
916 if self._data is not None:
920 def __eq__(self, other):
921 return type(self) == type(other) and self.idx == other.idx
924 """Number of entries in this pack."""
928 return "Pack(%r)" % self._basename
931 """Iterate over all the sha1s of the objects in this pack."""
932 return iter(self.idx)
935 if not self.idx.check():
937 if not self.data.check():
941 def get_stored_checksum(self):
942 return self.data.get_stored_checksum()
944 def __contains__(self, sha1):
945 """Check whether this pack contains a particular SHA1."""
947 self.idx.object_index(sha1)
952 def get_raw(self, sha1, resolve_ref=None):
953 offset = self.idx.object_index(sha1)
954 obj_type, obj = self.data.get_object_at(offset)
955 if type(offset) is long:
957 if resolve_ref is None:
958 resolve_ref = self.get_raw
959 return self.data.resolve_object(offset, obj_type, obj, resolve_ref)
961 def __getitem__(self, sha1):
962 """Retrieve the specified SHA1."""
963 type, uncomp = self.get_raw(sha1)
964 return ShaFile.from_raw_string(type, uncomp)
966 def iterobjects(self, get_raw=None):
968 get_raw = self.get_raw
969 for offset, type, obj, crc32 in self.data.iterobjects():
970 assert isinstance(offset, int)
971 yield ShaFile.from_raw_string(
972 *self.data.resolve_object(offset, type, obj, get_raw))
975 def load_packs(path):
976 if not os.path.exists(path):
978 for name in os.listdir(path):
979 if name.startswith("pack-") and name.endswith(".pack"):
980 yield Pack(os.path.join(path, name[:-len(".pack")]))
984 from dulwich._pack import apply_delta, bisect_find_sha