pack.py 63 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934
  1. # pack.py -- For dealing with packed git objects.
  2. # Copyright (C) 2007 James Westby <jw+debian@jameswestby.net>
  3. # Copyright (C) 2008-2013 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. from collections import defaultdict
  29. import binascii
  30. from io import BytesIO
  31. from collections import (
  32. deque,
  33. )
  34. import difflib
  35. from itertools import chain, imap, izip
  36. try:
  37. import mmap
  38. except ImportError:
  39. has_mmap = False
  40. else:
  41. has_mmap = True
  42. from hashlib import sha1
  43. import os
  44. from os import (
  45. SEEK_CUR,
  46. SEEK_END,
  47. )
  48. import struct
  49. from struct import unpack_from
  50. import warnings
  51. import zlib
  52. from dulwich.errors import (
  53. ApplyDeltaError,
  54. ChecksumMismatch,
  55. )
  56. from dulwich.file import GitFile
  57. from dulwich.lru_cache import (
  58. LRUSizeCache,
  59. )
  60. from dulwich.objects import (
  61. ShaFile,
  62. hex_to_sha,
  63. sha_to_hex,
  64. object_header,
  65. )
  66. OFS_DELTA = 6
  67. REF_DELTA = 7
  68. DELTA_TYPES = (OFS_DELTA, REF_DELTA)
  69. DEFAULT_PACK_DELTA_WINDOW_SIZE = 10
  70. def take_msb_bytes(read, crc32=None):
  71. """Read bytes marked with most significant bit.
  72. :param read: Read function
  73. """
  74. ret = []
  75. while len(ret) == 0 or ret[-1] & 0x80:
  76. b = read(1)
  77. if crc32 is not None:
  78. crc32 = binascii.crc32(b, crc32)
  79. ret.append(ord(b))
  80. return ret, crc32
  81. class UnpackedObject(object):
  82. """Class encapsulating an object unpacked from a pack file.
  83. These objects should only be created from within unpack_object. Most
  84. members start out as empty and are filled in at various points by
  85. read_zlib_chunks, unpack_object, DeltaChainIterator, etc.
  86. End users of this object should take care that the function they're getting
  87. this object from is guaranteed to set the members they need.
  88. """
  89. __slots__ = [
  90. 'offset', # Offset in its pack.
  91. '_sha', # Cached binary SHA.
  92. 'obj_type_num', # Type of this object.
  93. 'obj_chunks', # Decompressed and delta-resolved chunks.
  94. 'pack_type_num', # Type of this object in the pack (may be a delta).
  95. 'delta_base', # Delta base offset or SHA.
  96. 'comp_chunks', # Compressed object chunks.
  97. 'decomp_chunks', # Decompressed object chunks.
  98. 'decomp_len', # Decompressed length of this object.
  99. 'crc32', # CRC32.
  100. ]
  101. # TODO(dborowitz): read_zlib_chunks and unpack_object could very well be
  102. # methods of this object.
  103. def __init__(self, pack_type_num, delta_base, decomp_len, crc32):
  104. self.offset = None
  105. self._sha = None
  106. self.pack_type_num = pack_type_num
  107. self.delta_base = delta_base
  108. self.comp_chunks = None
  109. self.decomp_chunks = []
  110. self.decomp_len = decomp_len
  111. self.crc32 = crc32
  112. if pack_type_num in DELTA_TYPES:
  113. self.obj_type_num = None
  114. self.obj_chunks = None
  115. else:
  116. self.obj_type_num = pack_type_num
  117. self.obj_chunks = self.decomp_chunks
  118. self.delta_base = delta_base
  119. def sha(self):
  120. """Return the binary SHA of this object."""
  121. if self._sha is None:
  122. self._sha = obj_sha(self.obj_type_num, self.obj_chunks)
  123. return self._sha
  124. def sha_file(self):
  125. """Return a ShaFile from this object."""
  126. return ShaFile.from_raw_chunks(self.obj_type_num, self.obj_chunks)
  127. # Only provided for backwards compatibility with code that expects either
  128. # chunks or a delta tuple.
  129. def _obj(self):
  130. """Return the decompressed chunks, or (delta base, delta chunks)."""
  131. if self.pack_type_num in DELTA_TYPES:
  132. return (self.delta_base, self.decomp_chunks)
  133. else:
  134. return self.decomp_chunks
  135. def __eq__(self, other):
  136. if not isinstance(other, UnpackedObject):
  137. return False
  138. for slot in self.__slots__:
  139. if getattr(self, slot) != getattr(other, slot):
  140. return False
  141. return True
  142. def __ne__(self, other):
  143. return not (self == other)
  144. def __repr__(self):
  145. data = ['%s=%r' % (s, getattr(self, s)) for s in self.__slots__]
  146. return '%s(%s)' % (self.__class__.__name__, ', '.join(data))
  147. _ZLIB_BUFSIZE = 4096
  148. def read_zlib_chunks(read_some, unpacked, include_comp=False,
  149. buffer_size=_ZLIB_BUFSIZE):
  150. """Read zlib data from a buffer.
  151. This function requires that the buffer have additional data following the
  152. compressed data, which is guaranteed to be the case for git pack files.
  153. :param read_some: Read function that returns at least one byte, but may
  154. return less than the requested size.
  155. :param unpacked: An UnpackedObject to write result data to. If its crc32
  156. attr is not None, the CRC32 of the compressed bytes will be computed
  157. using this starting CRC32.
  158. After this function, will have the following attrs set:
  159. * comp_chunks (if include_comp is True)
  160. * decomp_chunks
  161. * decomp_len
  162. * crc32
  163. :param include_comp: If True, include compressed data in the result.
  164. :param buffer_size: Size of the read buffer.
  165. :return: Leftover unused data from the decompression.
  166. :raise zlib.error: if a decompression error occurred.
  167. """
  168. if unpacked.decomp_len <= -1:
  169. raise ValueError('non-negative zlib data stream size expected')
  170. decomp_obj = zlib.decompressobj()
  171. comp_chunks = []
  172. decomp_chunks = unpacked.decomp_chunks
  173. decomp_len = 0
  174. crc32 = unpacked.crc32
  175. while True:
  176. add = read_some(buffer_size)
  177. if not add:
  178. raise zlib.error('EOF before end of zlib stream')
  179. comp_chunks.append(add)
  180. decomp = decomp_obj.decompress(add)
  181. decomp_len += len(decomp)
  182. decomp_chunks.append(decomp)
  183. unused = decomp_obj.unused_data
  184. if unused:
  185. left = len(unused)
  186. if crc32 is not None:
  187. crc32 = binascii.crc32(add[:-left], crc32)
  188. if include_comp:
  189. comp_chunks[-1] = add[:-left]
  190. break
  191. elif crc32 is not None:
  192. crc32 = binascii.crc32(add, crc32)
  193. if crc32 is not None:
  194. crc32 &= 0xffffffff
  195. if decomp_len != unpacked.decomp_len:
  196. raise zlib.error('decompressed data does not match expected size')
  197. unpacked.crc32 = crc32
  198. if include_comp:
  199. unpacked.comp_chunks = comp_chunks
  200. return unused
  201. def iter_sha1(iter):
  202. """Return the hexdigest of the SHA1 over a set of names.
  203. :param iter: Iterator over string objects
  204. :return: 40-byte hex sha1 digest
  205. """
  206. sha = sha1()
  207. for name in iter:
  208. sha.update(name)
  209. return sha.hexdigest()
  210. def load_pack_index(path):
  211. """Load an index file by path.
  212. :param filename: Path to the index file
  213. :return: A PackIndex loaded from the given path
  214. """
  215. f = GitFile(path, 'rb')
  216. try:
  217. return load_pack_index_file(path, f)
  218. finally:
  219. f.close()
  220. def _load_file_contents(f, size=None):
  221. fileno = getattr(f, 'fileno', None)
  222. # Attempt to use mmap if possible
  223. if fileno is not None:
  224. fd = f.fileno()
  225. if size is None:
  226. size = os.fstat(fd).st_size
  227. if has_mmap:
  228. try:
  229. contents = mmap.mmap(fd, size, access=mmap.ACCESS_READ)
  230. except mmap.error:
  231. # Perhaps a socket?
  232. pass
  233. else:
  234. return contents, size
  235. contents = f.read()
  236. size = len(contents)
  237. return contents, size
  238. def load_pack_index_file(path, f):
  239. """Load an index file from a file-like object.
  240. :param path: Path for the index file
  241. :param f: File-like object
  242. :return: A PackIndex loaded from the given file
  243. """
  244. contents, size = _load_file_contents(f)
  245. if contents[:4] == '\377tOc':
  246. version = struct.unpack('>L', contents[4:8])[0]
  247. if version == 2:
  248. return PackIndex2(path, file=f, contents=contents,
  249. size=size)
  250. else:
  251. raise KeyError('Unknown pack index format %d' % version)
  252. else:
  253. return PackIndex1(path, file=f, contents=contents, size=size)
  254. def bisect_find_sha(start, end, sha, unpack_name):
  255. """Find a SHA in a data blob with sorted SHAs.
  256. :param start: Start index of range to search
  257. :param end: End index of range to search
  258. :param sha: Sha to find
  259. :param unpack_name: Callback to retrieve SHA by index
  260. :return: Index of the SHA, or None if it wasn't found
  261. """
  262. assert start <= end
  263. while start <= end:
  264. i = (start + end) // 2
  265. file_sha = unpack_name(i)
  266. x = cmp(file_sha, sha)
  267. if x < 0:
  268. start = i + 1
  269. elif x > 0:
  270. end = i - 1
  271. else:
  272. return i
  273. return None
  274. class PackIndex(object):
  275. """An index in to a packfile.
  276. Given a sha id of an object a pack index can tell you the location in the
  277. packfile of that object if it has it.
  278. """
  279. def __eq__(self, other):
  280. if not isinstance(other, PackIndex):
  281. return False
  282. for (name1, _, _), (name2, _, _) in izip(self.iterentries(),
  283. other.iterentries()):
  284. if name1 != name2:
  285. return False
  286. return True
  287. def __ne__(self, other):
  288. return not self.__eq__(other)
  289. def __len__(self):
  290. """Return the number of entries in this pack index."""
  291. raise NotImplementedError(self.__len__)
  292. def __iter__(self):
  293. """Iterate over the SHAs in this pack."""
  294. return imap(sha_to_hex, self._itersha())
  295. def iterentries(self):
  296. """Iterate over the entries in this pack index.
  297. :return: iterator over tuples with object name, offset in packfile and
  298. crc32 checksum.
  299. """
  300. raise NotImplementedError(self.iterentries)
  301. def get_pack_checksum(self):
  302. """Return the SHA1 checksum stored for the corresponding packfile.
  303. :return: 20-byte binary digest
  304. """
  305. raise NotImplementedError(self.get_pack_checksum)
  306. def object_index(self, sha):
  307. """Return the index in to the corresponding packfile for the object.
  308. Given the name of an object it will return the offset that object
  309. lives at within the corresponding pack file. If the pack file doesn't
  310. have the object then None will be returned.
  311. """
  312. if len(sha) == 40:
  313. sha = hex_to_sha(sha)
  314. return self._object_index(sha)
  315. def _object_index(self, sha):
  316. """See object_index.
  317. :param sha: A *binary* SHA string. (20 characters long)_
  318. """
  319. raise NotImplementedError(self._object_index)
  320. def objects_sha1(self):
  321. """Return the hex SHA1 over all the shas of all objects in this pack.
  322. :note: This is used for the filename of the pack.
  323. """
  324. return iter_sha1(self._itersha())
  325. def _itersha(self):
  326. """Yield all the SHA1's of the objects in the index, sorted."""
  327. raise NotImplementedError(self._itersha)
  328. class MemoryPackIndex(PackIndex):
  329. """Pack index that is stored entirely in memory."""
  330. def __init__(self, entries, pack_checksum=None):
  331. """Create a new MemoryPackIndex.
  332. :param entries: Sequence of name, idx, crc32 (sorted)
  333. :param pack_checksum: Optional pack checksum
  334. """
  335. self._by_sha = {}
  336. for name, idx, crc32 in entries:
  337. self._by_sha[name] = idx
  338. self._entries = entries
  339. self._pack_checksum = pack_checksum
  340. def get_pack_checksum(self):
  341. return self._pack_checksum
  342. def __len__(self):
  343. return len(self._entries)
  344. def _object_index(self, sha):
  345. return self._by_sha[sha][0]
  346. def _itersha(self):
  347. return iter(self._by_sha)
  348. def iterentries(self):
  349. return iter(self._entries)
  350. class FilePackIndex(PackIndex):
  351. """Pack index that is based on a file.
  352. To do the loop it opens the file, and indexes first 256 4 byte groups
  353. with the first byte of the sha id. The value in the four byte group indexed
  354. is the end of the group that shares the same starting byte. Subtract one
  355. from the starting byte and index again to find the start of the group.
  356. The values are sorted by sha id within the group, so do the math to find
  357. the start and end offset and then bisect in to find if the value is present.
  358. """
  359. def __init__(self, filename, file=None, contents=None, size=None):
  360. """Create a pack index object.
  361. Provide it with the name of the index file to consider, and it will map
  362. it whenever required.
  363. """
  364. self._filename = filename
  365. # Take the size now, so it can be checked each time we map the file to
  366. # ensure that it hasn't changed.
  367. if file is None:
  368. self._file = GitFile(filename, 'rb')
  369. else:
  370. self._file = file
  371. if contents is None:
  372. self._contents, self._size = _load_file_contents(self._file, size)
  373. else:
  374. self._contents, self._size = (contents, size)
  375. def __eq__(self, other):
  376. # Quick optimization:
  377. if (isinstance(other, FilePackIndex) and
  378. self._fan_out_table != other._fan_out_table):
  379. return False
  380. return super(FilePackIndex, self).__eq__(other)
  381. def close(self):
  382. self._file.close()
  383. if getattr(self._contents, "close", None) is not None:
  384. self._contents.close()
  385. def __len__(self):
  386. """Return the number of entries in this pack index."""
  387. return self._fan_out_table[-1]
  388. def _unpack_entry(self, i):
  389. """Unpack the i-th entry in the index file.
  390. :return: Tuple with object name (SHA), offset in pack file and CRC32
  391. checksum (if known).
  392. """
  393. raise NotImplementedError(self._unpack_entry)
  394. def _unpack_name(self, i):
  395. """Unpack the i-th name from the index file."""
  396. raise NotImplementedError(self._unpack_name)
  397. def _unpack_offset(self, i):
  398. """Unpack the i-th object offset from the index file."""
  399. raise NotImplementedError(self._unpack_offset)
  400. def _unpack_crc32_checksum(self, i):
  401. """Unpack the crc32 checksum for the i-th object from the index file."""
  402. raise NotImplementedError(self._unpack_crc32_checksum)
  403. def _itersha(self):
  404. for i in range(len(self)):
  405. yield self._unpack_name(i)
  406. def iterentries(self):
  407. """Iterate over the entries in this pack index.
  408. :return: iterator over tuples with object name, offset in packfile and
  409. crc32 checksum.
  410. """
  411. for i in range(len(self)):
  412. yield self._unpack_entry(i)
  413. def _read_fan_out_table(self, start_offset):
  414. ret = []
  415. for i in range(0x100):
  416. fanout_entry = self._contents[start_offset+i*4:start_offset+(i+1)*4]
  417. ret.append(struct.unpack('>L', fanout_entry)[0])
  418. return ret
  419. def check(self):
  420. """Check that the stored checksum matches the actual checksum."""
  421. actual = self.calculate_checksum()
  422. stored = self.get_stored_checksum()
  423. if actual != stored:
  424. raise ChecksumMismatch(stored, actual)
  425. def calculate_checksum(self):
  426. """Calculate the SHA1 checksum over this pack index.
  427. :return: This is a 20-byte binary digest
  428. """
  429. return sha1(self._contents[:-20]).digest()
  430. def get_pack_checksum(self):
  431. """Return the SHA1 checksum stored for the corresponding packfile.
  432. :return: 20-byte binary digest
  433. """
  434. return str(self._contents[-40:-20])
  435. def get_stored_checksum(self):
  436. """Return the SHA1 checksum stored for this index.
  437. :return: 20-byte binary digest
  438. """
  439. return str(self._contents[-20:])
  440. def _object_index(self, sha):
  441. """See object_index.
  442. :param sha: A *binary* SHA string. (20 characters long)_
  443. """
  444. assert len(sha) == 20
  445. idx = ord(sha[0])
  446. if idx == 0:
  447. start = 0
  448. else:
  449. start = self._fan_out_table[idx-1]
  450. end = self._fan_out_table[idx]
  451. i = bisect_find_sha(start, end, sha, self._unpack_name)
  452. if i is None:
  453. raise KeyError(sha)
  454. return self._unpack_offset(i)
  455. class PackIndex1(FilePackIndex):
  456. """Version 1 Pack Index file."""
  457. def __init__(self, filename, file=None, contents=None, size=None):
  458. super(PackIndex1, self).__init__(filename, file, contents, size)
  459. self.version = 1
  460. self._fan_out_table = self._read_fan_out_table(0)
  461. def _unpack_entry(self, i):
  462. (offset, name) = unpack_from('>L20s', self._contents,
  463. (0x100 * 4) + (i * 24))
  464. return (name, offset, None)
  465. def _unpack_name(self, i):
  466. offset = (0x100 * 4) + (i * 24) + 4
  467. return self._contents[offset:offset+20]
  468. def _unpack_offset(self, i):
  469. offset = (0x100 * 4) + (i * 24)
  470. return unpack_from('>L', self._contents, offset)[0]
  471. def _unpack_crc32_checksum(self, i):
  472. # Not stored in v1 index files
  473. return None
  474. class PackIndex2(FilePackIndex):
  475. """Version 2 Pack Index file."""
  476. def __init__(self, filename, file=None, contents=None, size=None):
  477. super(PackIndex2, self).__init__(filename, file, contents, size)
  478. if self._contents[:4] != '\377tOc':
  479. raise AssertionError('Not a v2 pack index file')
  480. (self.version, ) = unpack_from('>L', self._contents, 4)
  481. if self.version != 2:
  482. raise AssertionError('Version was %d' % self.version)
  483. self._fan_out_table = self._read_fan_out_table(8)
  484. self._name_table_offset = 8 + 0x100 * 4
  485. self._crc32_table_offset = self._name_table_offset + 20 * len(self)
  486. self._pack_offset_table_offset = (self._crc32_table_offset +
  487. 4 * len(self))
  488. self._pack_offset_largetable_offset = (self._pack_offset_table_offset +
  489. 4 * len(self))
  490. def _unpack_entry(self, i):
  491. return (self._unpack_name(i), self._unpack_offset(i),
  492. self._unpack_crc32_checksum(i))
  493. def _unpack_name(self, i):
  494. offset = self._name_table_offset + i * 20
  495. return self._contents[offset:offset+20]
  496. def _unpack_offset(self, i):
  497. offset = self._pack_offset_table_offset + i * 4
  498. offset = unpack_from('>L', self._contents, offset)[0]
  499. if offset & (2**31):
  500. offset = self._pack_offset_largetable_offset + (offset&(2**31-1)) * 8
  501. offset = unpack_from('>Q', self._contents, offset)[0]
  502. return offset
  503. def _unpack_crc32_checksum(self, i):
  504. return unpack_from('>L', self._contents,
  505. self._crc32_table_offset + i * 4)[0]
  506. def read_pack_header(read):
  507. """Read the header of a pack file.
  508. :param read: Read function
  509. :return: Tuple of (pack version, number of objects). If no data is available
  510. to read, returns (None, None).
  511. """
  512. header = read(12)
  513. if not header:
  514. return None, None
  515. if header[:4] != 'PACK':
  516. raise AssertionError('Invalid pack header %r' % header)
  517. (version,) = unpack_from('>L', header, 4)
  518. if version not in (2, 3):
  519. raise AssertionError('Version was %d' % version)
  520. (num_objects,) = unpack_from('>L', header, 8)
  521. return (version, num_objects)
  522. def chunks_length(chunks):
  523. return sum(imap(len, chunks))
  524. def unpack_object(read_all, read_some=None, compute_crc32=False,
  525. include_comp=False, zlib_bufsize=_ZLIB_BUFSIZE):
  526. """Unpack a Git object.
  527. :param read_all: Read function that blocks until the number of requested
  528. bytes are read.
  529. :param read_some: Read function that returns at least one byte, but may not
  530. return the number of bytes requested.
  531. :param compute_crc32: If True, compute the CRC32 of the compressed data. If
  532. False, the returned CRC32 will be None.
  533. :param include_comp: If True, include compressed data in the result.
  534. :param zlib_bufsize: An optional buffer size for zlib operations.
  535. :return: A tuple of (unpacked, unused), where unused is the unused data
  536. leftover from decompression, and unpacked in an UnpackedObject with
  537. the following attrs set:
  538. * obj_chunks (for non-delta types)
  539. * pack_type_num
  540. * delta_base (for delta types)
  541. * comp_chunks (if include_comp is True)
  542. * decomp_chunks
  543. * decomp_len
  544. * crc32 (if compute_crc32 is True)
  545. """
  546. if read_some is None:
  547. read_some = read_all
  548. if compute_crc32:
  549. crc32 = 0
  550. else:
  551. crc32 = None
  552. bytes, crc32 = take_msb_bytes(read_all, crc32=crc32)
  553. type_num = (bytes[0] >> 4) & 0x07
  554. size = bytes[0] & 0x0f
  555. for i, byte in enumerate(bytes[1:]):
  556. size += (byte & 0x7f) << ((i * 7) + 4)
  557. raw_base = len(bytes)
  558. if type_num == OFS_DELTA:
  559. bytes, crc32 = take_msb_bytes(read_all, crc32=crc32)
  560. raw_base += len(bytes)
  561. if bytes[-1] & 0x80:
  562. raise AssertionError
  563. delta_base_offset = bytes[0] & 0x7f
  564. for byte in bytes[1:]:
  565. delta_base_offset += 1
  566. delta_base_offset <<= 7
  567. delta_base_offset += (byte & 0x7f)
  568. delta_base = delta_base_offset
  569. elif type_num == REF_DELTA:
  570. delta_base = read_all(20)
  571. if compute_crc32:
  572. crc32 = binascii.crc32(delta_base, crc32)
  573. raw_base += 20
  574. else:
  575. delta_base = None
  576. unpacked = UnpackedObject(type_num, delta_base, size, crc32)
  577. unused = read_zlib_chunks(read_some, unpacked, buffer_size=zlib_bufsize,
  578. include_comp=include_comp)
  579. return unpacked, unused
  580. def _compute_object_size(value):
  581. """Compute the size of a unresolved object for use with LRUSizeCache."""
  582. (num, obj) = value
  583. if num in DELTA_TYPES:
  584. return chunks_length(obj[1])
  585. return chunks_length(obj)
  586. class PackStreamReader(object):
  587. """Class to read a pack stream.
  588. The pack is read from a ReceivableProtocol using read() or recv() as
  589. appropriate.
  590. """
  591. def __init__(self, read_all, read_some=None, zlib_bufsize=_ZLIB_BUFSIZE):
  592. self.read_all = read_all
  593. if read_some is None:
  594. self.read_some = read_all
  595. else:
  596. self.read_some = read_some
  597. self.sha = sha1()
  598. self._offset = 0
  599. self._rbuf = BytesIO()
  600. # trailer is a deque to avoid memory allocation on small reads
  601. self._trailer = deque()
  602. self._zlib_bufsize = zlib_bufsize
  603. def _read(self, read, size):
  604. """Read up to size bytes using the given callback.
  605. As a side effect, update the verifier's hash (excluding the last 20
  606. bytes read).
  607. :param read: The read callback to read from.
  608. :param size: The maximum number of bytes to read; the particular
  609. behavior is callback-specific.
  610. """
  611. data = read(size)
  612. # maintain a trailer of the last 20 bytes we've read
  613. n = len(data)
  614. self._offset += n
  615. tn = len(self._trailer)
  616. if n >= 20:
  617. to_pop = tn
  618. to_add = 20
  619. else:
  620. to_pop = max(n + tn - 20, 0)
  621. to_add = n
  622. for _ in xrange(to_pop):
  623. self.sha.update(self._trailer.popleft())
  624. self._trailer.extend(data[-to_add:])
  625. # hash everything but the trailer
  626. self.sha.update(data[:-to_add])
  627. return data
  628. def _buf_len(self):
  629. buf = self._rbuf
  630. start = buf.tell()
  631. buf.seek(0, SEEK_END)
  632. end = buf.tell()
  633. buf.seek(start)
  634. return end - start
  635. @property
  636. def offset(self):
  637. return self._offset - self._buf_len()
  638. def read(self, size):
  639. """Read, blocking until size bytes are read."""
  640. buf_len = self._buf_len()
  641. if buf_len >= size:
  642. return self._rbuf.read(size)
  643. buf_data = self._rbuf.read()
  644. self._rbuf = BytesIO()
  645. return buf_data + self._read(self.read_all, size - buf_len)
  646. def recv(self, size):
  647. """Read up to size bytes, blocking until one byte is read."""
  648. buf_len = self._buf_len()
  649. if buf_len:
  650. data = self._rbuf.read(size)
  651. if size >= buf_len:
  652. self._rbuf = BytesIO()
  653. return data
  654. return self._read(self.read_some, size)
  655. def __len__(self):
  656. return self._num_objects
  657. def read_objects(self, compute_crc32=False):
  658. """Read the objects in this pack file.
  659. :param compute_crc32: If True, compute the CRC32 of the compressed
  660. data. If False, the returned CRC32 will be None.
  661. :return: Iterator over UnpackedObjects with the following members set:
  662. offset
  663. obj_type_num
  664. obj_chunks (for non-delta types)
  665. delta_base (for delta types)
  666. decomp_chunks
  667. decomp_len
  668. crc32 (if compute_crc32 is True)
  669. :raise ChecksumMismatch: if the checksum of the pack contents does not
  670. match the checksum in the pack trailer.
  671. :raise zlib.error: if an error occurred during zlib decompression.
  672. :raise IOError: if an error occurred writing to the output file.
  673. """
  674. pack_version, self._num_objects = read_pack_header(self.read)
  675. if pack_version is None:
  676. return
  677. for i in xrange(self._num_objects):
  678. offset = self.offset
  679. unpacked, unused = unpack_object(
  680. self.read, read_some=self.recv, compute_crc32=compute_crc32,
  681. zlib_bufsize=self._zlib_bufsize)
  682. unpacked.offset = offset
  683. # prepend any unused data to current read buffer
  684. buf = BytesIO()
  685. buf.write(unused)
  686. buf.write(self._rbuf.read())
  687. buf.seek(0)
  688. self._rbuf = buf
  689. yield unpacked
  690. if self._buf_len() < 20:
  691. # If the read buffer is full, then the last read() got the whole
  692. # trailer off the wire. If not, it means there is still some of the
  693. # trailer to read. We need to read() all 20 bytes; N come from the
  694. # read buffer and (20 - N) come from the wire.
  695. self.read(20)
  696. pack_sha = ''.join(self._trailer)
  697. if pack_sha != self.sha.digest():
  698. raise ChecksumMismatch(sha_to_hex(pack_sha), self.sha.hexdigest())
  699. class PackStreamCopier(PackStreamReader):
  700. """Class to verify a pack stream as it is being read.
  701. The pack is read from a ReceivableProtocol using read() or recv() as
  702. appropriate and written out to the given file-like object.
  703. """
  704. def __init__(self, read_all, read_some, outfile, delta_iter=None):
  705. """Initialize the copier.
  706. :param read_all: Read function that blocks until the number of requested
  707. bytes are read.
  708. :param read_some: Read function that returns at least one byte, but may
  709. not return the number of bytes requested.
  710. :param outfile: File-like object to write output through.
  711. :param delta_iter: Optional DeltaChainIterator to record deltas as we
  712. read them.
  713. """
  714. super(PackStreamCopier, self).__init__(read_all, read_some=read_some)
  715. self.outfile = outfile
  716. self._delta_iter = delta_iter
  717. def _read(self, read, size):
  718. """Read data from the read callback and write it to the file."""
  719. data = super(PackStreamCopier, self)._read(read, size)
  720. self.outfile.write(data)
  721. return data
  722. def verify(self):
  723. """Verify a pack stream and write it to the output file.
  724. See PackStreamReader.iterobjects for a list of exceptions this may
  725. throw.
  726. """
  727. if self._delta_iter:
  728. for unpacked in self.read_objects():
  729. self._delta_iter.record(unpacked)
  730. else:
  731. for _ in self.read_objects():
  732. pass
  733. def obj_sha(type, chunks):
  734. """Compute the SHA for a numeric type and object chunks."""
  735. sha = sha1()
  736. sha.update(object_header(type, chunks_length(chunks)))
  737. for chunk in chunks:
  738. sha.update(chunk)
  739. return sha.digest()
  740. def compute_file_sha(f, start_ofs=0, end_ofs=0, buffer_size=1<<16):
  741. """Hash a portion of a file into a new SHA.
  742. :param f: A file-like object to read from that supports seek().
  743. :param start_ofs: The offset in the file to start reading at.
  744. :param end_ofs: The offset in the file to end reading at, relative to the
  745. end of the file.
  746. :param buffer_size: A buffer size for reading.
  747. :return: A new SHA object updated with data read from the file.
  748. """
  749. sha = sha1()
  750. f.seek(0, SEEK_END)
  751. todo = f.tell() + end_ofs - start_ofs
  752. f.seek(start_ofs)
  753. while todo:
  754. data = f.read(min(todo, buffer_size))
  755. sha.update(data)
  756. todo -= len(data)
  757. return sha
  758. class PackData(object):
  759. """The data contained in a packfile.
  760. Pack files can be accessed both sequentially for exploding a pack, and
  761. directly with the help of an index to retrieve a specific object.
  762. The objects within are either complete or a delta aginst another.
  763. The header is variable length. If the MSB of each byte is set then it
  764. indicates that the subsequent byte is still part of the header.
  765. For the first byte the next MS bits are the type, which tells you the type
  766. of object, and whether it is a delta. The LS byte is the lowest bits of the
  767. size. For each subsequent byte the LS 7 bits are the next MS bits of the
  768. size, i.e. the last byte of the header contains the MS bits of the size.
  769. For the complete objects the data is stored as zlib deflated data.
  770. The size in the header is the uncompressed object size, so to uncompress
  771. you need to just keep feeding data to zlib until you get an object back,
  772. or it errors on bad data. This is done here by just giving the complete
  773. buffer from the start of the deflated object on. This is bad, but until I
  774. get mmap sorted out it will have to do.
  775. Currently there are no integrity checks done. Also no attempt is made to
  776. try and detect the delta case, or a request for an object at the wrong
  777. position. It will all just throw a zlib or KeyError.
  778. """
  779. def __init__(self, filename, file=None, size=None):
  780. """Create a PackData object representing the pack in the given filename.
  781. The file must exist and stay readable until the object is disposed of. It
  782. must also stay the same size. It will be mapped whenever needed.
  783. Currently there is a restriction on the size of the pack as the python
  784. mmap implementation is flawed.
  785. """
  786. self._filename = filename
  787. self._size = size
  788. self._header_size = 12
  789. if file is None:
  790. self._file = GitFile(self._filename, 'rb')
  791. else:
  792. self._file = file
  793. (version, self._num_objects) = read_pack_header(self._file.read)
  794. self._offset_cache = LRUSizeCache(1024*1024*20,
  795. compute_size=_compute_object_size)
  796. self.pack = None
  797. @property
  798. def filename(self):
  799. return os.path.basename(self._filename)
  800. @classmethod
  801. def from_file(cls, file, size):
  802. return cls(str(file), file=file, size=size)
  803. @classmethod
  804. def from_path(cls, path):
  805. return cls(filename=path)
  806. def close(self):
  807. self._file.close()
  808. def __enter__(self):
  809. return self
  810. def __exit__(self, exc_type, exc_val, exc_tb):
  811. self.close()
  812. def _get_size(self):
  813. if self._size is not None:
  814. return self._size
  815. self._size = os.path.getsize(self._filename)
  816. if self._size < self._header_size:
  817. errmsg = ('%s is too small for a packfile (%d < %d)' %
  818. (self._filename, self._size, self._header_size))
  819. raise AssertionError(errmsg)
  820. return self._size
  821. def __len__(self):
  822. """Returns the number of objects in this pack."""
  823. return self._num_objects
  824. def calculate_checksum(self):
  825. """Calculate the checksum for this pack.
  826. :return: 20-byte binary SHA1 digest
  827. """
  828. return compute_file_sha(self._file, end_ofs=-20).digest()
  829. def get_ref(self, sha):
  830. """Get the object for a ref SHA, only looking in this pack."""
  831. # TODO: cache these results
  832. if self.pack is None:
  833. raise KeyError(sha)
  834. try:
  835. offset = self.pack.index.object_index(sha)
  836. except KeyError:
  837. offset = None
  838. if offset:
  839. type, obj = self.get_object_at(offset)
  840. elif self.pack is not None and self.pack.resolve_ext_ref:
  841. type, obj = self.pack.resolve_ext_ref(sha)
  842. else:
  843. raise KeyError(sha)
  844. return offset, type, obj
  845. def resolve_object(self, offset, type, obj, get_ref=None):
  846. """Resolve an object, possibly resolving deltas when necessary.
  847. :return: Tuple with object type and contents.
  848. """
  849. if type not in DELTA_TYPES:
  850. return type, obj
  851. if get_ref is None:
  852. get_ref = self.get_ref
  853. if type == OFS_DELTA:
  854. (delta_offset, delta) = obj
  855. # TODO: clean up asserts and replace with nicer error messages
  856. assert isinstance(offset, int) or isinstance(offset, long)
  857. assert isinstance(delta_offset, int) or isinstance(offset, long)
  858. base_offset = offset-delta_offset
  859. type, base_obj = self.get_object_at(base_offset)
  860. assert isinstance(type, int)
  861. elif type == REF_DELTA:
  862. (basename, delta) = obj
  863. assert isinstance(basename, str) and len(basename) == 20
  864. base_offset, type, base_obj = get_ref(basename)
  865. assert isinstance(type, int)
  866. type, base_chunks = self.resolve_object(base_offset, type, base_obj)
  867. chunks = apply_delta(base_chunks, delta)
  868. # TODO(dborowitz): This can result in poor performance if large base
  869. # objects are separated from deltas in the pack. We should reorganize
  870. # so that we apply deltas to all objects in a chain one after the other
  871. # to optimize cache performance.
  872. if offset is not None:
  873. self._offset_cache[offset] = type, chunks
  874. return type, chunks
  875. def iterobjects(self, progress=None, compute_crc32=True):
  876. self._file.seek(self._header_size)
  877. for i in xrange(1, self._num_objects + 1):
  878. offset = self._file.tell()
  879. unpacked, unused = unpack_object(
  880. self._file.read, compute_crc32=compute_crc32)
  881. if progress is not None:
  882. progress(i, self._num_objects)
  883. yield (offset, unpacked.pack_type_num, unpacked._obj(),
  884. unpacked.crc32)
  885. self._file.seek(-len(unused), SEEK_CUR) # Back up over unused data.
  886. def _iter_unpacked(self):
  887. # TODO(dborowitz): Merge this with iterobjects, if we can change its
  888. # return type.
  889. self._file.seek(self._header_size)
  890. for _ in xrange(self._num_objects):
  891. offset = self._file.tell()
  892. unpacked, unused = unpack_object(
  893. self._file.read, compute_crc32=False)
  894. unpacked.offset = offset
  895. yield unpacked
  896. self._file.seek(-len(unused), SEEK_CUR) # Back up over unused data.
  897. def iterentries(self, progress=None):
  898. """Yield entries summarizing the contents of this pack.
  899. :param progress: Progress function, called with current and total
  900. object count.
  901. :return: iterator of tuples with (sha, offset, crc32)
  902. """
  903. num_objects = self._num_objects
  904. resolve_ext_ref = (
  905. self.pack.resolve_ext_ref if self.pack is not None else None)
  906. indexer = PackIndexer.for_pack_data(
  907. self, resolve_ext_ref=resolve_ext_ref)
  908. for i, result in enumerate(indexer):
  909. if progress is not None:
  910. progress(i, num_objects)
  911. yield result
  912. def sorted_entries(self, progress=None):
  913. """Return entries in this pack, sorted by SHA.
  914. :param progress: Progress function, called with current and total
  915. object count
  916. :return: List of tuples with (sha, offset, crc32)
  917. """
  918. ret = list(self.iterentries(progress=progress))
  919. ret.sort()
  920. return ret
  921. def create_index_v1(self, filename, progress=None):
  922. """Create a version 1 file for this data file.
  923. :param filename: Index filename.
  924. :param progress: Progress report function
  925. :return: Checksum of index file
  926. """
  927. entries = self.sorted_entries(progress=progress)
  928. f = GitFile(filename, 'wb')
  929. try:
  930. return write_pack_index_v1(f, entries, self.calculate_checksum())
  931. finally:
  932. f.close()
  933. def create_index_v2(self, filename, progress=None):
  934. """Create a version 2 index file for this data file.
  935. :param filename: Index filename.
  936. :param progress: Progress report function
  937. :return: Checksum of index file
  938. """
  939. entries = self.sorted_entries(progress=progress)
  940. f = GitFile(filename, 'wb')
  941. try:
  942. return write_pack_index_v2(f, entries, self.calculate_checksum())
  943. finally:
  944. f.close()
  945. def create_index(self, filename, progress=None,
  946. version=2):
  947. """Create an index file for this data file.
  948. :param filename: Index filename.
  949. :param progress: Progress report function
  950. :return: Checksum of index file
  951. """
  952. if version == 1:
  953. return self.create_index_v1(filename, progress)
  954. elif version == 2:
  955. return self.create_index_v2(filename, progress)
  956. else:
  957. raise ValueError('unknown index format %d' % version)
  958. def get_stored_checksum(self):
  959. """Return the expected checksum stored in this pack."""
  960. self._file.seek(-20, SEEK_END)
  961. return self._file.read(20)
  962. def check(self):
  963. """Check the consistency of this pack."""
  964. actual = self.calculate_checksum()
  965. stored = self.get_stored_checksum()
  966. if actual != stored:
  967. raise ChecksumMismatch(stored, actual)
  968. def get_object_at(self, offset):
  969. """Given an offset in to the packfile return the object that is there.
  970. Using the associated index the location of an object can be looked up,
  971. and then the packfile can be asked directly for that object using this
  972. function.
  973. """
  974. try:
  975. return self._offset_cache[offset]
  976. except KeyError:
  977. pass
  978. assert isinstance(offset, long) or isinstance(offset, int),\
  979. 'offset was %r' % offset
  980. assert offset >= self._header_size
  981. self._file.seek(offset)
  982. unpacked, _ = unpack_object(self._file.read)
  983. return (unpacked.pack_type_num, unpacked._obj())
  984. class DeltaChainIterator(object):
  985. """Abstract iterator over pack data based on delta chains.
  986. Each object in the pack is guaranteed to be inflated exactly once,
  987. regardless of how many objects reference it as a delta base. As a result,
  988. memory usage is proportional to the length of the longest delta chain.
  989. Subclasses can override _result to define the result type of the iterator.
  990. By default, results are UnpackedObjects with the following members set:
  991. * offset
  992. * obj_type_num
  993. * obj_chunks
  994. * pack_type_num
  995. * delta_base (for delta types)
  996. * comp_chunks (if _include_comp is True)
  997. * decomp_chunks
  998. * decomp_len
  999. * crc32 (if _compute_crc32 is True)
  1000. """
  1001. _compute_crc32 = False
  1002. _include_comp = False
  1003. def __init__(self, file_obj, resolve_ext_ref=None):
  1004. self._file = file_obj
  1005. self._resolve_ext_ref = resolve_ext_ref
  1006. self._pending_ofs = defaultdict(list)
  1007. self._pending_ref = defaultdict(list)
  1008. self._full_ofs = []
  1009. self._shas = {}
  1010. self._ext_refs = []
  1011. @classmethod
  1012. def for_pack_data(cls, pack_data, resolve_ext_ref=None):
  1013. walker = cls(None, resolve_ext_ref=resolve_ext_ref)
  1014. walker.set_pack_data(pack_data)
  1015. for unpacked in pack_data._iter_unpacked():
  1016. walker.record(unpacked)
  1017. return walker
  1018. def record(self, unpacked):
  1019. type_num = unpacked.pack_type_num
  1020. offset = unpacked.offset
  1021. if type_num == OFS_DELTA:
  1022. base_offset = offset - unpacked.delta_base
  1023. self._pending_ofs[base_offset].append(offset)
  1024. elif type_num == REF_DELTA:
  1025. self._pending_ref[unpacked.delta_base].append(offset)
  1026. else:
  1027. self._full_ofs.append((offset, type_num))
  1028. def set_pack_data(self, pack_data):
  1029. self._file = pack_data._file
  1030. def _walk_all_chains(self):
  1031. for offset, type_num in self._full_ofs:
  1032. for result in self._follow_chain(offset, type_num, None):
  1033. yield result
  1034. for result in self._walk_ref_chains():
  1035. yield result
  1036. assert not self._pending_ofs
  1037. def _ensure_no_pending(self):
  1038. if self._pending_ref:
  1039. raise KeyError([sha_to_hex(s) for s in self._pending_ref])
  1040. def _walk_ref_chains(self):
  1041. if not self._resolve_ext_ref:
  1042. self._ensure_no_pending()
  1043. return
  1044. for base_sha, pending in sorted(self._pending_ref.iteritems()):
  1045. if base_sha not in self._pending_ref:
  1046. continue
  1047. try:
  1048. type_num, chunks = self._resolve_ext_ref(base_sha)
  1049. except KeyError:
  1050. # Not an external ref, but may depend on one. Either it will get
  1051. # popped via a _follow_chain call, or we will raise an error
  1052. # below.
  1053. continue
  1054. self._ext_refs.append(base_sha)
  1055. self._pending_ref.pop(base_sha)
  1056. for new_offset in pending:
  1057. for result in self._follow_chain(new_offset, type_num, chunks):
  1058. yield result
  1059. self._ensure_no_pending()
  1060. def _result(self, unpacked):
  1061. return unpacked
  1062. def _resolve_object(self, offset, obj_type_num, base_chunks):
  1063. self._file.seek(offset)
  1064. unpacked, _ = unpack_object(
  1065. self._file.read, include_comp=self._include_comp,
  1066. compute_crc32=self._compute_crc32)
  1067. unpacked.offset = offset
  1068. if base_chunks is None:
  1069. assert unpacked.pack_type_num == obj_type_num
  1070. else:
  1071. assert unpacked.pack_type_num in DELTA_TYPES
  1072. unpacked.obj_type_num = obj_type_num
  1073. unpacked.obj_chunks = apply_delta(base_chunks,
  1074. unpacked.decomp_chunks)
  1075. return unpacked
  1076. def _follow_chain(self, offset, obj_type_num, base_chunks):
  1077. # Unlike PackData.get_object_at, there is no need to cache offsets as
  1078. # this approach by design inflates each object exactly once.
  1079. unpacked = self._resolve_object(offset, obj_type_num, base_chunks)
  1080. yield self._result(unpacked)
  1081. pending = chain(self._pending_ofs.pop(unpacked.offset, []),
  1082. self._pending_ref.pop(unpacked.sha(), []))
  1083. for new_offset in pending:
  1084. for new_result in self._follow_chain(
  1085. new_offset, unpacked.obj_type_num, unpacked.obj_chunks):
  1086. yield new_result
  1087. def __iter__(self):
  1088. return self._walk_all_chains()
  1089. def ext_refs(self):
  1090. return self._ext_refs
  1091. class PackIndexer(DeltaChainIterator):
  1092. """Delta chain iterator that yields index entries."""
  1093. _compute_crc32 = True
  1094. def _result(self, unpacked):
  1095. return unpacked.sha(), unpacked.offset, unpacked.crc32
  1096. class PackInflater(DeltaChainIterator):
  1097. """Delta chain iterator that yields ShaFile objects."""
  1098. def _result(self, unpacked):
  1099. return unpacked.sha_file()
  1100. class SHA1Reader(object):
  1101. """Wrapper around a file-like object that remembers the SHA1 of its data."""
  1102. def __init__(self, f):
  1103. self.f = f
  1104. self.sha1 = sha1('')
  1105. def read(self, num=None):
  1106. data = self.f.read(num)
  1107. self.sha1.update(data)
  1108. return data
  1109. def check_sha(self):
  1110. stored = self.f.read(20)
  1111. if stored != self.sha1.digest():
  1112. raise ChecksumMismatch(self.sha1.hexdigest(), sha_to_hex(stored))
  1113. def close(self):
  1114. return self.f.close()
  1115. def tell(self):
  1116. return self.f.tell()
  1117. class SHA1Writer(object):
  1118. """Wrapper around a file-like object that remembers the SHA1 of its data."""
  1119. def __init__(self, f):
  1120. self.f = f
  1121. self.length = 0
  1122. self.sha1 = sha1('')
  1123. def write(self, data):
  1124. self.sha1.update(data)
  1125. self.f.write(data)
  1126. self.length += len(data)
  1127. def write_sha(self):
  1128. sha = self.sha1.digest()
  1129. assert len(sha) == 20
  1130. self.f.write(sha)
  1131. self.length += len(sha)
  1132. return sha
  1133. def close(self):
  1134. sha = self.write_sha()
  1135. self.f.close()
  1136. return sha
  1137. def offset(self):
  1138. return self.length
  1139. def tell(self):
  1140. return self.f.tell()
  1141. def pack_object_header(type_num, delta_base, size):
  1142. """Create a pack object header for the given object info.
  1143. :param type_num: Numeric type of the object.
  1144. :param delta_base: Delta base offset or ref, or None for whole objects.
  1145. :param size: Uncompressed object size.
  1146. :return: A header for a packed object.
  1147. """
  1148. header = ''
  1149. c = (type_num << 4) | (size & 15)
  1150. size >>= 4
  1151. while size:
  1152. header += (chr(c | 0x80))
  1153. c = size & 0x7f
  1154. size >>= 7
  1155. header += chr(c)
  1156. if type_num == OFS_DELTA:
  1157. ret = [delta_base & 0x7f]
  1158. delta_base >>= 7
  1159. while delta_base:
  1160. delta_base -= 1
  1161. ret.insert(0, 0x80 | (delta_base & 0x7f))
  1162. delta_base >>= 7
  1163. header += ''.join([chr(x) for x in ret])
  1164. elif type_num == REF_DELTA:
  1165. assert len(delta_base) == 20
  1166. header += delta_base
  1167. return header
  1168. def write_pack_object(f, type, object, sha=None):
  1169. """Write pack object to a file.
  1170. :param f: File to write to
  1171. :param type: Numeric type of the object
  1172. :param object: Object to write
  1173. :return: Tuple with offset at which the object was written, and crc32
  1174. """
  1175. if type in DELTA_TYPES:
  1176. delta_base, object = object
  1177. else:
  1178. delta_base = None
  1179. header = pack_object_header(type, delta_base, len(object))
  1180. comp_data = zlib.compress(object)
  1181. crc32 = 0
  1182. for data in (header, comp_data):
  1183. f.write(data)
  1184. if sha is not None:
  1185. sha.update(data)
  1186. crc32 = binascii.crc32(data, crc32)
  1187. return crc32 & 0xffffffff
  1188. def write_pack(filename, objects, deltify=None, delta_window_size=None):
  1189. """Write a new pack data file.
  1190. :param filename: Path to the new pack file (without .pack extension)
  1191. :param objects: Iterable of (object, path) tuples to write.
  1192. Should provide __len__
  1193. :param window_size: Delta window size
  1194. :param deltify: Whether to deltify pack objects
  1195. :return: Tuple with checksum of pack file and index file
  1196. """
  1197. f = GitFile(filename + '.pack', 'wb')
  1198. try:
  1199. entries, data_sum = write_pack_objects(f, objects,
  1200. delta_window_size=delta_window_size, deltify=deltify)
  1201. finally:
  1202. f.close()
  1203. entries = [(k, v[0], v[1]) for (k, v) in entries.iteritems()]
  1204. entries.sort()
  1205. f = GitFile(filename + '.idx', 'wb')
  1206. try:
  1207. return data_sum, write_pack_index_v2(f, entries, data_sum)
  1208. finally:
  1209. f.close()
  1210. def write_pack_header(f, num_objects):
  1211. """Write a pack header for the given number of objects."""
  1212. f.write('PACK') # Pack header
  1213. f.write(struct.pack('>L', 2)) # Pack version
  1214. f.write(struct.pack('>L', num_objects)) # Number of objects in pack
  1215. def deltify_pack_objects(objects, window_size=None):
  1216. """Generate deltas for pack objects.
  1217. :param objects: An iterable of (object, path) tuples to deltify.
  1218. :param window_size: Window size; None for default
  1219. :return: Iterator over type_num, object id, delta_base, content
  1220. delta_base is None for full text entries
  1221. """
  1222. if window_size is None:
  1223. window_size = DEFAULT_PACK_DELTA_WINDOW_SIZE
  1224. # Build a list of objects ordered by the magic Linus heuristic
  1225. # This helps us find good objects to diff against us
  1226. magic = []
  1227. for obj, path in objects:
  1228. magic.append((obj.type_num, path, -obj.raw_length(), obj))
  1229. magic.sort()
  1230. possible_bases = deque()
  1231. for type_num, path, neg_length, o in magic:
  1232. raw = o.as_raw_string()
  1233. winner = raw
  1234. winner_base = None
  1235. for base in possible_bases:
  1236. if base.type_num != type_num:
  1237. continue
  1238. delta = create_delta(base.as_raw_string(), raw)
  1239. if len(delta) < len(winner):
  1240. winner_base = base.sha().digest()
  1241. winner = delta
  1242. yield type_num, o.sha().digest(), winner_base, winner
  1243. possible_bases.appendleft(o)
  1244. while len(possible_bases) > window_size:
  1245. possible_bases.pop()
  1246. def write_pack_objects(f, objects, delta_window_size=None, deltify=False):
  1247. """Write a new pack data file.
  1248. :param f: File to write to
  1249. :param objects: Iterable of (object, path) tuples to write.
  1250. Should provide __len__
  1251. :param window_size: Sliding window size for searching for deltas;
  1252. Set to None for default window size.
  1253. :param deltify: Whether to deltify objects
  1254. :return: Dict mapping id -> (offset, crc32 checksum), pack checksum
  1255. """
  1256. if deltify:
  1257. pack_contents = deltify_pack_objects(objects, delta_window_size)
  1258. else:
  1259. pack_contents = (
  1260. (o.type_num, o.sha().digest(), None, o.as_raw_string())
  1261. for (o, path) in objects)
  1262. return write_pack_data(f, len(objects), pack_contents)
  1263. def write_pack_data(f, num_records, records):
  1264. """Write a new pack data file.
  1265. :param f: File to write to
  1266. :param num_records: Number of records
  1267. :param records: Iterator over type_num, object_id, delta_base, raw
  1268. :return: Dict mapping id -> (offset, crc32 checksum), pack checksum
  1269. """
  1270. # Write the pack
  1271. entries = {}
  1272. f = SHA1Writer(f)
  1273. write_pack_header(f, num_records)
  1274. for type_num, object_id, delta_base, raw in records:
  1275. offset = f.offset()
  1276. if delta_base is not None:
  1277. try:
  1278. base_offset, base_crc32 = entries[delta_base]
  1279. except KeyError:
  1280. type_num = REF_DELTA
  1281. raw = (delta_base, raw)
  1282. else:
  1283. type_num = OFS_DELTA
  1284. raw = (offset - base_offset, raw)
  1285. crc32 = write_pack_object(f, type_num, raw)
  1286. entries[object_id] = (offset, crc32)
  1287. return entries, f.write_sha()
  1288. def write_pack_index_v1(f, entries, pack_checksum):
  1289. """Write a new pack index file.
  1290. :param f: A file-like object to write to
  1291. :param entries: List of tuples with object name (sha), offset_in_pack,
  1292. and crc32_checksum.
  1293. :param pack_checksum: Checksum of the pack file.
  1294. :return: The SHA of the written index file
  1295. """
  1296. f = SHA1Writer(f)
  1297. fan_out_table = defaultdict(lambda: 0)
  1298. for (name, offset, entry_checksum) in entries:
  1299. fan_out_table[ord(name[0])] += 1
  1300. # Fan-out table
  1301. for i in range(0x100):
  1302. f.write(struct.pack('>L', fan_out_table[i]))
  1303. fan_out_table[i+1] += fan_out_table[i]
  1304. for (name, offset, entry_checksum) in entries:
  1305. if not (offset <= 0xffffffff):
  1306. raise TypeError("pack format 1 only supports offsets < 2Gb")
  1307. f.write(struct.pack('>L20s', offset, name))
  1308. assert len(pack_checksum) == 20
  1309. f.write(pack_checksum)
  1310. return f.write_sha()
  1311. def _delta_encode_size(size):
  1312. ret = ''
  1313. c = size & 0x7f
  1314. size >>= 7
  1315. while size:
  1316. ret += chr(c | 0x80)
  1317. c = size & 0x7f
  1318. size >>= 7
  1319. ret += chr(c)
  1320. return ret
  1321. # copy operations in git's delta format can be at most this long -
  1322. # after this you have to decompose the copy into multiple operations.
  1323. _MAX_COPY_LEN = 0xffffff
  1324. def _encode_copy_operation(start, length):
  1325. scratch = ''
  1326. op = 0x80
  1327. for i in range(4):
  1328. if start & 0xff << i*8:
  1329. scratch += chr((start >> i*8) & 0xff)
  1330. op |= 1 << i
  1331. for i in range(3):
  1332. if length & 0xff << i*8:
  1333. scratch += chr((length >> i*8) & 0xff)
  1334. op |= 1 << (4+i)
  1335. return chr(op) + scratch
  1336. def create_delta(base_buf, target_buf):
  1337. """Use python difflib to work out how to transform base_buf to target_buf.
  1338. :param base_buf: Base buffer
  1339. :param target_buf: Target buffer
  1340. """
  1341. assert isinstance(base_buf, str)
  1342. assert isinstance(target_buf, str)
  1343. out_buf = ''
  1344. # write delta header
  1345. out_buf += _delta_encode_size(len(base_buf))
  1346. out_buf += _delta_encode_size(len(target_buf))
  1347. # write out delta opcodes
  1348. seq = difflib.SequenceMatcher(a=base_buf, b=target_buf)
  1349. for opcode, i1, i2, j1, j2 in seq.get_opcodes():
  1350. # Git patch opcodes don't care about deletes!
  1351. #if opcode == 'replace' or opcode == 'delete':
  1352. # pass
  1353. if opcode == 'equal':
  1354. # If they are equal, unpacker will use data from base_buf
  1355. # Write out an opcode that says what range to use
  1356. copy_start = i1
  1357. copy_len = i2 - i1
  1358. while copy_len > 0:
  1359. to_copy = min(copy_len, _MAX_COPY_LEN)
  1360. out_buf += _encode_copy_operation(copy_start, to_copy)
  1361. copy_start += to_copy
  1362. copy_len -= to_copy
  1363. if opcode == 'replace' or opcode == 'insert':
  1364. # If we are replacing a range or adding one, then we just
  1365. # output it to the stream (prefixed by its size)
  1366. s = j2 - j1
  1367. o = j1
  1368. while s > 127:
  1369. out_buf += chr(127)
  1370. out_buf += target_buf[o:o+127]
  1371. s -= 127
  1372. o += 127
  1373. out_buf += chr(s)
  1374. out_buf += target_buf[o:o+s]
  1375. return out_buf
  1376. def apply_delta(src_buf, delta):
  1377. """Based on the similar function in git's patch-delta.c.
  1378. :param src_buf: Source buffer
  1379. :param delta: Delta instructions
  1380. """
  1381. if not isinstance(src_buf, str):
  1382. src_buf = ''.join(src_buf)
  1383. if not isinstance(delta, str):
  1384. delta = ''.join(delta)
  1385. out = []
  1386. index = 0
  1387. delta_length = len(delta)
  1388. def get_delta_header_size(delta, index):
  1389. size = 0
  1390. i = 0
  1391. while delta:
  1392. cmd = ord(delta[index])
  1393. index += 1
  1394. size |= (cmd & ~0x80) << i
  1395. i += 7
  1396. if not cmd & 0x80:
  1397. break
  1398. return size, index
  1399. src_size, index = get_delta_header_size(delta, index)
  1400. dest_size, index = get_delta_header_size(delta, index)
  1401. assert src_size == len(src_buf), '%d vs %d' % (src_size, len(src_buf))
  1402. while index < delta_length:
  1403. cmd = ord(delta[index])
  1404. index += 1
  1405. if cmd & 0x80:
  1406. cp_off = 0
  1407. for i in range(4):
  1408. if cmd & (1 << i):
  1409. x = ord(delta[index])
  1410. index += 1
  1411. cp_off |= x << (i * 8)
  1412. cp_size = 0
  1413. for i in range(3):
  1414. if cmd & (1 << (4+i)):
  1415. x = ord(delta[index])
  1416. index += 1
  1417. cp_size |= x << (i * 8)
  1418. if cp_size == 0:
  1419. cp_size = 0x10000
  1420. if (cp_off + cp_size < cp_size or
  1421. cp_off + cp_size > src_size or
  1422. cp_size > dest_size):
  1423. break
  1424. out.append(src_buf[cp_off:cp_off+cp_size])
  1425. elif cmd != 0:
  1426. out.append(delta[index:index+cmd])
  1427. index += cmd
  1428. else:
  1429. raise ApplyDeltaError('Invalid opcode 0')
  1430. if index != delta_length:
  1431. raise ApplyDeltaError('delta not empty: %r' % delta[index:])
  1432. if dest_size != chunks_length(out):
  1433. raise ApplyDeltaError('dest size incorrect')
  1434. return out
  1435. def write_pack_index_v2(f, entries, pack_checksum):
  1436. """Write a new pack index file.
  1437. :param f: File-like object to write to
  1438. :param entries: List of tuples with object name (sha), offset_in_pack, and
  1439. crc32_checksum.
  1440. :param pack_checksum: Checksum of the pack file.
  1441. :return: The SHA of the index file written
  1442. """
  1443. f = SHA1Writer(f)
  1444. f.write('\377tOc') # Magic!
  1445. f.write(struct.pack('>L', 2))
  1446. fan_out_table = defaultdict(lambda: 0)
  1447. for (name, offset, entry_checksum) in entries:
  1448. fan_out_table[ord(name[0])] += 1
  1449. # Fan-out table
  1450. largetable = []
  1451. for i in range(0x100):
  1452. f.write(struct.pack('>L', fan_out_table[i]))
  1453. fan_out_table[i+1] += fan_out_table[i]
  1454. for (name, offset, entry_checksum) in entries:
  1455. f.write(name)
  1456. for (name, offset, entry_checksum) in entries:
  1457. f.write(struct.pack('>L', entry_checksum))
  1458. for (name, offset, entry_checksum) in entries:
  1459. if offset < 2**31:
  1460. f.write(struct.pack('>L', offset))
  1461. else:
  1462. f.write(struct.pack('>L', 2**31 + len(largetable)))
  1463. largetable.append(offset)
  1464. for offset in largetable:
  1465. f.write(struct.pack('>Q', offset))
  1466. assert len(pack_checksum) == 20
  1467. f.write(pack_checksum)
  1468. return f.write_sha()
  1469. class Pack(object):
  1470. """A Git pack object."""
  1471. def __init__(self, basename, resolve_ext_ref=None):
  1472. self._basename = basename
  1473. self._data = None
  1474. self._idx = None
  1475. self._idx_path = self._basename + '.idx'
  1476. self._data_path = self._basename + '.pack'
  1477. self._data_load = lambda: PackData(self._data_path)
  1478. self._idx_load = lambda: load_pack_index(self._idx_path)
  1479. self.resolve_ext_ref = resolve_ext_ref
  1480. @classmethod
  1481. def from_lazy_objects(self, data_fn, idx_fn):
  1482. """Create a new pack object from callables to load pack data and
  1483. index objects."""
  1484. ret = Pack('')
  1485. ret._data_load = data_fn
  1486. ret._idx_load = idx_fn
  1487. return ret
  1488. @classmethod
  1489. def from_objects(self, data, idx):
  1490. """Create a new pack object from pack data and index objects."""
  1491. ret = Pack('')
  1492. ret._data_load = lambda: data
  1493. ret._idx_load = lambda: idx
  1494. return ret
  1495. def name(self):
  1496. """The SHA over the SHAs of the objects in this pack."""
  1497. return self.index.objects_sha1()
  1498. @property
  1499. def data(self):
  1500. """The pack data object being used."""
  1501. if self._data is None:
  1502. self._data = self._data_load()
  1503. self._data.pack = self
  1504. self.check_length_and_checksum()
  1505. return self._data
  1506. @property
  1507. def index(self):
  1508. """The index being used.
  1509. :note: This may be an in-memory index
  1510. """
  1511. if self._idx is None:
  1512. self._idx = self._idx_load()
  1513. return self._idx
  1514. def close(self):
  1515. if self._data is not None:
  1516. self._data.close()
  1517. if self._idx is not None:
  1518. self._idx.close()
  1519. def __enter__(self):
  1520. return self
  1521. def __exit__(self, exc_type, exc_val, exc_tb):
  1522. self.close()
  1523. def __eq__(self, other):
  1524. return isinstance(self, type(other)) and self.index == other.index
  1525. def __len__(self):
  1526. """Number of entries in this pack."""
  1527. return len(self.index)
  1528. def __repr__(self):
  1529. return '%s(%r)' % (self.__class__.__name__, self._basename)
  1530. def __iter__(self):
  1531. """Iterate over all the sha1s of the objects in this pack."""
  1532. return iter(self.index)
  1533. def check_length_and_checksum(self):
  1534. """Sanity check the length and checksum of the pack index and data."""
  1535. assert len(self.index) == len(self.data)
  1536. idx_stored_checksum = self.index.get_pack_checksum()
  1537. data_stored_checksum = self.data.get_stored_checksum()
  1538. if idx_stored_checksum != data_stored_checksum:
  1539. raise ChecksumMismatch(sha_to_hex(idx_stored_checksum),
  1540. sha_to_hex(data_stored_checksum))
  1541. def check(self):
  1542. """Check the integrity of this pack.
  1543. :raise ChecksumMismatch: if a checksum for the index or data is wrong
  1544. """
  1545. self.index.check()
  1546. self.data.check()
  1547. for obj in self.iterobjects():
  1548. obj.check()
  1549. # TODO: object connectivity checks
  1550. def get_stored_checksum(self):
  1551. return self.data.get_stored_checksum()
  1552. def __contains__(self, sha1):
  1553. """Check whether this pack contains a particular SHA1."""
  1554. try:
  1555. self.index.object_index(sha1)
  1556. return True
  1557. except KeyError:
  1558. return False
  1559. def get_raw(self, sha1):
  1560. offset = self.index.object_index(sha1)
  1561. obj_type, obj = self.data.get_object_at(offset)
  1562. type_num, chunks = self.data.resolve_object(offset, obj_type, obj)
  1563. return type_num, ''.join(chunks)
  1564. def __getitem__(self, sha1):
  1565. """Retrieve the specified SHA1."""
  1566. type, uncomp = self.get_raw(sha1)
  1567. return ShaFile.from_raw_string(type, uncomp, sha=sha1)
  1568. def iterobjects(self):
  1569. """Iterate over the objects in this pack."""
  1570. return iter(PackInflater.for_pack_data(
  1571. self.data, resolve_ext_ref=self.resolve_ext_ref))
  1572. def pack_tuples(self):
  1573. """Provide an iterable for use with write_pack_objects.
  1574. :return: Object that can iterate over (object, path) tuples
  1575. and provides __len__
  1576. """
  1577. class PackTupleIterable(object):
  1578. def __init__(self, pack):
  1579. self.pack = pack
  1580. def __len__(self):
  1581. return len(self.pack)
  1582. def __iter__(self):
  1583. return ((o, None) for o in self.pack.iterobjects())
  1584. return PackTupleIterable(self)
  1585. def keep(self, msg=None):
  1586. """Add a .keep file for the pack, preventing git from garbage collecting it.
  1587. :param msg: A message written inside the .keep file; can be used later to
  1588. determine whether or not a .keep file is obsolete.
  1589. :return: The path of the .keep file, as a string.
  1590. """
  1591. keepfile_name = '%s.keep' % self._basename
  1592. keepfile = GitFile(keepfile_name, 'wb')
  1593. try:
  1594. if msg:
  1595. keepfile.write(msg)
  1596. keepfile.write('\n')
  1597. finally:
  1598. keepfile.close()
  1599. return keepfile_name
  1600. try:
  1601. from dulwich._pack import apply_delta, bisect_find_sha
  1602. except ImportError:
  1603. pass