pack.py 65 KB

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