pack.py 63 KB

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