pack.py 77 KB

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