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 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)
437 self._offset_cache = LRUSizeCache(1024*1024*100,
438 compute_size=compute_object_size)
440 def _read_header(self):
441 f = open(self._filename, 'rb')
443 (version, self._num_objects) = \
445 f.seek(self._size-20)
446 (self._stored_checksum,) = read_pack_tail(f)
451 """Returns the number of objects in this pack."""
452 return self._num_objects
454 def calculate_checksum(self):
455 """Calculate the checksum for this pack."""
456 f = open(self._filename, 'rb')
458 map, map_offset = simple_mmap(f, 0, self._size - 20)
459 return make_sha(map[map_offset:self._size-20]).digest()
463 def resolve_object(self, offset, type, obj, get_ref, get_offset=None):
464 """Resolve an object, possibly resolving deltas when necessary.
466 :return: Tuple with object type and contents.
468 if type not in (6, 7): # Not a delta
471 if get_offset is None:
472 get_offset = self.get_object_at
474 if type == 6: # offset delta
475 (delta_offset, delta) = obj
476 assert isinstance(delta_offset, int)
477 assert isinstance(delta, str)
478 base_offset = offset-delta_offset
479 type, base_obj = get_offset(base_offset)
480 assert isinstance(type, int)
481 elif type == 7: # ref delta
482 (basename, delta) = obj
483 assert isinstance(basename, str) and len(basename) == 20
484 assert isinstance(delta, str)
485 type, base_obj = get_ref(basename)
486 assert isinstance(type, int)
487 # Can't be a ofs delta, as we wouldn't know the base offset
490 type, base_text = self.resolve_object(base_offset, type, base_obj, get_ref)
491 if base_offset is not None:
492 self._offset_cache[base_offset] = type, base_text
493 ret = (type, apply_delta(base_text, delta))
496 def iterobjects(self):
497 offset = self._header_size
498 f = open(self._filename, 'rb')
500 map, _ = simple_mmap(f, 0, self._size)
502 (type, obj, total_size) = unpack_object(map, offset)
503 crc32 = zlib.crc32(map[offset:offset+total_size]) & 0xffffffff
504 yield offset, type, obj, crc32
508 def iterentries(self, ext_resolve_ref=None):
510 postponed = defaultdict(list)
511 class Postpone(Exception):
512 """Raised to postpone delta resolving."""
514 def get_ref_text(sha):
519 return ext_resolve_ref(sha)
522 raise Postpone, (sha, )
523 todo = list(self.iterobjects())
525 (offset, type, obj, crc32) = todo.pop(0)
526 assert isinstance(offset, int)
527 assert isinstance(type, int)
528 assert isinstance(obj, tuple) or isinstance(obj, str)
530 type, obj = self.resolve_object(offset, type, obj, get_ref_text)
531 except Postpone, (sha, ):
532 postponed[sha].append((offset, type, obj))
534 shafile = ShaFile.from_raw_string(type, obj)
535 sha = shafile.sha().digest()
536 found[sha] = (type, obj)
537 yield sha, offset, crc32
538 todo += postponed.get(sha, [])
540 raise KeyError([sha_to_hex(h) for h in postponed.keys()])
542 def sorted_entries(self, resolve_ext_ref=None):
543 ret = list(self.iterentries(resolve_ext_ref))
547 def create_index_v1(self, filename, resolve_ext_ref=None):
548 entries = self.sorted_entries(resolve_ext_ref)
549 write_pack_index_v1(filename, entries, self.calculate_checksum())
551 def create_index_v2(self, filename, resolve_ext_ref=None):
552 entries = self.sorted_entries(resolve_ext_ref)
553 write_pack_index_v2(filename, entries, self.calculate_checksum())
555 def get_stored_checksum(self):
556 return self._stored_checksum
559 return (self.calculate_checksum() == self.get_stored_checksum())
561 def get_object_at(self, offset):
562 """Given an offset in to the packfile return the object that is there.
564 Using the associated index the location of an object can be looked up, and
565 then the packfile can be asked directly for that object using this
568 if offset in self._offset_cache:
569 return self._offset_cache[offset]
570 assert isinstance(offset, long) or isinstance(offset, int),\
571 "offset was %r" % offset
572 assert offset >= self._header_size
573 f = open(self._filename, 'rb')
575 map, map_offset = simple_mmap(f, offset, self._size-offset)
576 ret = unpack_object(map, map_offset)[:2]
582 class SHA1Writer(object):
584 def __init__(self, f):
586 self.sha1 = make_sha("")
588 def write(self, data):
589 self.sha1.update(data)
593 sha = self.sha1.digest()
594 assert len(sha) == 20
599 sha = self.write_sha()
607 def write_pack_object(f, type, object):
608 """Write pack object to a file.
610 :param f: File to write to
611 :param o: Object to write
612 :return: Tuple with offset at which the object was written, and crc32
616 if type == 6: # ref delta
617 (delta_base_offset, object) = object
618 elif type == 7: # offset delta
619 (basename, object) = object
621 c = (type << 4) | (size & 15)
624 packed_data_hdr += (chr(c | 0x80))
627 packed_data_hdr += chr(c)
628 if type == 6: # offset delta
629 ret = [delta_base_offset & 0x7f]
630 delta_base_offset >>= 7
631 while delta_base_offset:
632 delta_base_offset -= 1
633 ret.insert(0, 0x80 | (delta_base_offset & 0x7f))
634 delta_base_offset >>= 7
635 packed_data_hdr += "".join([chr(x) for x in ret])
636 elif type == 7: # ref delta
637 assert len(basename) == 20
638 packed_data_hdr += basename
639 packed_data = packed_data_hdr + zlib.compress(object)
641 return (f.tell(), (zlib.crc32(packed_data) & 0xffffffff))
644 def write_pack(filename, objects, num_objects):
645 f = open(filename + ".pack", 'w')
647 entries, data_sum = write_pack_data(f, objects, num_objects)
651 write_pack_index_v2(filename + ".idx", entries, data_sum)
654 def write_pack_data(f, objects, num_objects, window=10):
655 """Write a new pack file.
657 :param filename: The filename of the new pack file.
658 :param objects: List of objects to write (tuples with object and path)
659 :return: List with (name, offset, crc32 checksum) entries, pack checksum
661 recency = list(objects)
662 # FIXME: Somehow limit delta depth
663 # FIXME: Make thin-pack optional (its not used when cloning a pack)
664 # Build a list of objects ordered by the magic Linus heuristic
665 # This helps us find good objects to diff against us
667 for obj, path in recency:
668 magic.append( (obj.type, path, 1, -len(obj.as_raw_string()[1]), obj) )
670 # Build a map of objects and their index in magic - so we can find preceeding objects
673 for i in range(len(magic)):
674 offs[magic[i][4]] = i
678 f.write("PACK") # Pack header
679 f.write(struct.pack(">L", 2)) # Pack version
680 f.write(struct.pack(">L", num_objects)) # Number of objects in pack
681 for o, path in recency:
682 sha1 = o.sha().digest()
683 orig_t, raw = o.as_raw_string()
686 #for i in range(offs[o]-window, window):
687 # if i < 0 or i >= len(offs): continue
689 # if b.type != orig_t: continue
690 # _, base = b.as_raw_string()
691 # delta = create_delta(base, raw)
692 # if len(delta) < len(winner):
694 # t = 6 if magic[i][2] == 1 else 7
695 offset, crc32 = write_pack_object(f, t, winner)
696 entries.append((sha1, offset, crc32))
697 return entries, f.write_sha()
700 def write_pack_index_v1(filename, entries, pack_checksum):
701 """Write a new pack index file.
703 :param filename: The filename of the new pack index file.
704 :param entries: List of tuples with object name (sha), offset_in_pack, and
706 :param pack_checksum: Checksum of the pack file.
708 f = open(filename, 'w')
710 fan_out_table = defaultdict(lambda: 0)
711 for (name, offset, entry_checksum) in entries:
712 fan_out_table[ord(name[0])] += 1
714 for i in range(0x100):
715 f.write(struct.pack(">L", fan_out_table[i]))
716 fan_out_table[i+1] += fan_out_table[i]
717 for (name, offset, entry_checksum) in entries:
718 f.write(struct.pack(">L20s", offset, name))
719 assert len(pack_checksum) == 20
720 f.write(pack_checksum)
724 def create_delta(base_buf, target_buf):
725 """Use python difflib to work out how to transform base_buf to target_buf"""
726 assert isinstance(base_buf, str)
727 assert isinstance(target_buf, str)
730 def encode_size(size):
740 out_buf += encode_size(len(base_buf))
741 out_buf += encode_size(len(target_buf))
742 # write out delta opcodes
743 seq = difflib.SequenceMatcher(a=base_buf, b=target_buf)
744 for opcode, i1, i2, j1, j2 in seq.get_opcodes():
745 # Git patch opcodes don't care about deletes!
746 #if opcode == "replace" or opcode == "delete":
748 if opcode == "equal":
749 # If they are equal, unpacker will use data from base_buf
750 # Write out an opcode that says what range to use
756 scratch += chr(o >> i)
761 scratch += chr(s >> i)
765 if opcode == "replace" or opcode == "insert":
766 # If we are replacing a range or adding one, then we just
767 # output it to the stream (prefixed by its size)
772 out_buf += target_buf[o:o+127]
776 out_buf += target_buf[o:o+s]
780 def apply_delta(src_buf, delta):
781 """Based on the similar function in git's patch-delta.c.
783 :param src_buf: Source buffer
784 :param delta: Delta instructions
786 assert isinstance(src_buf, str), "was %r" % (src_buf,)
787 assert isinstance(delta, str)
790 delta_length = len(delta)
791 def get_delta_header_size(delta, index):
795 cmd = ord(delta[index])
797 size |= (cmd & ~0x80) << i
802 src_size, index = get_delta_header_size(delta, index)
803 dest_size, index = get_delta_header_size(delta, index)
804 assert src_size == len(src_buf), "%d vs %d" % (src_size, len(src_buf))
805 while index < delta_length:
806 cmd = ord(delta[index])
812 x = ord(delta[index])
814 cp_off |= x << (i * 8)
817 if cmd & (1 << (4+i)):
818 x = ord(delta[index])
820 cp_size |= x << (i * 8)
823 if (cp_off + cp_size < cp_size or
824 cp_off + cp_size > src_size or
825 cp_size > dest_size):
827 out.append(src_buf[cp_off:cp_off+cp_size])
829 out.append(delta[index:index+cmd])
832 raise ApplyDeltaError("Invalid opcode 0")
834 if index != delta_length:
835 raise ApplyDeltaError("delta not empty: %r" % delta[index:])
838 if dest_size != len(out):
839 raise ApplyDeltaError("dest size incorrect")
844 def write_pack_index_v2(filename, entries, pack_checksum):
845 """Write a new pack index file.
847 :param filename: The filename of the new pack index file.
848 :param entries: List of tuples with object name (sha), offset_in_pack, and
850 :param pack_checksum: Checksum of the pack file.
852 f = open(filename, 'w')
854 f.write('\377tOc') # Magic!
855 f.write(struct.pack(">L", 2))
856 fan_out_table = defaultdict(lambda: 0)
857 for (name, offset, entry_checksum) in entries:
858 fan_out_table[ord(name[0])] += 1
860 for i in range(0x100):
861 f.write(struct.pack(">L", fan_out_table[i]))
862 fan_out_table[i+1] += fan_out_table[i]
863 for (name, offset, entry_checksum) in entries:
865 for (name, offset, entry_checksum) in entries:
866 f.write(struct.pack(">L", entry_checksum))
867 for (name, offset, entry_checksum) in entries:
868 # FIXME: handle if MSBit is set in offset
869 f.write(struct.pack(">L", offset))
870 # FIXME: handle table for pack files > 8 Gb
871 assert len(pack_checksum) == 20
872 f.write(pack_checksum)
878 def __init__(self, basename):
879 self._basename = basename
880 self._data_path = self._basename + ".pack"
881 self._idx_path = self._basename + ".idx"
886 """The SHA over the SHAs of the objects in this pack."""
887 return self.idx.objects_sha1()
891 if self._data is None:
892 self._data = PackData(self._data_path)
893 assert len(self.idx) == len(self._data)
894 idx_stored_checksum = self.idx.get_pack_checksum()
895 data_stored_checksum = self._data.get_stored_checksum()
896 if idx_stored_checksum != data_stored_checksum:
897 raise ChecksumMismatch(sha_to_hex(idx_stored_checksum),
898 sha_to_hex(data_stored_checksum))
903 if self._idx is None:
904 self._idx = load_pack_index(self._idx_path)
908 if self._data is not None:
912 def __eq__(self, other):
913 return type(self) == type(other) and self.idx == other.idx
916 """Number of entries in this pack."""
920 return "Pack(%r)" % self._basename
923 """Iterate over all the sha1s of the objects in this pack."""
924 return iter(self.idx)
927 if not self.idx.check():
929 if not self.data.check():
933 def get_stored_checksum(self):
934 return self.data.get_stored_checksum()
936 def __contains__(self, sha1):
937 """Check whether this pack contains a particular SHA1."""
938 return (self.idx.object_index(sha1) is not None)
940 def get_raw(self, sha1, resolve_ref=None):
941 offset = self.idx.object_index(sha1)
944 type, obj = self.data.get_object_at(offset)
945 if isinstance(offset, long):
947 if resolve_ref is None:
948 resolve_ref = self.get_raw
949 assert isinstance(offset, int)
950 return self.data.resolve_object(offset, type, obj, resolve_ref)
952 def __getitem__(self, sha1):
953 """Retrieve the specified SHA1."""
954 type, uncomp = self.get_raw(sha1)
955 return ShaFile.from_raw_string(type, uncomp)
957 def iterobjects(self, get_raw=None):
959 get_raw = self.get_raw
960 for offset, type, obj, crc32 in self.data.iterobjects():
961 assert isinstance(offset, int)
962 yield ShaFile.from_raw_string(
963 *self.data.resolve_object(offset, type, obj, get_raw))
966 def load_packs(path):
967 if not os.path.exists(path):
969 for name in os.listdir(path):
970 if name.startswith("pack-") and name.endswith(".pack"):
971 yield Pack(os.path.join(path, name[:-len(".pack")]))
975 from dulwich._pack import apply_delta, bisect_find_sha