pack.py 48 KB

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