2
0

pack.py 45 KB

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