2
0

pack.py 45 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391
  1. # pack.py -- For dealing with packed git objects.
  2. # Copyright (C) 2007 James Westby <jw+debian@jameswestby.net>
  3. # Copyright (C) 2008-2009 Jelmer Vernooij <jelmer@samba.org>
  4. #
  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.
  9. #
  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.
  14. #
  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,
  18. # MA 02110-1301, USA.
  19. """Classes for dealing with packed git objects.
  20. A pack is a compact representation of a bunch of objects, stored
  21. using deltas where possible.
  22. They have two parts, the pack file, which stores the data, and an index
  23. that tells you where the data is.
  24. To find an object you look in all of the index files 'til you find a
  25. match for the object name. You then use the pointer got from this as
  26. a pointer in to the corresponding packfile.
  27. """
  28. try:
  29. from collections import defaultdict
  30. except ImportError:
  31. from misc import defaultdict
  32. from cStringIO import (
  33. StringIO,
  34. )
  35. from collections import (
  36. deque,
  37. )
  38. import difflib
  39. from itertools import (
  40. chain,
  41. imap,
  42. izip,
  43. )
  44. import mmap
  45. import os
  46. import struct
  47. try:
  48. from struct import unpack_from
  49. except ImportError:
  50. from dulwich.misc import unpack_from
  51. import sys
  52. import zlib
  53. from dulwich.errors import (
  54. ApplyDeltaError,
  55. ChecksumMismatch,
  56. )
  57. from dulwich.file import GitFile
  58. from dulwich.lru_cache import (
  59. LRUSizeCache,
  60. )
  61. from dulwich.misc import (
  62. make_sha,
  63. SEEK_END,
  64. )
  65. from dulwich.objects import (
  66. ShaFile,
  67. hex_to_sha,
  68. sha_to_hex,
  69. object_header,
  70. )
  71. supports_mmap_offset = (sys.version_info[0] >= 3 or
  72. (sys.version_info[0] == 2 and sys.version_info[1] >= 6))
  73. OFS_DELTA = 6
  74. REF_DELTA = 7
  75. DELTA_TYPES = (OFS_DELTA, REF_DELTA)
  76. def take_msb_bytes(read):
  77. """Read bytes marked with most significant bit.
  78. :param read: Read function
  79. """
  80. ret = []
  81. while len(ret) == 0 or ret[-1] & 0x80:
  82. ret.append(ord(read(1)))
  83. return ret
  84. def read_zlib_chunks(read_some, dec_size, buffer_size=4096):
  85. """Read zlib data from a buffer.
  86. This function requires that the buffer have additional data following the
  87. compressed data, which is guaranteed to be the case for git pack files.
  88. :param read_some: Read function that returns at least one byte, but may
  89. return less than the requested size
  90. :param dec_size: Expected size of the decompressed buffer
  91. :param buffer_size: Size of the read buffer
  92. :return: Tuple with list of chunks, length of compressed data length and
  93. and unused read data.
  94. :raise zlib.error: if a decompression error occurred.
  95. """
  96. if dec_size <= -1:
  97. raise ValueError("non-negative zlib data stream size expected")
  98. obj = zlib.decompressobj()
  99. ret = []
  100. fed = 0
  101. size = 0
  102. while obj.unused_data == "":
  103. add = read_some(buffer_size)
  104. if not add:
  105. raise zlib.error("EOF before end of zlib stream")
  106. fed += len(add)
  107. decomp = obj.decompress(add)
  108. size += len(decomp)
  109. ret.append(decomp)
  110. if size != dec_size:
  111. raise zlib.error("decompressed data does not match expected size")
  112. comp_len = fed - len(obj.unused_data)
  113. return ret, comp_len, obj.unused_data
  114. def iter_sha1(iter):
  115. """Return the hexdigest of the SHA1 over a set of names.
  116. :param iter: Iterator over string objects
  117. :return: 40-byte hex sha1 digest
  118. """
  119. sha1 = make_sha()
  120. for name in iter:
  121. sha1.update(name)
  122. return sha1.hexdigest()
  123. def load_pack_index(path):
  124. """Load an index file by path.
  125. :param filename: Path to the index file
  126. :return: A PackIndex loaded from the given path
  127. """
  128. f = GitFile(path, 'rb')
  129. try:
  130. return load_pack_index_file(path, f)
  131. finally:
  132. f.close()
  133. def _load_file_contents(f, size=None):
  134. fileno = getattr(f, 'fileno', None)
  135. # Attempt to use mmap if possible
  136. if fileno is not None:
  137. fd = f.fileno()
  138. if size is None:
  139. size = os.fstat(fd).st_size
  140. try:
  141. contents = mmap.mmap(fd, size, access=mmap.ACCESS_READ)
  142. except mmap.error:
  143. # Perhaps a socket?
  144. pass
  145. else:
  146. return contents, size
  147. contents = f.read()
  148. size = len(contents)
  149. return contents, size
  150. def load_pack_index_file(path, f):
  151. """Load an index file from a file-like object.
  152. :param path: Path for the index file
  153. :param f: File-like object
  154. :return: A PackIndex loaded from the given file
  155. """
  156. contents, size = _load_file_contents(f)
  157. if contents[:4] == '\377tOc':
  158. version = struct.unpack(">L", contents[4:8])[0]
  159. if version == 2:
  160. return PackIndex2(path, file=f, contents=contents,
  161. size=size)
  162. else:
  163. raise KeyError("Unknown pack index format %d" % version)
  164. else:
  165. return PackIndex1(path, file=f, contents=contents, size=size)
  166. def bisect_find_sha(start, end, sha, unpack_name):
  167. """Find a SHA in a data blob with sorted SHAs.
  168. :param start: Start index of range to search
  169. :param end: End index of range to search
  170. :param sha: Sha to find
  171. :param unpack_name: Callback to retrieve SHA by index
  172. :return: Index of the SHA, or None if it wasn't found
  173. """
  174. assert start <= end
  175. while start <= end:
  176. i = (start + end)/2
  177. file_sha = unpack_name(i)
  178. x = cmp(file_sha, sha)
  179. if x < 0:
  180. start = i + 1
  181. elif x > 0:
  182. end = i - 1
  183. else:
  184. return i
  185. return None
  186. class PackIndex(object):
  187. """An index in to a packfile.
  188. Given a sha id of an object a pack index can tell you the location in the
  189. packfile of that object if it has it.
  190. To do the loop it opens the file, and indexes first 256 4 byte groups
  191. with the first byte of the sha id. The value in the four byte group indexed
  192. is the end of the group that shares the same starting byte. Subtract one
  193. from the starting byte and index again to find the start of the group.
  194. The values are sorted by sha id within the group, so do the math to find
  195. the start and end offset and then bisect in to find if the value is present.
  196. """
  197. def __init__(self, filename, file=None, contents=None, size=None):
  198. """Create a pack index object.
  199. Provide it with the name of the index file to consider, and it will map
  200. it whenever required.
  201. """
  202. self._filename = filename
  203. # Take the size now, so it can be checked each time we map the file to
  204. # ensure that it hasn't changed.
  205. if file is None:
  206. self._file = GitFile(filename, 'rb')
  207. else:
  208. self._file = file
  209. if contents is None:
  210. self._contents, self._size = _load_file_contents(file, size)
  211. else:
  212. self._contents, self._size = (contents, size)
  213. def __eq__(self, other):
  214. if not isinstance(other, PackIndex):
  215. return False
  216. if self._fan_out_table != other._fan_out_table:
  217. return False
  218. for (name1, _, _), (name2, _, _) in izip(self.iterentries(),
  219. other.iterentries()):
  220. if name1 != name2:
  221. return False
  222. return True
  223. def __ne__(self, other):
  224. return not self.__eq__(other)
  225. def close(self):
  226. self._file.close()
  227. def __len__(self):
  228. """Return the number of entries in this pack index."""
  229. return self._fan_out_table[-1]
  230. def _unpack_entry(self, i):
  231. """Unpack the i-th entry in the index file.
  232. :return: Tuple with object name (SHA), offset in pack file and CRC32
  233. checksum (if known).
  234. """
  235. raise NotImplementedError(self._unpack_entry)
  236. def _unpack_name(self, i):
  237. """Unpack the i-th name from the index file."""
  238. raise NotImplementedError(self._unpack_name)
  239. def _unpack_offset(self, i):
  240. """Unpack the i-th object offset from the index file."""
  241. raise NotImplementedError(self._unpack_offset)
  242. def _unpack_crc32_checksum(self, i):
  243. """Unpack the crc32 checksum for the i-th object from the index file."""
  244. raise NotImplementedError(self._unpack_crc32_checksum)
  245. def __iter__(self):
  246. """Iterate over the SHAs in this pack."""
  247. return imap(sha_to_hex, self._itersha())
  248. def _itersha(self):
  249. for i in range(len(self)):
  250. yield self._unpack_name(i)
  251. def objects_sha1(self):
  252. """Return the hex SHA1 over all the shas of all objects in this pack.
  253. :note: This is used for the filename of the pack.
  254. """
  255. return iter_sha1(self._itersha())
  256. def iterentries(self):
  257. """Iterate over the entries in this pack index.
  258. :yields: tuples with object name, offset in packfile and crc32 checksum.
  259. """
  260. for i in range(len(self)):
  261. yield self._unpack_entry(i)
  262. def _read_fan_out_table(self, start_offset):
  263. ret = []
  264. for i in range(0x100):
  265. fanout_entry = self._contents[start_offset+i*4:start_offset+(i+1)*4]
  266. ret.append(struct.unpack(">L", fanout_entry)[0])
  267. return ret
  268. def check(self):
  269. """Check that the stored checksum matches the actual checksum."""
  270. actual = self.calculate_checksum()
  271. stored = self.get_stored_checksum()
  272. if actual != stored:
  273. raise ChecksumMismatch(stored, actual)
  274. def calculate_checksum(self):
  275. """Calculate the SHA1 checksum over this pack index.
  276. :return: This is a 20-byte binary digest
  277. """
  278. return make_sha(self._contents[:-20]).digest()
  279. def get_pack_checksum(self):
  280. """Return the SHA1 checksum stored for the corresponding packfile.
  281. :return: 20-byte binary digest
  282. """
  283. return str(self._contents[-40:-20])
  284. def get_stored_checksum(self):
  285. """Return the SHA1 checksum stored for this index.
  286. :return: 20-byte binary digest
  287. """
  288. return str(self._contents[-20:])
  289. def object_index(self, sha):
  290. """Return the index in to the corresponding packfile for the object.
  291. Given the name of an object it will return the offset that object
  292. lives at within the corresponding pack file. If the pack file doesn't
  293. have the object then None will be returned.
  294. """
  295. if len(sha) == 40:
  296. sha = hex_to_sha(sha)
  297. return self._object_index(sha)
  298. def _object_index(self, sha):
  299. """See object_index.
  300. :param sha: A *binary* SHA string. (20 characters long)_
  301. """
  302. assert len(sha) == 20
  303. idx = ord(sha[0])
  304. if idx == 0:
  305. start = 0
  306. else:
  307. start = self._fan_out_table[idx-1]
  308. end = self._fan_out_table[idx]
  309. i = bisect_find_sha(start, end, sha, self._unpack_name)
  310. if i is None:
  311. raise KeyError(sha)
  312. return self._unpack_offset(i)
  313. class PackIndex1(PackIndex):
  314. """Version 1 Pack Index."""
  315. def __init__(self, filename, file=None, contents=None, size=None):
  316. PackIndex.__init__(self, filename, file, contents, size)
  317. self.version = 1
  318. self._fan_out_table = self._read_fan_out_table(0)
  319. def _unpack_entry(self, i):
  320. (offset, name) = unpack_from(">L20s", self._contents,
  321. (0x100 * 4) + (i * 24))
  322. return (name, offset, None)
  323. def _unpack_name(self, i):
  324. offset = (0x100 * 4) + (i * 24) + 4
  325. return self._contents[offset:offset+20]
  326. def _unpack_offset(self, i):
  327. offset = (0x100 * 4) + (i * 24)
  328. return unpack_from(">L", self._contents, offset)[0]
  329. def _unpack_crc32_checksum(self, i):
  330. # Not stored in v1 index files
  331. return None
  332. class PackIndex2(PackIndex):
  333. """Version 2 Pack Index."""
  334. def __init__(self, filename, file=None, contents=None, size=None):
  335. PackIndex.__init__(self, filename, file, contents, size)
  336. assert self._contents[:4] == '\377tOc', "Not a v2 pack index file"
  337. (self.version, ) = unpack_from(">L", self._contents, 4)
  338. assert self.version == 2, "Version was %d" % self.version
  339. self._fan_out_table = self._read_fan_out_table(8)
  340. self._name_table_offset = 8 + 0x100 * 4
  341. self._crc32_table_offset = self._name_table_offset + 20 * len(self)
  342. self._pack_offset_table_offset = (self._crc32_table_offset +
  343. 4 * len(self))
  344. def _unpack_entry(self, i):
  345. return (self._unpack_name(i), self._unpack_offset(i),
  346. self._unpack_crc32_checksum(i))
  347. def _unpack_name(self, i):
  348. offset = self._name_table_offset + i * 20
  349. return self._contents[offset:offset+20]
  350. def _unpack_offset(self, i):
  351. offset = self._pack_offset_table_offset + i * 4
  352. return unpack_from(">L", self._contents, offset)[0]
  353. def _unpack_crc32_checksum(self, i):
  354. return unpack_from(">L", self._contents,
  355. self._crc32_table_offset + i * 4)[0]
  356. def read_pack_header(read):
  357. """Read the header of a pack file.
  358. :param read: Read function
  359. :return: Tuple with pack version and number of objects
  360. """
  361. header = read(12)
  362. assert header[:4] == "PACK"
  363. (version,) = unpack_from(">L", header, 4)
  364. assert version in (2, 3), "Version was %d" % version
  365. (num_objects,) = unpack_from(">L", header, 8)
  366. return (version, num_objects)
  367. def chunks_length(chunks):
  368. return sum(imap(len, chunks))
  369. def unpack_object(read_all, read_some=None):
  370. """Unpack a Git object.
  371. :param read_all: Read function that blocks until the number of requested
  372. bytes are read.
  373. :param read_some: Read function that returns at least one byte, but may not
  374. return the number of bytes requested.
  375. :return: tuple with type, uncompressed data, compressed size and tail data.
  376. """
  377. if read_some is None:
  378. read_some = read_all
  379. bytes = take_msb_bytes(read_all)
  380. type = (bytes[0] >> 4) & 0x07
  381. size = bytes[0] & 0x0f
  382. for i, byte in enumerate(bytes[1:]):
  383. size += (byte & 0x7f) << ((i * 7) + 4)
  384. raw_base = len(bytes)
  385. if type == OFS_DELTA:
  386. bytes = take_msb_bytes(read_all)
  387. raw_base += len(bytes)
  388. assert not (bytes[-1] & 0x80)
  389. delta_base_offset = bytes[0] & 0x7f
  390. for byte in bytes[1:]:
  391. delta_base_offset += 1
  392. delta_base_offset <<= 7
  393. delta_base_offset += (byte & 0x7f)
  394. uncomp, comp_len, unused = read_zlib_chunks(read_some, size)
  395. assert size == chunks_length(uncomp)
  396. return type, (delta_base_offset, uncomp), comp_len+raw_base, unused
  397. elif type == REF_DELTA:
  398. basename = read_all(20)
  399. raw_base += 20
  400. uncomp, comp_len, unused = read_zlib_chunks(read_some, size)
  401. assert size == chunks_length(uncomp)
  402. return type, (basename, uncomp), comp_len+raw_base, unused
  403. else:
  404. uncomp, comp_len, unused = read_zlib_chunks(read_some, size)
  405. assert chunks_length(uncomp) == size
  406. return type, uncomp, comp_len+raw_base, unused
  407. def _compute_object_size((num, obj)):
  408. """Compute the size of a unresolved object for use with LRUSizeCache."""
  409. if num in DELTA_TYPES:
  410. return chunks_length(obj[1])
  411. return chunks_length(obj)
  412. class PackStreamReader(object):
  413. """Class to read a pack stream.
  414. The pack is read from a ReceivableProtocol using read() or recv() as
  415. appropriate.
  416. """
  417. def __init__(self, read_all, read_some=None):
  418. self.read_all = read_all
  419. if read_some is None:
  420. self.read_some = read_all
  421. else:
  422. self.read_some = read_some
  423. self.sha = make_sha()
  424. self._offset = 0
  425. self._rbuf = StringIO()
  426. # trailer is a deque to avoid memory allocation on small reads
  427. self._trailer = deque()
  428. def _read(self, read, size):
  429. """Read up to size bytes using the given callback.
  430. As a side effect, update the verifier's hash (excluding the last 20
  431. bytes read) and write through to the output file.
  432. :param read: The read callback to read from.
  433. :param size: The maximum number of bytes to read; the particular
  434. behavior is callback-specific.
  435. """
  436. data = read(size)
  437. # maintain a trailer of the last 20 bytes we've read
  438. n = len(data)
  439. self._offset += n
  440. tn = len(self._trailer)
  441. if n >= 20:
  442. to_pop = tn
  443. to_add = 20
  444. else:
  445. to_pop = max(n + tn - 20, 0)
  446. to_add = n
  447. for _ in xrange(to_pop):
  448. self.sha.update(self._trailer.popleft())
  449. self._trailer.extend(data[-to_add:])
  450. # hash everything but the trailer
  451. self.sha.update(data[:-to_add])
  452. return data
  453. def _buf_len(self):
  454. buf = self._rbuf
  455. start = buf.tell()
  456. buf.seek(0, SEEK_END)
  457. end = buf.tell()
  458. buf.seek(start)
  459. return end - start
  460. @property
  461. def offset(self):
  462. return self._offset - self._buf_len()
  463. def read(self, size):
  464. """Read, blocking until size bytes are read."""
  465. buf_len = self._buf_len()
  466. if buf_len >= size:
  467. return self._rbuf.read(size)
  468. buf_data = self._rbuf.read()
  469. self._rbuf = StringIO()
  470. return buf_data + self._read(self.read_all, size - buf_len)
  471. def recv(self, size):
  472. """Read up to size bytes, blocking until one byte is read."""
  473. buf_len = self._buf_len()
  474. if buf_len:
  475. data = self._rbuf.read(size)
  476. if size >= buf_len:
  477. self._rbuf = StringIO()
  478. return data
  479. return self._read(self.read_some, size)
  480. def __len__(self):
  481. return self._num_objects
  482. def read_objects(self):
  483. """Read the objects in this pack file.
  484. :raise AssertionError: if there is an error in the pack format.
  485. :raise ChecksumMismatch: if the checksum of the pack contents does not
  486. match the checksum in the pack trailer.
  487. :raise zlib.error: if an error occurred during zlib decompression.
  488. :raise IOError: if an error occurred writing to the output file.
  489. """
  490. pack_version, self._num_objects = read_pack_header(self.read)
  491. for i in xrange(self._num_objects):
  492. type, uncomp, comp_len, unused = unpack_object(self.read, self.recv)
  493. yield type, uncomp, comp_len
  494. # prepend any unused data to current read buffer
  495. buf = StringIO()
  496. buf.write(unused)
  497. buf.write(self._rbuf.read())
  498. buf.seek(0)
  499. self._rbuf = buf
  500. pack_sha = sha_to_hex(''.join([c for c in self._trailer]))
  501. calculated_sha = self.sha.hexdigest()
  502. if pack_sha != calculated_sha:
  503. raise ChecksumMismatch(pack_sha, calculated_sha)
  504. class PackObjectIterator(object):
  505. def __init__(self, pack, progress=None):
  506. self.i = 0
  507. self.offset = pack._header_size
  508. self.num = len(pack)
  509. self.map = pack._file
  510. self._progress = progress
  511. def __iter__(self):
  512. return self
  513. def __len__(self):
  514. return self.num
  515. def next(self):
  516. if self.i == self.num:
  517. raise StopIteration
  518. self.map.seek(self.offset)
  519. (type, obj, total_size, unused) = unpack_object(self.map.read)
  520. self.map.seek(self.offset)
  521. crc32 = zlib.crc32(self.map.read(total_size)) & 0xffffffff
  522. ret = (self.offset, type, obj, crc32)
  523. self.offset += total_size
  524. if self._progress is not None:
  525. self._progress(self.i, self.num)
  526. self.i+=1
  527. return ret
  528. def obj_sha(type, chunks):
  529. """Compute the SHA for a numeric type and object chunks."""
  530. sha = make_sha()
  531. sha.update(object_header(type, chunks_length(chunks)))
  532. for chunk in chunks:
  533. sha.update(chunk)
  534. return sha.digest()
  535. class PackData(object):
  536. """The data contained in a packfile.
  537. Pack files can be accessed both sequentially for exploding a pack, and
  538. directly with the help of an index to retrieve a specific object.
  539. The objects within are either complete or a delta aginst another.
  540. The header is variable length. If the MSB of each byte is set then it
  541. indicates that the subsequent byte is still part of the header.
  542. For the first byte the next MS bits are the type, which tells you the type
  543. of object, and whether it is a delta. The LS byte is the lowest bits of the
  544. size. For each subsequent byte the LS 7 bits are the next MS bits of the
  545. size, i.e. the last byte of the header contains the MS bits of the size.
  546. For the complete objects the data is stored as zlib deflated data.
  547. The size in the header is the uncompressed object size, so to uncompress
  548. you need to just keep feeding data to zlib until you get an object back,
  549. or it errors on bad data. This is done here by just giving the complete
  550. buffer from the start of the deflated object on. This is bad, but until I
  551. get mmap sorted out it will have to do.
  552. Currently there are no integrity checks done. Also no attempt is made to
  553. try and detect the delta case, or a request for an object at the wrong
  554. position. It will all just throw a zlib or KeyError.
  555. """
  556. def __init__(self, filename, file=None, size=None):
  557. """Create a PackData object representing the pack in the given filename.
  558. The file must exist and stay readable until the object is disposed of. It
  559. must also stay the same size. It will be mapped whenever needed.
  560. Currently there is a restriction on the size of the pack as the python
  561. mmap implementation is flawed.
  562. """
  563. self._filename = filename
  564. self._size = size
  565. self._header_size = 12
  566. if file is None:
  567. self._file = GitFile(self._filename, 'rb')
  568. else:
  569. self._file = file
  570. (version, self._num_objects) = read_pack_header(self._file.read)
  571. self._offset_cache = LRUSizeCache(1024*1024*20,
  572. compute_size=_compute_object_size)
  573. self.pack = None
  574. @classmethod
  575. def from_file(cls, file, size):
  576. return cls(str(file), file=file, size=size)
  577. @classmethod
  578. def from_path(cls, path):
  579. return cls(filename=path)
  580. def close(self):
  581. self._file.close()
  582. def _get_size(self):
  583. if self._size is not None:
  584. return self._size
  585. self._size = os.path.getsize(self._filename)
  586. if self._size < self._header_size:
  587. errmsg = ("%s is too small for a packfile (%d < %d)" %
  588. (self._filename, self._size, self._header_size))
  589. raise AssertionError(errmsg)
  590. return self._size
  591. def __len__(self):
  592. """Returns the number of objects in this pack."""
  593. return self._num_objects
  594. def calculate_checksum(self):
  595. """Calculate the checksum for this pack.
  596. :return: 20-byte binary SHA1 digest
  597. """
  598. s = make_sha()
  599. self._file.seek(0)
  600. todo = self._get_size() - 20
  601. while todo > 0:
  602. x = self._file.read(min(todo, 1<<16))
  603. s.update(x)
  604. todo -= len(x)
  605. return s.digest()
  606. def get_ref(self, sha):
  607. """Get the object for a ref SHA, only looking in this pack."""
  608. # TODO: cache these results
  609. if self.pack is None:
  610. raise KeyError(sha)
  611. offset = self.pack.index.object_index(sha)
  612. if not offset:
  613. raise KeyError(sha)
  614. type, obj = self.get_object_at(offset)
  615. return offset, type, obj
  616. def resolve_object(self, offset, type, obj, get_ref=None):
  617. """Resolve an object, possibly resolving deltas when necessary.
  618. :return: Tuple with object type and contents.
  619. """
  620. if type not in DELTA_TYPES:
  621. return type, obj
  622. if get_ref is None:
  623. get_ref = self.get_ref
  624. if type == OFS_DELTA:
  625. (delta_offset, delta) = obj
  626. # TODO: clean up asserts and replace with nicer error messages
  627. assert isinstance(offset, int)
  628. assert isinstance(delta_offset, int)
  629. base_offset = offset-delta_offset
  630. type, base_obj = self.get_object_at(base_offset)
  631. assert isinstance(type, int)
  632. elif type == REF_DELTA:
  633. (basename, delta) = obj
  634. assert isinstance(basename, str) and len(basename) == 20
  635. base_offset, type, base_obj = get_ref(basename)
  636. assert isinstance(type, int)
  637. type, base_chunks = self.resolve_object(base_offset, type, base_obj)
  638. chunks = apply_delta(base_chunks, delta)
  639. # TODO(dborowitz): This can result in poor performance if large base
  640. # objects are separated from deltas in the pack. We should reorganize
  641. # so that we apply deltas to all objects in a chain one after the other
  642. # to optimize cache performance.
  643. if offset is not None:
  644. self._offset_cache[offset] = type, chunks
  645. return type, chunks
  646. def iterobjects(self, progress=None):
  647. return PackObjectIterator(self, progress)
  648. def iterentries(self, progress=None):
  649. """Yield entries summarizing the contents of this pack.
  650. :param progress: Progress function, called with current and total object
  651. count.
  652. :yields: tuples with (sha, offset, crc32)
  653. """
  654. for offset, type, obj, crc32 in self.iterobjects(progress=progress):
  655. assert isinstance(offset, int)
  656. assert isinstance(type, int)
  657. assert isinstance(obj, list) or isinstance(obj, tuple)
  658. type, obj = self.resolve_object(offset, type, obj)
  659. yield obj_sha(type, obj), offset, crc32
  660. def sorted_entries(self, progress=None):
  661. """Return entries in this pack, sorted by SHA.
  662. :param progress: Progress function, called with current and total object
  663. count
  664. :return: List of tuples with (sha, offset, crc32)
  665. """
  666. ret = list(self.iterentries(progress=progress))
  667. ret.sort()
  668. return ret
  669. def create_index_v1(self, filename, progress=None):
  670. """Create a version 1 file for this data file.
  671. :param filename: Index filename.
  672. :param progress: Progress report function
  673. """
  674. entries = self.sorted_entries(progress=progress)
  675. write_pack_index_v1(filename, entries, self.calculate_checksum())
  676. def create_index_v2(self, filename, progress=None):
  677. """Create a version 2 index file for this data file.
  678. :param filename: Index filename.
  679. :param progress: Progress report function
  680. """
  681. entries = self.sorted_entries(progress=progress)
  682. write_pack_index_v2(filename, entries, self.calculate_checksum())
  683. def create_index(self, filename, progress=None,
  684. version=2):
  685. """Create an index file for this data file.
  686. :param filename: Index filename.
  687. :param progress: Progress report function
  688. """
  689. if version == 1:
  690. self.create_index_v1(filename, progress)
  691. elif version == 2:
  692. self.create_index_v2(filename, progress)
  693. else:
  694. raise ValueError("unknown index format %d" % version)
  695. def get_stored_checksum(self):
  696. """Return the expected checksum stored in this pack."""
  697. self._file.seek(self._get_size()-20)
  698. return self._file.read(20)
  699. def check(self):
  700. """Check the consistency of this pack."""
  701. actual = self.calculate_checksum()
  702. stored = self.get_stored_checksum()
  703. if actual != stored:
  704. raise ChecksumMismatch(stored, actual)
  705. def get_object_at(self, offset):
  706. """Given an offset in to the packfile return the object that is there.
  707. Using the associated index the location of an object can be looked up,
  708. and then the packfile can be asked directly for that object using this
  709. function.
  710. """
  711. if offset in self._offset_cache:
  712. return self._offset_cache[offset]
  713. assert isinstance(offset, long) or isinstance(offset, int),\
  714. "offset was %r" % offset
  715. assert offset >= self._header_size
  716. self._file.seek(offset)
  717. return unpack_object(self._file.read)[:2]
  718. class ThinPackData(PackData):
  719. """PackData for thin packs, which require an ObjectStore for resolving."""
  720. def __init__(self, resolve_ext_ref, *args, **kwargs):
  721. super(ThinPackData, self).__init__(*args, **kwargs)
  722. self.resolve_ext_ref = resolve_ext_ref
  723. def get_ref(self, sha):
  724. """Resolve a reference looking in both this pack and the store."""
  725. try:
  726. # As part of completing a pack we create a Pack object with a
  727. # ThinPackData and a full PackIndex, so check in the index first if
  728. # possible.
  729. # TODO(dborowitz): reevaluate this when the pack completion code is
  730. # rewritten.
  731. return super(ThinPackData, self).get_ref(sha)
  732. except KeyError:
  733. type, obj = self.resolve_ext_ref(sha)
  734. return None, type, obj
  735. def iterentries(self, progress=None):
  736. """Yield entries summarizing the contents of this pack.
  737. :param progress: Progress function, called with current and
  738. total object count.
  739. This will yield tuples with (sha, offset, crc32)
  740. """
  741. found = {}
  742. postponed = defaultdict(list)
  743. class Postpone(Exception):
  744. """Raised to postpone delta resolving."""
  745. def __init__(self, sha):
  746. self.sha = sha
  747. def get_ref_text(sha):
  748. assert len(sha) == 20
  749. if sha in found:
  750. offset = found[sha]
  751. type, obj = self.get_object_at(offset)
  752. return offset, type, obj
  753. try:
  754. return self.get_ref(sha)
  755. except KeyError:
  756. raise Postpone(sha)
  757. extra = []
  758. todo = chain(self.iterobjects(progress=progress), extra)
  759. for (offset, type, obj, crc32) in todo:
  760. assert isinstance(offset, int)
  761. if obj is None:
  762. # Inflate postponed delta
  763. obj, type = self.get_object_at(offset)
  764. assert isinstance(type, int)
  765. assert isinstance(obj, list) or isinstance(obj, tuple)
  766. try:
  767. type, obj = self.resolve_object(offset, type, obj, get_ref_text)
  768. except Postpone, e:
  769. # Save memory by not storing the inflated obj in postponed
  770. postponed[e.sha].append((offset, type, None, crc32))
  771. else:
  772. sha = obj_sha(type, obj)
  773. found[sha] = offset
  774. yield sha, offset, crc32
  775. extra.extend(postponed.pop(sha, []))
  776. if postponed:
  777. raise KeyError([sha_to_hex(h) for h in postponed.keys()])
  778. class SHA1Reader(object):
  779. """Wrapper around a file-like object that remembers the SHA1 of its data."""
  780. def __init__(self, f):
  781. self.f = f
  782. self.sha1 = make_sha("")
  783. def read(self, num=None):
  784. data = self.f.read(num)
  785. self.sha1.update(data)
  786. return data
  787. def check_sha(self):
  788. stored = self.f.read(20)
  789. if stored != self.sha1.digest():
  790. raise ChecksumMismatch(self.sha1.hexdigest(), sha_to_hex(stored))
  791. def close(self):
  792. return self.f.close()
  793. def tell(self):
  794. return self.f.tell()
  795. class SHA1Writer(object):
  796. """Wrapper around a file-like object that remembers the SHA1 of its data."""
  797. def __init__(self, f):
  798. self.f = f
  799. self.sha1 = make_sha("")
  800. def write(self, data):
  801. self.sha1.update(data)
  802. self.f.write(data)
  803. def write_sha(self):
  804. sha = self.sha1.digest()
  805. assert len(sha) == 20
  806. self.f.write(sha)
  807. return sha
  808. def close(self):
  809. sha = self.write_sha()
  810. self.f.close()
  811. return sha
  812. def tell(self):
  813. return self.f.tell()
  814. def write_pack_object(f, type, object):
  815. """Write pack object to a file.
  816. :param f: File to write to
  817. :param type: Numeric type of the object
  818. :param object: Object to write
  819. :return: Tuple with offset at which the object was written, and crc32
  820. """
  821. offset = f.tell()
  822. packed_data_hdr = ""
  823. if type == OFS_DELTA:
  824. (delta_base_offset, object) = object
  825. elif type == REF_DELTA:
  826. (basename, object) = object
  827. size = len(object)
  828. c = (type << 4) | (size & 15)
  829. size >>= 4
  830. while size:
  831. packed_data_hdr += (chr(c | 0x80))
  832. c = size & 0x7f
  833. size >>= 7
  834. packed_data_hdr += chr(c)
  835. if type == OFS_DELTA:
  836. ret = [delta_base_offset & 0x7f]
  837. delta_base_offset >>= 7
  838. while delta_base_offset:
  839. delta_base_offset -= 1
  840. ret.insert(0, 0x80 | (delta_base_offset & 0x7f))
  841. delta_base_offset >>= 7
  842. packed_data_hdr += "".join([chr(x) for x in ret])
  843. elif type == REF_DELTA:
  844. assert len(basename) == 20
  845. packed_data_hdr += basename
  846. packed_data = packed_data_hdr + zlib.compress(object)
  847. f.write(packed_data)
  848. return (offset, (zlib.crc32(packed_data) & 0xffffffff))
  849. def write_pack(filename, objects, num_objects):
  850. """Write a new pack data file.
  851. :param filename: Path to the new pack file (without .pack extension)
  852. :param objects: Iterable over (object, path) tuples to write
  853. :param num_objects: Number of objects to write
  854. """
  855. f = GitFile(filename + ".pack", 'wb')
  856. try:
  857. entries, data_sum = write_pack_data(f, objects, num_objects)
  858. finally:
  859. f.close()
  860. entries.sort()
  861. write_pack_index_v2(filename + ".idx", entries, data_sum)
  862. def write_pack_data(f, objects, num_objects, window=10):
  863. """Write a new pack file.
  864. :param filename: The filename of the new pack file.
  865. :param objects: List of objects to write (tuples with object and path)
  866. :return: List with (name, offset, crc32 checksum) entries, pack checksum
  867. """
  868. recency = list(objects)
  869. # FIXME: Somehow limit delta depth
  870. # FIXME: Make thin-pack optional (its not used when cloning a pack)
  871. # Build a list of objects ordered by the magic Linus heuristic
  872. # This helps us find good objects to diff against us
  873. magic = []
  874. for obj, path in recency:
  875. magic.append( (obj.type_num, path, 1, -obj.raw_length(), obj) )
  876. magic.sort()
  877. # Build a map of objects and their index in magic - so we can find
  878. # preceeding objects to diff against
  879. offs = {}
  880. for i in range(len(magic)):
  881. offs[magic[i][4]] = i
  882. # Write the pack
  883. entries = []
  884. f = SHA1Writer(f)
  885. f.write("PACK") # Pack header
  886. f.write(struct.pack(">L", 2)) # Pack version
  887. f.write(struct.pack(">L", num_objects)) # Number of objects in pack
  888. for o, path in recency:
  889. sha1 = o.sha().digest()
  890. orig_t = o.type_num
  891. raw = o.as_raw_string()
  892. winner = raw
  893. t = orig_t
  894. #for i in range(offs[o]-window, window):
  895. # if i < 0 or i >= len(offs): continue
  896. # b = magic[i][4]
  897. # if b.type_num != orig_t: continue
  898. # base = b.as_raw_string()
  899. # delta = create_delta(base, raw)
  900. # if len(delta) < len(winner):
  901. # winner = delta
  902. # t = 6 if magic[i][2] == 1 else 7
  903. offset, crc32 = write_pack_object(f, t, winner)
  904. entries.append((sha1, offset, crc32))
  905. return entries, f.write_sha()
  906. def write_pack_index_v1(filename, entries, pack_checksum):
  907. """Write a new pack index file.
  908. :param filename: The filename of the new pack index file.
  909. :param entries: List of tuples with object name (sha), offset_in_pack,
  910. and crc32_checksum.
  911. :param pack_checksum: Checksum of the pack file.
  912. """
  913. f = GitFile(filename, 'wb')
  914. try:
  915. f = SHA1Writer(f)
  916. fan_out_table = defaultdict(lambda: 0)
  917. for (name, offset, entry_checksum) in entries:
  918. fan_out_table[ord(name[0])] += 1
  919. # Fan-out table
  920. for i in range(0x100):
  921. f.write(struct.pack(">L", fan_out_table[i]))
  922. fan_out_table[i+1] += fan_out_table[i]
  923. for (name, offset, entry_checksum) in entries:
  924. f.write(struct.pack(">L20s", offset, name))
  925. assert len(pack_checksum) == 20
  926. f.write(pack_checksum)
  927. finally:
  928. f.close()
  929. def create_delta(base_buf, target_buf):
  930. """Use python difflib to work out how to transform base_buf to target_buf.
  931. :param base_buf: Base buffer
  932. :param target_buf: Target buffer
  933. """
  934. assert isinstance(base_buf, str)
  935. assert isinstance(target_buf, str)
  936. out_buf = ""
  937. # write delta header
  938. def encode_size(size):
  939. ret = ""
  940. c = size & 0x7f
  941. size >>= 7
  942. while size:
  943. ret += chr(c | 0x80)
  944. c = size & 0x7f
  945. size >>= 7
  946. ret += chr(c)
  947. return ret
  948. out_buf += encode_size(len(base_buf))
  949. out_buf += encode_size(len(target_buf))
  950. # write out delta opcodes
  951. seq = difflib.SequenceMatcher(a=base_buf, b=target_buf)
  952. for opcode, i1, i2, j1, j2 in seq.get_opcodes():
  953. # Git patch opcodes don't care about deletes!
  954. #if opcode == "replace" or opcode == "delete":
  955. # pass
  956. if opcode == "equal":
  957. # If they are equal, unpacker will use data from base_buf
  958. # Write out an opcode that says what range to use
  959. scratch = ""
  960. op = 0x80
  961. o = i1
  962. for i in range(4):
  963. if o & 0xff << i*8:
  964. scratch += chr((o >> i*8) & 0xff)
  965. op |= 1 << i
  966. s = i2 - i1
  967. for i in range(2):
  968. if s & 0xff << i*8:
  969. scratch += chr((s >> i*8) & 0xff)
  970. op |= 1 << (4+i)
  971. out_buf += chr(op)
  972. out_buf += scratch
  973. if opcode == "replace" or opcode == "insert":
  974. # If we are replacing a range or adding one, then we just
  975. # output it to the stream (prefixed by its size)
  976. s = j2 - j1
  977. o = j1
  978. while s > 127:
  979. out_buf += chr(127)
  980. out_buf += target_buf[o:o+127]
  981. s -= 127
  982. o += 127
  983. out_buf += chr(s)
  984. out_buf += target_buf[o:o+s]
  985. return out_buf
  986. def apply_delta(src_buf, delta):
  987. """Based on the similar function in git's patch-delta.c.
  988. :param src_buf: Source buffer
  989. :param delta: Delta instructions
  990. """
  991. if type(src_buf) != str:
  992. src_buf = "".join(src_buf)
  993. if type(delta) != str:
  994. delta = "".join(delta)
  995. out = []
  996. index = 0
  997. delta_length = len(delta)
  998. def get_delta_header_size(delta, index):
  999. size = 0
  1000. i = 0
  1001. while delta:
  1002. cmd = ord(delta[index])
  1003. index += 1
  1004. size |= (cmd & ~0x80) << i
  1005. i += 7
  1006. if not cmd & 0x80:
  1007. break
  1008. return size, index
  1009. src_size, index = get_delta_header_size(delta, index)
  1010. dest_size, index = get_delta_header_size(delta, index)
  1011. assert src_size == len(src_buf), "%d vs %d" % (src_size, len(src_buf))
  1012. while index < delta_length:
  1013. cmd = ord(delta[index])
  1014. index += 1
  1015. if cmd & 0x80:
  1016. cp_off = 0
  1017. for i in range(4):
  1018. if cmd & (1 << i):
  1019. x = ord(delta[index])
  1020. index += 1
  1021. cp_off |= x << (i * 8)
  1022. cp_size = 0
  1023. for i in range(3):
  1024. if cmd & (1 << (4+i)):
  1025. x = ord(delta[index])
  1026. index += 1
  1027. cp_size |= x << (i * 8)
  1028. if cp_size == 0:
  1029. cp_size = 0x10000
  1030. if (cp_off + cp_size < cp_size or
  1031. cp_off + cp_size > src_size or
  1032. cp_size > dest_size):
  1033. break
  1034. out.append(src_buf[cp_off:cp_off+cp_size])
  1035. elif cmd != 0:
  1036. out.append(delta[index:index+cmd])
  1037. index += cmd
  1038. else:
  1039. raise ApplyDeltaError("Invalid opcode 0")
  1040. if index != delta_length:
  1041. raise ApplyDeltaError("delta not empty: %r" % delta[index:])
  1042. if dest_size != chunks_length(out):
  1043. raise ApplyDeltaError("dest size incorrect")
  1044. return out
  1045. def write_pack_index_v2(filename, entries, pack_checksum):
  1046. """Write a new pack index file.
  1047. :param filename: The filename of the new pack index file.
  1048. :param entries: List of tuples with object name (sha), offset_in_pack, and
  1049. crc32_checksum.
  1050. :param pack_checksum: Checksum of the pack file.
  1051. """
  1052. f = GitFile(filename, 'wb')
  1053. try:
  1054. f = SHA1Writer(f)
  1055. f.write('\377tOc') # Magic!
  1056. f.write(struct.pack(">L", 2))
  1057. fan_out_table = defaultdict(lambda: 0)
  1058. for (name, offset, entry_checksum) in entries:
  1059. fan_out_table[ord(name[0])] += 1
  1060. # Fan-out table
  1061. for i in range(0x100):
  1062. f.write(struct.pack(">L", fan_out_table[i]))
  1063. fan_out_table[i+1] += fan_out_table[i]
  1064. for (name, offset, entry_checksum) in entries:
  1065. f.write(name)
  1066. for (name, offset, entry_checksum) in entries:
  1067. f.write(struct.pack(">L", entry_checksum))
  1068. for (name, offset, entry_checksum) in entries:
  1069. # FIXME: handle if MSBit is set in offset
  1070. f.write(struct.pack(">L", offset))
  1071. # FIXME: handle table for pack files > 8 Gb
  1072. assert len(pack_checksum) == 20
  1073. f.write(pack_checksum)
  1074. finally:
  1075. f.close()
  1076. class Pack(object):
  1077. """A Git pack object."""
  1078. def __init__(self, basename):
  1079. self._basename = basename
  1080. self._data_path = self._basename + ".pack"
  1081. self._idx_path = self._basename + ".idx"
  1082. self._data = None
  1083. self._idx = None
  1084. @classmethod
  1085. def from_objects(self, data, idx):
  1086. """Create a new pack object from pack data and index objects."""
  1087. ret = Pack("")
  1088. ret._data = data
  1089. ret._idx = idx
  1090. data.pack = ret
  1091. return ret
  1092. def name(self):
  1093. """The SHA over the SHAs of the objects in this pack."""
  1094. return self.index.objects_sha1()
  1095. @property
  1096. def data(self):
  1097. """The pack data object being used."""
  1098. if self._data is None:
  1099. self._data = PackData(self._data_path)
  1100. self._data.pack = self
  1101. assert len(self.index) == len(self._data)
  1102. idx_stored_checksum = self.index.get_pack_checksum()
  1103. data_stored_checksum = self._data.get_stored_checksum()
  1104. if idx_stored_checksum != data_stored_checksum:
  1105. raise ChecksumMismatch(sha_to_hex(idx_stored_checksum),
  1106. sha_to_hex(data_stored_checksum))
  1107. return self._data
  1108. @property
  1109. def index(self):
  1110. """The index being used.
  1111. :note: This may be an in-memory index
  1112. """
  1113. if self._idx is None:
  1114. self._idx = load_pack_index(self._idx_path)
  1115. return self._idx
  1116. def close(self):
  1117. if self._data is not None:
  1118. self._data.close()
  1119. self.index.close()
  1120. def __eq__(self, other):
  1121. return type(self) == type(other) and self.index == other.index
  1122. def __len__(self):
  1123. """Number of entries in this pack."""
  1124. return len(self.index)
  1125. def __repr__(self):
  1126. return "%s(%r)" % (self.__class__.__name__, self._basename)
  1127. def __iter__(self):
  1128. """Iterate over all the sha1s of the objects in this pack."""
  1129. return iter(self.index)
  1130. def check(self):
  1131. """Check the integrity of this pack.
  1132. :raise ChecksumMismatch: if a checksum for the index or data is wrong
  1133. """
  1134. self.index.check()
  1135. self.data.check()
  1136. for obj in self.iterobjects():
  1137. obj.check()
  1138. # TODO: object connectivity checks
  1139. def get_stored_checksum(self):
  1140. return self.data.get_stored_checksum()
  1141. def __contains__(self, sha1):
  1142. """Check whether this pack contains a particular SHA1."""
  1143. try:
  1144. self.index.object_index(sha1)
  1145. return True
  1146. except KeyError:
  1147. return False
  1148. def get_raw(self, sha1):
  1149. offset = self.index.object_index(sha1)
  1150. obj_type, obj = self.data.get_object_at(offset)
  1151. if type(offset) is long:
  1152. offset = int(offset)
  1153. type_num, chunks = self.data.resolve_object(offset, obj_type, obj)
  1154. return type_num, "".join(chunks)
  1155. def __getitem__(self, sha1):
  1156. """Retrieve the specified SHA1."""
  1157. type, uncomp = self.get_raw(sha1)
  1158. return ShaFile.from_raw_string(type, uncomp)
  1159. def iterobjects(self):
  1160. """Iterate over the objects in this pack."""
  1161. for offset, type, obj, crc32 in self.data.iterobjects():
  1162. assert isinstance(offset, int)
  1163. yield ShaFile.from_raw_chunks(
  1164. *self.data.resolve_object(offset, type, obj))
  1165. try:
  1166. from dulwich._pack import apply_delta, bisect_find_sha
  1167. except ImportError:
  1168. pass