pack.py 103 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188
  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. # SPDX-License-Identifier: Apache-2.0 OR GPL-2.0-or-later
  6. # Dulwich is dual-licensed under the Apache License, Version 2.0 and the GNU
  7. # General Public License as published by the Free Software Foundation; version 2.0
  8. # or (at your option) any later version. You can redistribute it and/or
  9. # modify it under the terms of either of these two licenses.
  10. #
  11. # Unless required by applicable law or agreed to in writing, software
  12. # distributed under the License is distributed on an "AS IS" BASIS,
  13. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  14. # See the License for the specific language governing permissions and
  15. # limitations under the License.
  16. #
  17. # You should have received a copy of the licenses; if not, see
  18. # <http://www.gnu.org/licenses/> for a copy of the GNU General Public License
  19. # and <http://www.apache.org/licenses/LICENSE-2.0> for a copy of the Apache
  20. # License, Version 2.0.
  21. #
  22. """Classes for dealing with packed git objects.
  23. A pack is a compact representation of a bunch of objects, stored
  24. using deltas where possible.
  25. They have two parts, the pack file, which stores the data, and an index
  26. that tells you where the data is.
  27. To find an object you look in all of the index files 'til you find a
  28. match for the object name. You then use the pointer got from this as
  29. a pointer in to the corresponding packfile.
  30. """
  31. import binascii
  32. from collections import defaultdict, deque
  33. from contextlib import suppress
  34. from io import BytesIO, UnsupportedOperation
  35. try:
  36. from cdifflib import CSequenceMatcher as SequenceMatcher
  37. except ModuleNotFoundError:
  38. from difflib import SequenceMatcher
  39. import os
  40. import struct
  41. import sys
  42. import warnings
  43. import zlib
  44. from collections.abc import Iterable, Iterator, Sequence
  45. from hashlib import sha1
  46. from itertools import chain
  47. from os import SEEK_CUR, SEEK_END
  48. from struct import unpack_from
  49. from typing import (
  50. IO,
  51. TYPE_CHECKING,
  52. Any,
  53. BinaryIO,
  54. Callable,
  55. Generic,
  56. Optional,
  57. Protocol,
  58. TypeVar,
  59. Union,
  60. )
  61. try:
  62. import mmap
  63. except ImportError:
  64. has_mmap = False
  65. else:
  66. has_mmap = True
  67. if TYPE_CHECKING:
  68. from .commit_graph import CommitGraph
  69. # For some reason the above try, except fails to set has_mmap = False for plan9
  70. if sys.platform == "Plan9":
  71. has_mmap = False
  72. from . import replace_me
  73. from .errors import ApplyDeltaError, ChecksumMismatch
  74. from .file import GitFile, _GitFile
  75. from .lru_cache import LRUSizeCache
  76. from .objects import ObjectID, ShaFile, hex_to_sha, object_header, sha_to_hex
  77. OFS_DELTA = 6
  78. REF_DELTA = 7
  79. DELTA_TYPES = (OFS_DELTA, REF_DELTA)
  80. DEFAULT_PACK_DELTA_WINDOW_SIZE = 10
  81. # Keep pack files under 16Mb in memory, otherwise write them out to disk
  82. PACK_SPOOL_FILE_MAX_SIZE = 16 * 1024 * 1024
  83. # Default pack index version to use when none is specified
  84. DEFAULT_PACK_INDEX_VERSION = 2
  85. OldUnpackedObject = Union[tuple[Union[bytes, int], list[bytes]], list[bytes]]
  86. ResolveExtRefFn = Callable[[bytes], tuple[int, OldUnpackedObject]]
  87. ProgressFn = Callable[[int, str], None]
  88. PackHint = tuple[int, Optional[bytes]]
  89. class UnresolvedDeltas(Exception):
  90. """Delta objects could not be resolved."""
  91. def __init__(self, shas: list[bytes]) -> None:
  92. self.shas = shas
  93. class ObjectContainer(Protocol):
  94. def add_object(self, obj: ShaFile) -> None:
  95. """Add a single object to this object store."""
  96. def add_objects(
  97. self,
  98. objects: Sequence[tuple[ShaFile, Optional[str]]],
  99. progress: Optional[Callable[[str], None]] = None,
  100. ) -> None:
  101. """Add a set of objects to this object store.
  102. Args:
  103. objects: Iterable over a list of (object, path) tuples
  104. """
  105. def __contains__(self, sha1: bytes) -> bool:
  106. """Check if a hex sha is present."""
  107. def __getitem__(self, sha1: bytes) -> ShaFile:
  108. """Retrieve an object."""
  109. def get_commit_graph(self) -> Optional["CommitGraph"]:
  110. """Get the commit graph for this object store.
  111. Returns:
  112. CommitGraph object if available, None otherwise
  113. """
  114. return None
  115. class PackedObjectContainer(ObjectContainer):
  116. def get_unpacked_object(
  117. self, sha1: bytes, *, include_comp: bool = False
  118. ) -> "UnpackedObject":
  119. """Get a raw unresolved object."""
  120. raise NotImplementedError(self.get_unpacked_object)
  121. def iterobjects_subset(
  122. self, shas: Iterable[bytes], *, allow_missing: bool = False
  123. ) -> Iterator[ShaFile]:
  124. raise NotImplementedError(self.iterobjects_subset)
  125. def iter_unpacked_subset(
  126. self,
  127. shas: set[bytes],
  128. include_comp: bool = False,
  129. allow_missing: bool = False,
  130. convert_ofs_delta: bool = True,
  131. ) -> Iterator["UnpackedObject"]:
  132. raise NotImplementedError(self.iter_unpacked_subset)
  133. class UnpackedObjectStream:
  134. def __iter__(self) -> Iterator["UnpackedObject"]:
  135. raise NotImplementedError(self.__iter__)
  136. def __len__(self) -> int:
  137. raise NotImplementedError(self.__len__)
  138. def take_msb_bytes(
  139. read: Callable[[int], bytes], crc32: Optional[int] = None
  140. ) -> tuple[list[int], Optional[int]]:
  141. """Read bytes marked with most significant bit.
  142. Args:
  143. read: Read function
  144. """
  145. ret: list[int] = []
  146. while len(ret) == 0 or ret[-1] & 0x80:
  147. b = read(1)
  148. if crc32 is not None:
  149. crc32 = binascii.crc32(b, crc32)
  150. ret.append(ord(b[:1]))
  151. return ret, crc32
  152. class PackFileDisappeared(Exception):
  153. def __init__(self, obj: object) -> None:
  154. self.obj = obj
  155. class UnpackedObject:
  156. """Class encapsulating an object unpacked from a pack file.
  157. These objects should only be created from within unpack_object. Most
  158. members start out as empty and are filled in at various points by
  159. read_zlib_chunks, unpack_object, DeltaChainIterator, etc.
  160. End users of this object should take care that the function they're getting
  161. this object from is guaranteed to set the members they need.
  162. """
  163. __slots__ = [
  164. "_sha", # Cached binary SHA.
  165. "comp_chunks", # Compressed object chunks.
  166. "crc32", # CRC32.
  167. "decomp_chunks", # Decompressed object chunks.
  168. "decomp_len", # Decompressed length of this object.
  169. "delta_base", # Delta base offset or SHA.
  170. "obj_chunks", # Decompressed and delta-resolved chunks.
  171. "obj_type_num", # Type of this object.
  172. "offset", # Offset in its pack.
  173. "pack_type_num", # Type of this object in the pack (may be a delta).
  174. ]
  175. obj_type_num: Optional[int]
  176. obj_chunks: Optional[list[bytes]]
  177. delta_base: Union[None, bytes, int]
  178. decomp_chunks: list[bytes]
  179. comp_chunks: Optional[list[bytes]]
  180. decomp_len: Optional[int]
  181. crc32: Optional[int]
  182. offset: Optional[int]
  183. pack_type_num: int
  184. _sha: Optional[bytes]
  185. # TODO(dborowitz): read_zlib_chunks and unpack_object could very well be
  186. # methods of this object.
  187. def __init__(
  188. self,
  189. pack_type_num: int,
  190. *,
  191. delta_base: Union[None, bytes, int] = None,
  192. decomp_len: Optional[int] = None,
  193. crc32: Optional[int] = None,
  194. sha: Optional[bytes] = None,
  195. decomp_chunks: Optional[list[bytes]] = None,
  196. offset: Optional[int] = None,
  197. ) -> None:
  198. self.offset = offset
  199. self._sha = sha
  200. self.pack_type_num = pack_type_num
  201. self.delta_base = delta_base
  202. self.comp_chunks = None
  203. self.decomp_chunks: list[bytes] = decomp_chunks or []
  204. if decomp_chunks is not None and decomp_len is None:
  205. self.decomp_len = sum(map(len, decomp_chunks))
  206. else:
  207. self.decomp_len = decomp_len
  208. self.crc32 = crc32
  209. if pack_type_num in DELTA_TYPES:
  210. self.obj_type_num = None
  211. self.obj_chunks = None
  212. else:
  213. self.obj_type_num = pack_type_num
  214. self.obj_chunks = self.decomp_chunks
  215. self.delta_base = delta_base
  216. def sha(self) -> bytes:
  217. """Return the binary SHA of this object."""
  218. if self._sha is None:
  219. self._sha = obj_sha(self.obj_type_num, self.obj_chunks)
  220. return self._sha
  221. def sha_file(self) -> ShaFile:
  222. """Return a ShaFile from this object."""
  223. assert self.obj_type_num is not None and self.obj_chunks is not None
  224. return ShaFile.from_raw_chunks(self.obj_type_num, self.obj_chunks)
  225. # Only provided for backwards compatibility with code that expects either
  226. # chunks or a delta tuple.
  227. def _obj(self) -> OldUnpackedObject:
  228. """Return the decompressed chunks, or (delta base, delta chunks)."""
  229. if self.pack_type_num in DELTA_TYPES:
  230. assert isinstance(self.delta_base, (bytes, int))
  231. return (self.delta_base, self.decomp_chunks)
  232. else:
  233. return self.decomp_chunks
  234. def __eq__(self, other: object) -> bool:
  235. if not isinstance(other, UnpackedObject):
  236. return False
  237. for slot in self.__slots__:
  238. if getattr(self, slot) != getattr(other, slot):
  239. return False
  240. return True
  241. def __ne__(self, other: object) -> bool:
  242. return not (self == other)
  243. def __repr__(self) -> str:
  244. data = [f"{s}={getattr(self, s)!r}" for s in self.__slots__]
  245. return "{}({})".format(self.__class__.__name__, ", ".join(data))
  246. _ZLIB_BUFSIZE = 65536 # 64KB buffer for better I/O performance
  247. def read_zlib_chunks(
  248. read_some: Callable[[int], bytes],
  249. unpacked: UnpackedObject,
  250. include_comp: bool = False,
  251. buffer_size: int = _ZLIB_BUFSIZE,
  252. ) -> bytes:
  253. """Read zlib data from a buffer.
  254. This function requires that the buffer have additional data following the
  255. compressed data, which is guaranteed to be the case for git pack files.
  256. Args:
  257. read_some: Read function that returns at least one byte, but may
  258. return less than the requested size.
  259. unpacked: An UnpackedObject to write result data to. If its crc32
  260. attr is not None, the CRC32 of the compressed bytes will be computed
  261. using this starting CRC32.
  262. After this function, will have the following attrs set:
  263. * comp_chunks (if include_comp is True)
  264. * decomp_chunks
  265. * decomp_len
  266. * crc32
  267. include_comp: If True, include compressed data in the result.
  268. buffer_size: Size of the read buffer.
  269. Returns: Leftover unused data from the decompression.
  270. Raises:
  271. zlib.error: if a decompression error occurred.
  272. """
  273. if unpacked.decomp_len is None or unpacked.decomp_len <= -1:
  274. raise ValueError("non-negative zlib data stream size expected")
  275. decomp_obj = zlib.decompressobj()
  276. comp_chunks = []
  277. decomp_chunks = unpacked.decomp_chunks
  278. decomp_len = 0
  279. crc32 = unpacked.crc32
  280. while True:
  281. add = read_some(buffer_size)
  282. if not add:
  283. raise zlib.error("EOF before end of zlib stream")
  284. comp_chunks.append(add)
  285. decomp = decomp_obj.decompress(add)
  286. decomp_len += len(decomp)
  287. decomp_chunks.append(decomp)
  288. unused = decomp_obj.unused_data
  289. if unused:
  290. left = len(unused)
  291. if crc32 is not None:
  292. crc32 = binascii.crc32(add[:-left], crc32)
  293. if include_comp:
  294. comp_chunks[-1] = add[:-left]
  295. break
  296. elif crc32 is not None:
  297. crc32 = binascii.crc32(add, crc32)
  298. if crc32 is not None:
  299. crc32 &= 0xFFFFFFFF
  300. if decomp_len != unpacked.decomp_len:
  301. raise zlib.error("decompressed data does not match expected size")
  302. unpacked.crc32 = crc32
  303. if include_comp:
  304. unpacked.comp_chunks = comp_chunks
  305. return unused
  306. def iter_sha1(iter: Iterable[bytes]) -> bytes:
  307. """Return the hexdigest of the SHA1 over a set of names.
  308. Args:
  309. iter: Iterator over string objects
  310. Returns: 40-byte hex sha1 digest
  311. """
  312. sha = sha1()
  313. for name in iter:
  314. sha.update(name)
  315. return sha.hexdigest().encode("ascii")
  316. def load_pack_index(path: Union[str, os.PathLike]) -> "PackIndex":
  317. """Load an index file by path.
  318. Args:
  319. path: Path to the index file
  320. Returns: A PackIndex loaded from the given path
  321. """
  322. with GitFile(path, "rb") as f:
  323. return load_pack_index_file(path, f)
  324. def _load_file_contents(
  325. f: Union[IO[bytes], _GitFile], size: Optional[int] = None
  326. ) -> tuple[Union[bytes, Any], int]:
  327. try:
  328. fd = f.fileno()
  329. except (UnsupportedOperation, AttributeError):
  330. fd = None
  331. # Attempt to use mmap if possible
  332. if fd is not None:
  333. if size is None:
  334. size = os.fstat(fd).st_size
  335. if has_mmap:
  336. try:
  337. contents = mmap.mmap(fd, size, access=mmap.ACCESS_READ)
  338. except (OSError, ValueError):
  339. # Can't mmap - perhaps a socket or invalid file descriptor
  340. pass
  341. else:
  342. return contents, size
  343. contents_bytes = f.read()
  344. size = len(contents_bytes)
  345. return contents_bytes, size
  346. def load_pack_index_file(
  347. path: Union[str, os.PathLike], f: Union[IO[bytes], _GitFile]
  348. ) -> "PackIndex":
  349. """Load an index file from a file-like object.
  350. Args:
  351. path: Path for the index file
  352. f: File-like object
  353. Returns: A PackIndex loaded from the given file
  354. """
  355. contents, size = _load_file_contents(f)
  356. if contents[:4] == b"\377tOc":
  357. version = struct.unpack(b">L", contents[4:8])[0]
  358. if version == 2:
  359. return PackIndex2(path, file=f, contents=contents, size=size)
  360. elif version == 3:
  361. return PackIndex3(path, file=f, contents=contents, size=size)
  362. else:
  363. raise KeyError(f"Unknown pack index format {version}")
  364. else:
  365. return PackIndex1(path, file=f, contents=contents, size=size)
  366. def bisect_find_sha(
  367. start: int, end: int, sha: bytes, unpack_name: Callable[[int], bytes]
  368. ) -> Optional[int]:
  369. """Find a SHA in a data blob with sorted SHAs.
  370. Args:
  371. start: Start index of range to search
  372. end: End index of range to search
  373. sha: Sha to find
  374. unpack_name: Callback to retrieve SHA by index
  375. Returns: Index of the SHA, or None if it wasn't found
  376. """
  377. assert start <= end
  378. while start <= end:
  379. i = (start + end) // 2
  380. file_sha = unpack_name(i)
  381. if file_sha < sha:
  382. start = i + 1
  383. elif file_sha > sha:
  384. end = i - 1
  385. else:
  386. return i
  387. return None
  388. PackIndexEntry = tuple[bytes, int, Optional[int]]
  389. class PackIndex:
  390. """An index in to a packfile.
  391. Given a sha id of an object a pack index can tell you the location in the
  392. packfile of that object if it has it.
  393. """
  394. # Default to SHA-1 for backward compatibility
  395. hash_algorithm = 1
  396. hash_size = 20
  397. def __eq__(self, other: object) -> bool:
  398. if not isinstance(other, PackIndex):
  399. return False
  400. for (name1, _, _), (name2, _, _) in zip(
  401. self.iterentries(), other.iterentries()
  402. ):
  403. if name1 != name2:
  404. return False
  405. return True
  406. def __ne__(self, other: object) -> bool:
  407. return not self.__eq__(other)
  408. def __len__(self) -> int:
  409. """Return the number of entries in this pack index."""
  410. raise NotImplementedError(self.__len__)
  411. def __iter__(self) -> Iterator[bytes]:
  412. """Iterate over the SHAs in this pack."""
  413. return map(sha_to_hex, self._itersha())
  414. def iterentries(self) -> Iterator[PackIndexEntry]:
  415. """Iterate over the entries in this pack index.
  416. Returns: iterator over tuples with object name, offset in packfile and
  417. crc32 checksum.
  418. """
  419. raise NotImplementedError(self.iterentries)
  420. def get_pack_checksum(self) -> Optional[bytes]:
  421. """Return the SHA1 checksum stored for the corresponding packfile.
  422. Returns: 20-byte binary digest, or None if not available
  423. """
  424. raise NotImplementedError(self.get_pack_checksum)
  425. @replace_me(since="0.21.0", remove_in="0.23.0")
  426. def object_index(self, sha: bytes) -> int:
  427. return self.object_offset(sha)
  428. def object_offset(self, sha: bytes) -> int:
  429. """Return the offset in to the corresponding packfile for the object.
  430. Given the name of an object it will return the offset that object
  431. lives at within the corresponding pack file. If the pack file doesn't
  432. have the object then None will be returned.
  433. """
  434. raise NotImplementedError(self.object_offset)
  435. def object_sha1(self, index: int) -> bytes:
  436. """Return the SHA1 corresponding to the index in the pack file."""
  437. for name, offset, _crc32 in self.iterentries():
  438. if offset == index:
  439. return name
  440. else:
  441. raise KeyError(index)
  442. def _object_offset(self, sha: bytes) -> int:
  443. """See object_offset.
  444. Args:
  445. sha: A *binary* SHA string. (20 characters long)_
  446. """
  447. raise NotImplementedError(self._object_offset)
  448. def objects_sha1(self) -> bytes:
  449. """Return the hex SHA1 over all the shas of all objects in this pack.
  450. Note: This is used for the filename of the pack.
  451. """
  452. return iter_sha1(self._itersha())
  453. def _itersha(self) -> Iterator[bytes]:
  454. """Yield all the SHA1's of the objects in the index, sorted."""
  455. raise NotImplementedError(self._itersha)
  456. def close(self) -> None:
  457. pass
  458. def check(self) -> None:
  459. pass
  460. class MemoryPackIndex(PackIndex):
  461. """Pack index that is stored entirely in memory."""
  462. def __init__(
  463. self,
  464. entries: list[tuple[bytes, int, Optional[int]]],
  465. pack_checksum: Optional[bytes] = None,
  466. ) -> None:
  467. """Create a new MemoryPackIndex.
  468. Args:
  469. entries: Sequence of name, idx, crc32 (sorted)
  470. pack_checksum: Optional pack checksum
  471. """
  472. self._by_sha = {}
  473. self._by_offset = {}
  474. for name, offset, _crc32 in entries:
  475. self._by_sha[name] = offset
  476. self._by_offset[offset] = name
  477. self._entries = entries
  478. self._pack_checksum = pack_checksum
  479. def get_pack_checksum(self) -> Optional[bytes]:
  480. return self._pack_checksum
  481. def __len__(self) -> int:
  482. return len(self._entries)
  483. def object_offset(self, sha: bytes) -> int:
  484. if len(sha) == 40:
  485. sha = hex_to_sha(sha)
  486. return self._by_sha[sha]
  487. def object_sha1(self, offset: int) -> bytes:
  488. return self._by_offset[offset]
  489. def _itersha(self) -> Iterator[bytes]:
  490. return iter(self._by_sha)
  491. def iterentries(self) -> Iterator[PackIndexEntry]:
  492. return iter(self._entries)
  493. @classmethod
  494. def for_pack(cls, pack_data: "PackData") -> "MemoryPackIndex":
  495. return MemoryPackIndex(
  496. list(pack_data.sorted_entries()), pack_data.get_stored_checksum()
  497. )
  498. @classmethod
  499. def clone(cls, other_index: "PackIndex") -> "MemoryPackIndex":
  500. return cls(list(other_index.iterentries()), other_index.get_pack_checksum())
  501. class FilePackIndex(PackIndex):
  502. """Pack index that is based on a file.
  503. To do the loop it opens the file, and indexes first 256 4 byte groups
  504. with the first byte of the sha id. The value in the four byte group indexed
  505. is the end of the group that shares the same starting byte. Subtract one
  506. from the starting byte and index again to find the start of the group.
  507. The values are sorted by sha id within the group, so do the math to find
  508. the start and end offset and then bisect in to find if the value is
  509. present.
  510. """
  511. _fan_out_table: list[int]
  512. def __init__(
  513. self,
  514. filename: Union[str, os.PathLike],
  515. file: Optional[BinaryIO] = None,
  516. contents: Optional[Union[bytes, "mmap.mmap"]] = None,
  517. size: Optional[int] = None,
  518. ) -> None:
  519. """Create a pack index object.
  520. Provide it with the name of the index file to consider, and it will map
  521. it whenever required.
  522. """
  523. self._filename = filename
  524. # Take the size now, so it can be checked each time we map the file to
  525. # ensure that it hasn't changed.
  526. if file is None:
  527. self._file = GitFile(filename, "rb")
  528. else:
  529. self._file = file
  530. if contents is None:
  531. self._contents, self._size = _load_file_contents(self._file, size)
  532. else:
  533. self._contents = contents
  534. self._size = size if size is not None else len(contents)
  535. @property
  536. def path(self) -> str:
  537. return os.fspath(self._filename)
  538. def __eq__(self, other: object) -> bool:
  539. # Quick optimization:
  540. if (
  541. isinstance(other, FilePackIndex)
  542. and self._fan_out_table != other._fan_out_table
  543. ):
  544. return False
  545. return super().__eq__(other)
  546. def close(self) -> None:
  547. self._file.close()
  548. close_fn = getattr(self._contents, "close", None)
  549. if close_fn is not None:
  550. close_fn()
  551. def __len__(self) -> int:
  552. """Return the number of entries in this pack index."""
  553. return self._fan_out_table[-1]
  554. def _unpack_entry(self, i: int) -> PackIndexEntry:
  555. """Unpack the i-th entry in the index file.
  556. Returns: Tuple with object name (SHA), offset in pack file and CRC32
  557. checksum (if known).
  558. """
  559. raise NotImplementedError(self._unpack_entry)
  560. def _unpack_name(self, i) -> bytes:
  561. """Unpack the i-th name from the index file."""
  562. raise NotImplementedError(self._unpack_name)
  563. def _unpack_offset(self, i) -> int:
  564. """Unpack the i-th object offset from the index file."""
  565. raise NotImplementedError(self._unpack_offset)
  566. def _unpack_crc32_checksum(self, i) -> Optional[int]:
  567. """Unpack the crc32 checksum for the ith object from the index file."""
  568. raise NotImplementedError(self._unpack_crc32_checksum)
  569. def _itersha(self) -> Iterator[bytes]:
  570. for i in range(len(self)):
  571. yield self._unpack_name(i)
  572. def iterentries(self) -> Iterator[PackIndexEntry]:
  573. """Iterate over the entries in this pack index.
  574. Returns: iterator over tuples with object name, offset in packfile and
  575. crc32 checksum.
  576. """
  577. for i in range(len(self)):
  578. yield self._unpack_entry(i)
  579. def _read_fan_out_table(self, start_offset: int) -> list[int]:
  580. ret = []
  581. for i in range(0x100):
  582. fanout_entry = self._contents[
  583. start_offset + i * 4 : start_offset + (i + 1) * 4
  584. ]
  585. ret.append(struct.unpack(">L", fanout_entry)[0])
  586. return ret
  587. def check(self) -> None:
  588. """Check that the stored checksum matches the actual checksum."""
  589. actual = self.calculate_checksum()
  590. stored = self.get_stored_checksum()
  591. if actual != stored:
  592. raise ChecksumMismatch(stored, actual)
  593. def calculate_checksum(self) -> bytes:
  594. """Calculate the SHA1 checksum over this pack index.
  595. Returns: This is a 20-byte binary digest
  596. """
  597. return sha1(self._contents[:-20]).digest()
  598. def get_pack_checksum(self) -> bytes:
  599. """Return the SHA1 checksum stored for the corresponding packfile.
  600. Returns: 20-byte binary digest
  601. """
  602. return bytes(self._contents[-40:-20])
  603. def get_stored_checksum(self) -> bytes:
  604. """Return the SHA1 checksum stored for this index.
  605. Returns: 20-byte binary digest
  606. """
  607. return bytes(self._contents[-20:])
  608. def object_offset(self, sha: bytes) -> int:
  609. """Return the offset in to the corresponding packfile for the object.
  610. Given the name of an object it will return the offset that object
  611. lives at within the corresponding pack file. If the pack file doesn't
  612. have the object then None will be returned.
  613. """
  614. if len(sha) == 40:
  615. sha = hex_to_sha(sha)
  616. try:
  617. return self._object_offset(sha)
  618. except ValueError as exc:
  619. closed = getattr(self._contents, "closed", None)
  620. if closed in (None, True):
  621. raise PackFileDisappeared(self) from exc
  622. raise
  623. def _object_offset(self, sha: bytes) -> int:
  624. """See object_offset.
  625. Args:
  626. sha: A *binary* SHA string. (20 characters long)_
  627. """
  628. assert len(sha) == 20
  629. idx = ord(sha[:1])
  630. if idx == 0:
  631. start = 0
  632. else:
  633. start = self._fan_out_table[idx - 1]
  634. end = self._fan_out_table[idx]
  635. i = bisect_find_sha(start, end, sha, self._unpack_name)
  636. if i is None:
  637. raise KeyError(sha)
  638. return self._unpack_offset(i)
  639. def iter_prefix(self, prefix: bytes) -> Iterator[bytes]:
  640. """Iterate over all SHA1s with the given prefix."""
  641. start = ord(prefix[:1])
  642. if start == 0:
  643. start = 0
  644. else:
  645. start = self._fan_out_table[start - 1]
  646. end = ord(prefix[:1]) + 1
  647. if end == 0x100:
  648. end = len(self)
  649. else:
  650. end = self._fan_out_table[end]
  651. assert start <= end
  652. started = False
  653. for i in range(start, end):
  654. name: bytes = self._unpack_name(i)
  655. if name.startswith(prefix):
  656. yield name
  657. started = True
  658. elif started:
  659. break
  660. class PackIndex1(FilePackIndex):
  661. """Version 1 Pack Index file."""
  662. def __init__(
  663. self, filename: Union[str, os.PathLike], file=None, contents=None, size=None
  664. ) -> None:
  665. super().__init__(filename, file, contents, size)
  666. self.version = 1
  667. self._fan_out_table = self._read_fan_out_table(0)
  668. def _unpack_entry(self, i):
  669. (offset, name) = unpack_from(">L20s", self._contents, (0x100 * 4) + (i * 24))
  670. return (name, offset, None)
  671. def _unpack_name(self, i):
  672. offset = (0x100 * 4) + (i * 24) + 4
  673. return self._contents[offset : offset + 20]
  674. def _unpack_offset(self, i):
  675. offset = (0x100 * 4) + (i * 24)
  676. return unpack_from(">L", self._contents, offset)[0]
  677. def _unpack_crc32_checksum(self, i) -> None:
  678. # Not stored in v1 index files
  679. return None
  680. class PackIndex2(FilePackIndex):
  681. """Version 2 Pack Index file."""
  682. def __init__(
  683. self, filename: Union[str, os.PathLike], file=None, contents=None, size=None
  684. ) -> None:
  685. super().__init__(filename, file, contents, size)
  686. if self._contents[:4] != b"\377tOc":
  687. raise AssertionError("Not a v2 pack index file")
  688. (self.version,) = unpack_from(b">L", self._contents, 4)
  689. if self.version != 2:
  690. raise AssertionError(f"Version was {self.version}")
  691. self._fan_out_table = self._read_fan_out_table(8)
  692. self._name_table_offset = 8 + 0x100 * 4
  693. self._crc32_table_offset = self._name_table_offset + 20 * len(self)
  694. self._pack_offset_table_offset = self._crc32_table_offset + 4 * len(self)
  695. self._pack_offset_largetable_offset = self._pack_offset_table_offset + 4 * len(
  696. self
  697. )
  698. def _unpack_entry(self, i):
  699. return (
  700. self._unpack_name(i),
  701. self._unpack_offset(i),
  702. self._unpack_crc32_checksum(i),
  703. )
  704. def _unpack_name(self, i):
  705. offset = self._name_table_offset + i * 20
  706. return self._contents[offset : offset + 20]
  707. def _unpack_offset(self, i):
  708. offset = self._pack_offset_table_offset + i * 4
  709. offset = unpack_from(">L", self._contents, offset)[0]
  710. if offset & (2**31):
  711. offset = self._pack_offset_largetable_offset + (offset & (2**31 - 1)) * 8
  712. offset = unpack_from(">Q", self._contents, offset)[0]
  713. return offset
  714. def _unpack_crc32_checksum(self, i):
  715. return unpack_from(">L", self._contents, self._crc32_table_offset + i * 4)[0]
  716. class PackIndex3(FilePackIndex):
  717. """Version 3 Pack Index file.
  718. Supports variable hash sizes for SHA-1 (20 bytes) and SHA-256 (32 bytes).
  719. """
  720. def __init__(
  721. self, filename: Union[str, os.PathLike], file=None, contents=None, size=None
  722. ) -> None:
  723. super().__init__(filename, file, contents, size)
  724. if self._contents[:4] != b"\377tOc":
  725. raise AssertionError("Not a v3 pack index file")
  726. (self.version,) = unpack_from(b">L", self._contents, 4)
  727. if self.version != 3:
  728. raise AssertionError(f"Version was {self.version}")
  729. # Read hash algorithm identifier (1 = SHA-1, 2 = SHA-256)
  730. (self.hash_algorithm,) = unpack_from(b">L", self._contents, 8)
  731. if self.hash_algorithm == 1:
  732. self.hash_size = 20 # SHA-1
  733. elif self.hash_algorithm == 2:
  734. self.hash_size = 32 # SHA-256
  735. else:
  736. raise AssertionError(f"Unknown hash algorithm {self.hash_algorithm}")
  737. # Read length of shortened object names
  738. (self.shortened_oid_len,) = unpack_from(b">L", self._contents, 12)
  739. # Calculate offsets based on variable hash size
  740. self._fan_out_table = self._read_fan_out_table(
  741. 16
  742. ) # After header (4 + 4 + 4 + 4)
  743. self._name_table_offset = 16 + 0x100 * 4
  744. self._crc32_table_offset = self._name_table_offset + self.hash_size * len(self)
  745. self._pack_offset_table_offset = self._crc32_table_offset + 4 * len(self)
  746. self._pack_offset_largetable_offset = self._pack_offset_table_offset + 4 * len(
  747. self
  748. )
  749. def _unpack_entry(self, i):
  750. return (
  751. self._unpack_name(i),
  752. self._unpack_offset(i),
  753. self._unpack_crc32_checksum(i),
  754. )
  755. def _unpack_name(self, i):
  756. offset = self._name_table_offset + i * self.hash_size
  757. return self._contents[offset : offset + self.hash_size]
  758. def _unpack_offset(self, i):
  759. offset = self._pack_offset_table_offset + i * 4
  760. offset = unpack_from(">L", self._contents, offset)[0]
  761. if offset & (2**31):
  762. offset = self._pack_offset_largetable_offset + (offset & (2**31 - 1)) * 8
  763. offset = unpack_from(">Q", self._contents, offset)[0]
  764. return offset
  765. def _unpack_crc32_checksum(self, i):
  766. return unpack_from(">L", self._contents, self._crc32_table_offset + i * 4)[0]
  767. def read_pack_header(read) -> tuple[int, int]:
  768. """Read the header of a pack file.
  769. Args:
  770. read: Read function
  771. Returns: Tuple of (pack version, number of objects). If no data is
  772. available to read, returns (None, None).
  773. """
  774. header = read(12)
  775. if not header:
  776. raise AssertionError("file too short to contain pack")
  777. if header[:4] != b"PACK":
  778. raise AssertionError(f"Invalid pack header {header!r}")
  779. (version,) = unpack_from(b">L", header, 4)
  780. if version not in (2, 3):
  781. raise AssertionError(f"Version was {version}")
  782. (num_objects,) = unpack_from(b">L", header, 8)
  783. return (version, num_objects)
  784. def chunks_length(chunks: Union[bytes, Iterable[bytes]]) -> int:
  785. if isinstance(chunks, bytes):
  786. return len(chunks)
  787. else:
  788. return sum(map(len, chunks))
  789. def unpack_object(
  790. read_all: Callable[[int], bytes],
  791. read_some: Optional[Callable[[int], bytes]] = None,
  792. compute_crc32=False,
  793. include_comp=False,
  794. zlib_bufsize=_ZLIB_BUFSIZE,
  795. ) -> tuple[UnpackedObject, bytes]:
  796. """Unpack a Git object.
  797. Args:
  798. read_all: Read function that blocks until the number of requested
  799. bytes are read.
  800. read_some: Read function that returns at least one byte, but may not
  801. return the number of bytes requested.
  802. compute_crc32: If True, compute the CRC32 of the compressed data. If
  803. False, the returned CRC32 will be None.
  804. include_comp: If True, include compressed data in the result.
  805. zlib_bufsize: An optional buffer size for zlib operations.
  806. Returns: A tuple of (unpacked, unused), where unused is the unused data
  807. leftover from decompression, and unpacked in an UnpackedObject with
  808. the following attrs set:
  809. * obj_chunks (for non-delta types)
  810. * pack_type_num
  811. * delta_base (for delta types)
  812. * comp_chunks (if include_comp is True)
  813. * decomp_chunks
  814. * decomp_len
  815. * crc32 (if compute_crc32 is True)
  816. """
  817. if read_some is None:
  818. read_some = read_all
  819. if compute_crc32:
  820. crc32 = 0
  821. else:
  822. crc32 = None
  823. raw, crc32 = take_msb_bytes(read_all, crc32=crc32)
  824. type_num = (raw[0] >> 4) & 0x07
  825. size = raw[0] & 0x0F
  826. for i, byte in enumerate(raw[1:]):
  827. size += (byte & 0x7F) << ((i * 7) + 4)
  828. delta_base: Union[int, bytes, None]
  829. raw_base = len(raw)
  830. if type_num == OFS_DELTA:
  831. raw, crc32 = take_msb_bytes(read_all, crc32=crc32)
  832. raw_base += len(raw)
  833. if raw[-1] & 0x80:
  834. raise AssertionError
  835. delta_base_offset = raw[0] & 0x7F
  836. for byte in raw[1:]:
  837. delta_base_offset += 1
  838. delta_base_offset <<= 7
  839. delta_base_offset += byte & 0x7F
  840. delta_base = delta_base_offset
  841. elif type_num == REF_DELTA:
  842. delta_base_obj = read_all(20)
  843. if crc32 is not None:
  844. crc32 = binascii.crc32(delta_base_obj, crc32)
  845. delta_base = delta_base_obj
  846. raw_base += 20
  847. else:
  848. delta_base = None
  849. unpacked = UnpackedObject(
  850. type_num, delta_base=delta_base, decomp_len=size, crc32=crc32
  851. )
  852. unused = read_zlib_chunks(
  853. read_some,
  854. unpacked,
  855. buffer_size=zlib_bufsize,
  856. include_comp=include_comp,
  857. )
  858. return unpacked, unused
  859. def _compute_object_size(value):
  860. """Compute the size of a unresolved object for use with LRUSizeCache."""
  861. (num, obj) = value
  862. if num in DELTA_TYPES:
  863. return chunks_length(obj[1])
  864. return chunks_length(obj)
  865. class PackStreamReader:
  866. """Class to read a pack stream.
  867. The pack is read from a ReceivableProtocol using read() or recv() as
  868. appropriate.
  869. """
  870. def __init__(self, read_all, read_some=None, zlib_bufsize=_ZLIB_BUFSIZE) -> None:
  871. self.read_all = read_all
  872. if read_some is None:
  873. self.read_some = read_all
  874. else:
  875. self.read_some = read_some
  876. self.sha = sha1()
  877. self._offset = 0
  878. self._rbuf = BytesIO()
  879. # trailer is a deque to avoid memory allocation on small reads
  880. self._trailer: deque[bytes] = deque()
  881. self._zlib_bufsize = zlib_bufsize
  882. def _read(self, read, size):
  883. """Read up to size bytes using the given callback.
  884. As a side effect, update the verifier's hash (excluding the last 20
  885. bytes read).
  886. Args:
  887. read: The read callback to read from.
  888. size: The maximum number of bytes to read; the particular
  889. behavior is callback-specific.
  890. """
  891. data = read(size)
  892. # maintain a trailer of the last 20 bytes we've read
  893. n = len(data)
  894. self._offset += n
  895. tn = len(self._trailer)
  896. if n >= 20:
  897. to_pop = tn
  898. to_add = 20
  899. else:
  900. to_pop = max(n + tn - 20, 0)
  901. to_add = n
  902. self.sha.update(
  903. bytes(bytearray([self._trailer.popleft() for _ in range(to_pop)]))
  904. )
  905. self._trailer.extend(data[-to_add:])
  906. # hash everything but the trailer
  907. self.sha.update(data[:-to_add])
  908. return data
  909. def _buf_len(self):
  910. buf = self._rbuf
  911. start = buf.tell()
  912. buf.seek(0, SEEK_END)
  913. end = buf.tell()
  914. buf.seek(start)
  915. return end - start
  916. @property
  917. def offset(self):
  918. return self._offset - self._buf_len()
  919. def read(self, size):
  920. """Read, blocking until size bytes are read."""
  921. buf_len = self._buf_len()
  922. if buf_len >= size:
  923. return self._rbuf.read(size)
  924. buf_data = self._rbuf.read()
  925. self._rbuf = BytesIO()
  926. return buf_data + self._read(self.read_all, size - buf_len)
  927. def recv(self, size):
  928. """Read up to size bytes, blocking until one byte is read."""
  929. buf_len = self._buf_len()
  930. if buf_len:
  931. data = self._rbuf.read(size)
  932. if size >= buf_len:
  933. self._rbuf = BytesIO()
  934. return data
  935. return self._read(self.read_some, size)
  936. def __len__(self) -> int:
  937. return self._num_objects
  938. def read_objects(self, compute_crc32=False) -> Iterator[UnpackedObject]:
  939. """Read the objects in this pack file.
  940. Args:
  941. compute_crc32: If True, compute the CRC32 of the compressed
  942. data. If False, the returned CRC32 will be None.
  943. Returns: Iterator over UnpackedObjects with the following members set:
  944. offset
  945. obj_type_num
  946. obj_chunks (for non-delta types)
  947. delta_base (for delta types)
  948. decomp_chunks
  949. decomp_len
  950. crc32 (if compute_crc32 is True)
  951. Raises:
  952. ChecksumMismatch: if the checksum of the pack contents does not
  953. match the checksum in the pack trailer.
  954. zlib.error: if an error occurred during zlib decompression.
  955. IOError: if an error occurred writing to the output file.
  956. """
  957. pack_version, self._num_objects = read_pack_header(self.read)
  958. for _ in range(self._num_objects):
  959. offset = self.offset
  960. unpacked, unused = unpack_object(
  961. self.read,
  962. read_some=self.recv,
  963. compute_crc32=compute_crc32,
  964. zlib_bufsize=self._zlib_bufsize,
  965. )
  966. unpacked.offset = offset
  967. # prepend any unused data to current read buffer
  968. buf = BytesIO()
  969. buf.write(unused)
  970. buf.write(self._rbuf.read())
  971. buf.seek(0)
  972. self._rbuf = buf
  973. yield unpacked
  974. if self._buf_len() < 20:
  975. # If the read buffer is full, then the last read() got the whole
  976. # trailer off the wire. If not, it means there is still some of the
  977. # trailer to read. We need to read() all 20 bytes; N come from the
  978. # read buffer and (20 - N) come from the wire.
  979. self.read(20)
  980. pack_sha = bytearray(self._trailer) # type: ignore
  981. if pack_sha != self.sha.digest():
  982. raise ChecksumMismatch(sha_to_hex(pack_sha), self.sha.hexdigest())
  983. class PackStreamCopier(PackStreamReader):
  984. """Class to verify a pack stream as it is being read.
  985. The pack is read from a ReceivableProtocol using read() or recv() as
  986. appropriate and written out to the given file-like object.
  987. """
  988. def __init__(self, read_all, read_some, outfile, delta_iter=None) -> None:
  989. """Initialize the copier.
  990. Args:
  991. read_all: Read function that blocks until the number of
  992. requested bytes are read.
  993. read_some: Read function that returns at least one byte, but may
  994. not return the number of bytes requested.
  995. outfile: File-like object to write output through.
  996. delta_iter: Optional DeltaChainIterator to record deltas as we
  997. read them.
  998. """
  999. super().__init__(read_all, read_some=read_some)
  1000. self.outfile = outfile
  1001. self._delta_iter = delta_iter
  1002. def _read(self, read, size):
  1003. """Read data from the read callback and write it to the file."""
  1004. data = super()._read(read, size)
  1005. self.outfile.write(data)
  1006. return data
  1007. def verify(self, progress=None) -> None:
  1008. """Verify a pack stream and write it to the output file.
  1009. See PackStreamReader.iterobjects for a list of exceptions this may
  1010. throw.
  1011. """
  1012. i = 0 # default count of entries if read_objects() is empty
  1013. for i, unpacked in enumerate(self.read_objects()):
  1014. if self._delta_iter:
  1015. self._delta_iter.record(unpacked)
  1016. if progress is not None:
  1017. progress(f"copying pack entries: {i}/{len(self)}\r".encode("ascii"))
  1018. if progress is not None:
  1019. progress(f"copied {i} pack entries\n".encode("ascii"))
  1020. def obj_sha(type, chunks):
  1021. """Compute the SHA for a numeric type and object chunks."""
  1022. sha = sha1()
  1023. sha.update(object_header(type, chunks_length(chunks)))
  1024. if isinstance(chunks, bytes):
  1025. sha.update(chunks)
  1026. else:
  1027. for chunk in chunks:
  1028. sha.update(chunk)
  1029. return sha.digest()
  1030. def compute_file_sha(f, start_ofs=0, end_ofs=0, buffer_size=1 << 16):
  1031. """Hash a portion of a file into a new SHA.
  1032. Args:
  1033. f: A file-like object to read from that supports seek().
  1034. start_ofs: The offset in the file to start reading at.
  1035. end_ofs: The offset in the file to end reading at, relative to the
  1036. end of the file.
  1037. buffer_size: A buffer size for reading.
  1038. Returns: A new SHA object updated with data read from the file.
  1039. """
  1040. sha = sha1()
  1041. f.seek(0, SEEK_END)
  1042. length = f.tell()
  1043. if (end_ofs < 0 and length + end_ofs < start_ofs) or end_ofs > length:
  1044. raise AssertionError(
  1045. f"Attempt to read beyond file length. start_ofs: {start_ofs}, end_ofs: {end_ofs}, file length: {length}"
  1046. )
  1047. todo = length + end_ofs - start_ofs
  1048. f.seek(start_ofs)
  1049. while todo:
  1050. data = f.read(min(todo, buffer_size))
  1051. sha.update(data)
  1052. todo -= len(data)
  1053. return sha
  1054. class PackData:
  1055. """The data contained in a packfile.
  1056. Pack files can be accessed both sequentially for exploding a pack, and
  1057. directly with the help of an index to retrieve a specific object.
  1058. The objects within are either complete or a delta against another.
  1059. The header is variable length. If the MSB of each byte is set then it
  1060. indicates that the subsequent byte is still part of the header.
  1061. For the first byte the next MS bits are the type, which tells you the type
  1062. of object, and whether it is a delta. The LS byte is the lowest bits of the
  1063. size. For each subsequent byte the LS 7 bits are the next MS bits of the
  1064. size, i.e. the last byte of the header contains the MS bits of the size.
  1065. For the complete objects the data is stored as zlib deflated data.
  1066. The size in the header is the uncompressed object size, so to uncompress
  1067. you need to just keep feeding data to zlib until you get an object back,
  1068. or it errors on bad data. This is done here by just giving the complete
  1069. buffer from the start of the deflated object on. This is bad, but until I
  1070. get mmap sorted out it will have to do.
  1071. Currently there are no integrity checks done. Also no attempt is made to
  1072. try and detect the delta case, or a request for an object at the wrong
  1073. position. It will all just throw a zlib or KeyError.
  1074. """
  1075. def __init__(
  1076. self,
  1077. filename: Union[str, os.PathLike],
  1078. file=None,
  1079. size=None,
  1080. *,
  1081. delta_window_size=None,
  1082. window_memory=None,
  1083. delta_cache_size=None,
  1084. depth=None,
  1085. threads=None,
  1086. big_file_threshold=None,
  1087. ) -> None:
  1088. """Create a PackData object representing the pack in the given filename.
  1089. The file must exist and stay readable until the object is disposed of.
  1090. It must also stay the same size. It will be mapped whenever needed.
  1091. Currently there is a restriction on the size of the pack as the python
  1092. mmap implementation is flawed.
  1093. """
  1094. self._filename = filename
  1095. self._size = size
  1096. self._header_size = 12
  1097. self.delta_window_size = delta_window_size
  1098. self.window_memory = window_memory
  1099. self.delta_cache_size = delta_cache_size
  1100. self.depth = depth
  1101. self.threads = threads
  1102. self.big_file_threshold = big_file_threshold
  1103. if file is None:
  1104. self._file = GitFile(self._filename, "rb")
  1105. else:
  1106. self._file = file
  1107. (version, self._num_objects) = read_pack_header(self._file.read)
  1108. # Use delta_cache_size config if available, otherwise default
  1109. cache_size = delta_cache_size or (1024 * 1024 * 20)
  1110. self._offset_cache = LRUSizeCache[int, tuple[int, OldUnpackedObject]](
  1111. cache_size, compute_size=_compute_object_size
  1112. )
  1113. @property
  1114. def filename(self):
  1115. return os.path.basename(self._filename)
  1116. @property
  1117. def path(self):
  1118. return self._filename
  1119. @classmethod
  1120. def from_file(cls, file, size=None):
  1121. return cls(str(file), file=file, size=size)
  1122. @classmethod
  1123. def from_path(cls, path: Union[str, os.PathLike]):
  1124. return cls(filename=path)
  1125. def close(self) -> None:
  1126. self._file.close()
  1127. def __enter__(self):
  1128. return self
  1129. def __exit__(self, exc_type, exc_val, exc_tb):
  1130. self.close()
  1131. def __eq__(self, other):
  1132. if isinstance(other, PackData):
  1133. return self.get_stored_checksum() == other.get_stored_checksum()
  1134. return False
  1135. def _get_size(self):
  1136. if self._size is not None:
  1137. return self._size
  1138. self._size = os.path.getsize(self._filename)
  1139. if self._size < self._header_size:
  1140. errmsg = f"{self._filename} is too small for a packfile ({self._size} < {self._header_size})"
  1141. raise AssertionError(errmsg)
  1142. return self._size
  1143. def __len__(self) -> int:
  1144. """Returns the number of objects in this pack."""
  1145. return self._num_objects
  1146. def calculate_checksum(self):
  1147. """Calculate the checksum for this pack.
  1148. Returns: 20-byte binary SHA1 digest
  1149. """
  1150. return compute_file_sha(self._file, end_ofs=-20).digest()
  1151. def iter_unpacked(self, *, include_comp: bool = False):
  1152. self._file.seek(self._header_size)
  1153. if self._num_objects is None:
  1154. return
  1155. for _ in range(self._num_objects):
  1156. offset = self._file.tell()
  1157. unpacked, unused = unpack_object(
  1158. self._file.read, compute_crc32=False, include_comp=include_comp
  1159. )
  1160. unpacked.offset = offset
  1161. yield unpacked
  1162. # Back up over unused data.
  1163. self._file.seek(-len(unused), SEEK_CUR)
  1164. def iterentries(
  1165. self, progress=None, resolve_ext_ref: Optional[ResolveExtRefFn] = None
  1166. ):
  1167. """Yield entries summarizing the contents of this pack.
  1168. Args:
  1169. progress: Progress function, called with current and total
  1170. object count.
  1171. Returns: iterator of tuples with (sha, offset, crc32)
  1172. """
  1173. num_objects = self._num_objects
  1174. indexer = PackIndexer.for_pack_data(self, resolve_ext_ref=resolve_ext_ref)
  1175. for i, result in enumerate(indexer):
  1176. if progress is not None:
  1177. progress(i, num_objects)
  1178. yield result
  1179. def sorted_entries(
  1180. self,
  1181. progress: Optional[ProgressFn] = None,
  1182. resolve_ext_ref: Optional[ResolveExtRefFn] = None,
  1183. ):
  1184. """Return entries in this pack, sorted by SHA.
  1185. Args:
  1186. progress: Progress function, called with current and total
  1187. object count
  1188. Returns: Iterator of tuples with (sha, offset, crc32)
  1189. """
  1190. return sorted(
  1191. self.iterentries(progress=progress, resolve_ext_ref=resolve_ext_ref)
  1192. )
  1193. def create_index_v1(self, filename, progress=None, resolve_ext_ref=None):
  1194. """Create a version 1 file for this data file.
  1195. Args:
  1196. filename: Index filename.
  1197. progress: Progress report function
  1198. Returns: Checksum of index file
  1199. """
  1200. entries = self.sorted_entries(
  1201. progress=progress, resolve_ext_ref=resolve_ext_ref
  1202. )
  1203. with GitFile(filename, "wb") as f:
  1204. return write_pack_index_v1(f, entries, self.calculate_checksum())
  1205. def create_index_v2(self, filename, progress=None, resolve_ext_ref=None):
  1206. """Create a version 2 index file for this data file.
  1207. Args:
  1208. filename: Index filename.
  1209. progress: Progress report function
  1210. Returns: Checksum of index file
  1211. """
  1212. entries = self.sorted_entries(
  1213. progress=progress, resolve_ext_ref=resolve_ext_ref
  1214. )
  1215. with GitFile(filename, "wb") as f:
  1216. return write_pack_index_v2(f, entries, self.calculate_checksum())
  1217. def create_index_v3(
  1218. self, filename, progress=None, resolve_ext_ref=None, hash_algorithm=1
  1219. ):
  1220. """Create a version 3 index file for this data file.
  1221. Args:
  1222. filename: Index filename.
  1223. progress: Progress report function
  1224. resolve_ext_ref: Function to resolve external references
  1225. hash_algorithm: Hash algorithm identifier (1 = SHA-1, 2 = SHA-256)
  1226. Returns: Checksum of index file
  1227. """
  1228. entries = self.sorted_entries(
  1229. progress=progress, resolve_ext_ref=resolve_ext_ref
  1230. )
  1231. with GitFile(filename, "wb") as f:
  1232. return write_pack_index_v3(
  1233. f, entries, self.calculate_checksum(), hash_algorithm
  1234. )
  1235. def create_index(
  1236. self, filename, progress=None, version=2, resolve_ext_ref=None, hash_algorithm=1
  1237. ):
  1238. """Create an index file for this data file.
  1239. Args:
  1240. filename: Index filename.
  1241. progress: Progress report function
  1242. version: Index version (1, 2, or 3)
  1243. resolve_ext_ref: Function to resolve external references
  1244. hash_algorithm: Hash algorithm identifier for v3 (1 = SHA-1, 2 = SHA-256)
  1245. Returns: Checksum of index file
  1246. """
  1247. if version == 1:
  1248. return self.create_index_v1(
  1249. filename, progress, resolve_ext_ref=resolve_ext_ref
  1250. )
  1251. elif version == 2:
  1252. return self.create_index_v2(
  1253. filename, progress, resolve_ext_ref=resolve_ext_ref
  1254. )
  1255. elif version == 3:
  1256. return self.create_index_v3(
  1257. filename,
  1258. progress,
  1259. resolve_ext_ref=resolve_ext_ref,
  1260. hash_algorithm=hash_algorithm,
  1261. )
  1262. else:
  1263. raise ValueError(f"unknown index format {version}")
  1264. def get_stored_checksum(self):
  1265. """Return the expected checksum stored in this pack."""
  1266. self._file.seek(-20, SEEK_END)
  1267. return self._file.read(20)
  1268. def check(self) -> None:
  1269. """Check the consistency of this pack."""
  1270. actual = self.calculate_checksum()
  1271. stored = self.get_stored_checksum()
  1272. if actual != stored:
  1273. raise ChecksumMismatch(stored, actual)
  1274. def get_unpacked_object_at(
  1275. self, offset: int, *, include_comp: bool = False
  1276. ) -> UnpackedObject:
  1277. """Given offset in the packfile return a UnpackedObject."""
  1278. assert offset >= self._header_size
  1279. self._file.seek(offset)
  1280. unpacked, _ = unpack_object(self._file.read, include_comp=include_comp)
  1281. unpacked.offset = offset
  1282. return unpacked
  1283. def get_object_at(self, offset: int) -> tuple[int, OldUnpackedObject]:
  1284. """Given an offset in to the packfile return the object that is there.
  1285. Using the associated index the location of an object can be looked up,
  1286. and then the packfile can be asked directly for that object using this
  1287. function.
  1288. """
  1289. try:
  1290. return self._offset_cache[offset]
  1291. except KeyError:
  1292. pass
  1293. unpacked = self.get_unpacked_object_at(offset, include_comp=False)
  1294. return (unpacked.pack_type_num, unpacked._obj())
  1295. T = TypeVar("T")
  1296. class DeltaChainIterator(Generic[T]):
  1297. """Abstract iterator over pack data based on delta chains.
  1298. Each object in the pack is guaranteed to be inflated exactly once,
  1299. regardless of how many objects reference it as a delta base. As a result,
  1300. memory usage is proportional to the length of the longest delta chain.
  1301. Subclasses can override _result to define the result type of the iterator.
  1302. By default, results are UnpackedObjects with the following members set:
  1303. * offset
  1304. * obj_type_num
  1305. * obj_chunks
  1306. * pack_type_num
  1307. * delta_base (for delta types)
  1308. * comp_chunks (if _include_comp is True)
  1309. * decomp_chunks
  1310. * decomp_len
  1311. * crc32 (if _compute_crc32 is True)
  1312. """
  1313. _compute_crc32 = False
  1314. _include_comp = False
  1315. def __init__(self, file_obj, *, resolve_ext_ref=None) -> None:
  1316. self._file = file_obj
  1317. self._resolve_ext_ref = resolve_ext_ref
  1318. self._pending_ofs: dict[int, list[int]] = defaultdict(list)
  1319. self._pending_ref: dict[bytes, list[int]] = defaultdict(list)
  1320. self._full_ofs: list[tuple[int, int]] = []
  1321. self._ext_refs: list[bytes] = []
  1322. @classmethod
  1323. def for_pack_data(cls, pack_data: PackData, resolve_ext_ref=None):
  1324. walker = cls(None, resolve_ext_ref=resolve_ext_ref)
  1325. walker.set_pack_data(pack_data)
  1326. for unpacked in pack_data.iter_unpacked(include_comp=False):
  1327. walker.record(unpacked)
  1328. return walker
  1329. @classmethod
  1330. def for_pack_subset(
  1331. cls,
  1332. pack: "Pack",
  1333. shas: Iterable[bytes],
  1334. *,
  1335. allow_missing: bool = False,
  1336. resolve_ext_ref=None,
  1337. ):
  1338. walker = cls(None, resolve_ext_ref=resolve_ext_ref)
  1339. walker.set_pack_data(pack.data)
  1340. todo = set()
  1341. for sha in shas:
  1342. assert isinstance(sha, bytes)
  1343. try:
  1344. off = pack.index.object_offset(sha)
  1345. except KeyError:
  1346. if not allow_missing:
  1347. raise
  1348. else:
  1349. todo.add(off)
  1350. done = set()
  1351. while todo:
  1352. off = todo.pop()
  1353. unpacked = pack.data.get_unpacked_object_at(off)
  1354. walker.record(unpacked)
  1355. done.add(off)
  1356. base_ofs = None
  1357. if unpacked.pack_type_num == OFS_DELTA:
  1358. assert unpacked.offset is not None
  1359. assert unpacked.delta_base is not None
  1360. assert isinstance(unpacked.delta_base, int)
  1361. base_ofs = unpacked.offset - unpacked.delta_base
  1362. elif unpacked.pack_type_num == REF_DELTA:
  1363. with suppress(KeyError):
  1364. assert isinstance(unpacked.delta_base, bytes)
  1365. base_ofs = pack.index.object_index(unpacked.delta_base)
  1366. if base_ofs is not None and base_ofs not in done:
  1367. todo.add(base_ofs)
  1368. return walker
  1369. def record(self, unpacked: UnpackedObject) -> None:
  1370. type_num = unpacked.pack_type_num
  1371. offset = unpacked.offset
  1372. assert offset is not None
  1373. if type_num == OFS_DELTA:
  1374. assert unpacked.delta_base is not None
  1375. assert isinstance(unpacked.delta_base, int)
  1376. base_offset = offset - unpacked.delta_base
  1377. self._pending_ofs[base_offset].append(offset)
  1378. elif type_num == REF_DELTA:
  1379. assert isinstance(unpacked.delta_base, bytes)
  1380. self._pending_ref[unpacked.delta_base].append(offset)
  1381. else:
  1382. self._full_ofs.append((offset, type_num))
  1383. def set_pack_data(self, pack_data: PackData) -> None:
  1384. self._file = pack_data._file
  1385. def _walk_all_chains(self):
  1386. for offset, type_num in self._full_ofs:
  1387. yield from self._follow_chain(offset, type_num, None)
  1388. yield from self._walk_ref_chains()
  1389. assert not self._pending_ofs, repr(self._pending_ofs)
  1390. def _ensure_no_pending(self) -> None:
  1391. if self._pending_ref:
  1392. raise UnresolvedDeltas([sha_to_hex(s) for s in self._pending_ref])
  1393. def _walk_ref_chains(self):
  1394. if not self._resolve_ext_ref:
  1395. self._ensure_no_pending()
  1396. return
  1397. for base_sha, pending in sorted(self._pending_ref.items()):
  1398. if base_sha not in self._pending_ref:
  1399. continue
  1400. try:
  1401. type_num, chunks = self._resolve_ext_ref(base_sha)
  1402. except KeyError:
  1403. # Not an external ref, but may depend on one. Either it will
  1404. # get popped via a _follow_chain call, or we will raise an
  1405. # error below.
  1406. continue
  1407. self._ext_refs.append(base_sha)
  1408. self._pending_ref.pop(base_sha)
  1409. for new_offset in pending:
  1410. yield from self._follow_chain(new_offset, type_num, chunks)
  1411. self._ensure_no_pending()
  1412. def _result(self, unpacked: UnpackedObject) -> T:
  1413. raise NotImplementedError
  1414. def _resolve_object(
  1415. self, offset: int, obj_type_num: int, base_chunks: list[bytes]
  1416. ) -> UnpackedObject:
  1417. self._file.seek(offset)
  1418. unpacked, _ = unpack_object(
  1419. self._file.read,
  1420. include_comp=self._include_comp,
  1421. compute_crc32=self._compute_crc32,
  1422. )
  1423. unpacked.offset = offset
  1424. if base_chunks is None:
  1425. assert unpacked.pack_type_num == obj_type_num
  1426. else:
  1427. assert unpacked.pack_type_num in DELTA_TYPES
  1428. unpacked.obj_type_num = obj_type_num
  1429. unpacked.obj_chunks = apply_delta(base_chunks, unpacked.decomp_chunks)
  1430. return unpacked
  1431. def _follow_chain(self, offset: int, obj_type_num: int, base_chunks: list[bytes]):
  1432. # Unlike PackData.get_object_at, there is no need to cache offsets as
  1433. # this approach by design inflates each object exactly once.
  1434. todo = [(offset, obj_type_num, base_chunks)]
  1435. while todo:
  1436. (offset, obj_type_num, base_chunks) = todo.pop()
  1437. unpacked = self._resolve_object(offset, obj_type_num, base_chunks)
  1438. yield self._result(unpacked)
  1439. assert unpacked.offset is not None
  1440. unblocked = chain(
  1441. self._pending_ofs.pop(unpacked.offset, []),
  1442. self._pending_ref.pop(unpacked.sha(), []),
  1443. )
  1444. todo.extend(
  1445. (new_offset, unpacked.obj_type_num, unpacked.obj_chunks) # type: ignore
  1446. for new_offset in unblocked
  1447. )
  1448. def __iter__(self) -> Iterator[T]:
  1449. return self._walk_all_chains()
  1450. def ext_refs(self):
  1451. return self._ext_refs
  1452. class UnpackedObjectIterator(DeltaChainIterator[UnpackedObject]):
  1453. """Delta chain iterator that yield unpacked objects."""
  1454. def _result(self, unpacked):
  1455. return unpacked
  1456. class PackIndexer(DeltaChainIterator[PackIndexEntry]):
  1457. """Delta chain iterator that yields index entries."""
  1458. _compute_crc32 = True
  1459. def _result(self, unpacked):
  1460. return unpacked.sha(), unpacked.offset, unpacked.crc32
  1461. class PackInflater(DeltaChainIterator[ShaFile]):
  1462. """Delta chain iterator that yields ShaFile objects."""
  1463. def _result(self, unpacked):
  1464. return unpacked.sha_file()
  1465. class SHA1Reader(BinaryIO):
  1466. """Wrapper for file-like object that remembers the SHA1 of its data."""
  1467. def __init__(self, f) -> None:
  1468. self.f = f
  1469. self.sha1 = sha1(b"")
  1470. def read(self, size: int = -1) -> bytes:
  1471. data = self.f.read(size)
  1472. self.sha1.update(data)
  1473. return data
  1474. def check_sha(self, allow_empty: bool = False) -> None:
  1475. stored = self.f.read(20)
  1476. # If git option index.skipHash is set the index will be empty
  1477. if stored != self.sha1.digest() and (
  1478. not allow_empty
  1479. or sha_to_hex(stored) != b"0000000000000000000000000000000000000000"
  1480. ):
  1481. raise ChecksumMismatch(self.sha1.hexdigest(), sha_to_hex(stored))
  1482. def close(self):
  1483. return self.f.close()
  1484. def tell(self) -> int:
  1485. return self.f.tell()
  1486. # BinaryIO abstract methods
  1487. def readable(self) -> bool:
  1488. return True
  1489. def writable(self) -> bool:
  1490. return False
  1491. def seekable(self) -> bool:
  1492. return getattr(self.f, "seekable", lambda: False)()
  1493. def seek(self, offset: int, whence: int = 0) -> int:
  1494. return self.f.seek(offset, whence)
  1495. def flush(self) -> None:
  1496. if hasattr(self.f, "flush"):
  1497. self.f.flush()
  1498. def readline(self, size: int = -1) -> bytes:
  1499. return self.f.readline(size)
  1500. def readlines(self, hint: int = -1) -> list[bytes]:
  1501. return self.f.readlines(hint)
  1502. def writelines(self, lines) -> None:
  1503. raise UnsupportedOperation("writelines")
  1504. def write(self, data) -> int:
  1505. raise UnsupportedOperation("write")
  1506. def __enter__(self):
  1507. return self
  1508. def __exit__(self, type, value, traceback):
  1509. self.close()
  1510. def __iter__(self):
  1511. return self
  1512. def __next__(self) -> bytes:
  1513. line = self.readline()
  1514. if not line:
  1515. raise StopIteration
  1516. return line
  1517. def fileno(self) -> int:
  1518. return self.f.fileno()
  1519. def isatty(self) -> bool:
  1520. return getattr(self.f, "isatty", lambda: False)()
  1521. def truncate(self, size: Optional[int] = None) -> int:
  1522. raise UnsupportedOperation("truncate")
  1523. class SHA1Writer(BinaryIO):
  1524. """Wrapper for file-like object that remembers the SHA1 of its data."""
  1525. def __init__(self, f) -> None:
  1526. self.f = f
  1527. self.length = 0
  1528. self.sha1 = sha1(b"")
  1529. def write(self, data) -> int:
  1530. self.sha1.update(data)
  1531. self.f.write(data)
  1532. self.length += len(data)
  1533. return len(data)
  1534. def write_sha(self):
  1535. sha = self.sha1.digest()
  1536. assert len(sha) == 20
  1537. self.f.write(sha)
  1538. self.length += len(sha)
  1539. return sha
  1540. def close(self):
  1541. sha = self.write_sha()
  1542. self.f.close()
  1543. return sha
  1544. def offset(self):
  1545. return self.length
  1546. def tell(self) -> int:
  1547. return self.f.tell()
  1548. # BinaryIO abstract methods
  1549. def readable(self) -> bool:
  1550. return False
  1551. def writable(self) -> bool:
  1552. return True
  1553. def seekable(self) -> bool:
  1554. return getattr(self.f, "seekable", lambda: False)()
  1555. def seek(self, offset: int, whence: int = 0) -> int:
  1556. return self.f.seek(offset, whence)
  1557. def flush(self) -> None:
  1558. if hasattr(self.f, "flush"):
  1559. self.f.flush()
  1560. def readline(self, size: int = -1) -> bytes:
  1561. raise UnsupportedOperation("readline")
  1562. def readlines(self, hint: int = -1) -> list[bytes]:
  1563. raise UnsupportedOperation("readlines")
  1564. def writelines(self, lines) -> None:
  1565. for line in lines:
  1566. self.write(line)
  1567. def read(self, size: int = -1) -> bytes:
  1568. raise UnsupportedOperation("read")
  1569. def __enter__(self):
  1570. return self
  1571. def __exit__(self, type, value, traceback):
  1572. self.close()
  1573. def __iter__(self):
  1574. return self
  1575. def __next__(self) -> bytes:
  1576. raise UnsupportedOperation("__next__")
  1577. def fileno(self) -> int:
  1578. return self.f.fileno()
  1579. def isatty(self) -> bool:
  1580. return getattr(self.f, "isatty", lambda: False)()
  1581. def truncate(self, size: Optional[int] = None) -> int:
  1582. raise UnsupportedOperation("truncate")
  1583. def pack_object_header(type_num, delta_base, size):
  1584. """Create a pack object header for the given object info.
  1585. Args:
  1586. type_num: Numeric type of the object.
  1587. delta_base: Delta base offset or ref, or None for whole objects.
  1588. size: Uncompressed object size.
  1589. Returns: A header for a packed object.
  1590. """
  1591. header = []
  1592. c = (type_num << 4) | (size & 15)
  1593. size >>= 4
  1594. while size:
  1595. header.append(c | 0x80)
  1596. c = size & 0x7F
  1597. size >>= 7
  1598. header.append(c)
  1599. if type_num == OFS_DELTA:
  1600. ret = [delta_base & 0x7F]
  1601. delta_base >>= 7
  1602. while delta_base:
  1603. delta_base -= 1
  1604. ret.insert(0, 0x80 | (delta_base & 0x7F))
  1605. delta_base >>= 7
  1606. header.extend(ret)
  1607. elif type_num == REF_DELTA:
  1608. assert len(delta_base) == 20
  1609. header += delta_base
  1610. return bytearray(header)
  1611. def pack_object_chunks(type, object, compression_level=-1):
  1612. """Generate chunks for a pack object.
  1613. Args:
  1614. type: Numeric type of the object
  1615. object: Object to write
  1616. compression_level: the zlib compression level
  1617. Returns: Chunks
  1618. """
  1619. if type in DELTA_TYPES:
  1620. delta_base, object = object
  1621. else:
  1622. delta_base = None
  1623. if isinstance(object, bytes):
  1624. object = [object]
  1625. yield bytes(pack_object_header(type, delta_base, sum(map(len, object))))
  1626. compressor = zlib.compressobj(level=compression_level)
  1627. for data in object:
  1628. yield compressor.compress(data)
  1629. yield compressor.flush()
  1630. def write_pack_object(write, type, object, sha=None, compression_level=-1):
  1631. """Write pack object to a file.
  1632. Args:
  1633. write: Write function to use
  1634. type: Numeric type of the object
  1635. object: Object to write
  1636. compression_level: the zlib compression level
  1637. Returns: Tuple with offset at which the object was written, and crc32
  1638. """
  1639. crc32 = 0
  1640. for chunk in pack_object_chunks(type, object, compression_level=compression_level):
  1641. write(chunk)
  1642. if sha is not None:
  1643. sha.update(chunk)
  1644. crc32 = binascii.crc32(chunk, crc32)
  1645. return crc32 & 0xFFFFFFFF
  1646. def write_pack(
  1647. filename,
  1648. objects: Union[Sequence[ShaFile], Sequence[tuple[ShaFile, Optional[bytes]]]],
  1649. *,
  1650. deltify: Optional[bool] = None,
  1651. delta_window_size: Optional[int] = None,
  1652. compression_level: int = -1,
  1653. ):
  1654. """Write a new pack data file.
  1655. Args:
  1656. filename: Path to the new pack file (without .pack extension)
  1657. delta_window_size: Delta window size
  1658. deltify: Whether to deltify pack objects
  1659. compression_level: the zlib compression level
  1660. Returns: Tuple with checksum of pack file and index file
  1661. """
  1662. with GitFile(filename + ".pack", "wb") as f:
  1663. entries, data_sum = write_pack_objects(
  1664. f.write,
  1665. objects,
  1666. delta_window_size=delta_window_size,
  1667. deltify=deltify,
  1668. compression_level=compression_level,
  1669. )
  1670. entries = sorted([(k, v[0], v[1]) for (k, v) in entries.items()])
  1671. with GitFile(filename + ".idx", "wb") as f:
  1672. return data_sum, write_pack_index(f, entries, data_sum)
  1673. def pack_header_chunks(num_objects):
  1674. """Yield chunks for a pack header."""
  1675. yield b"PACK" # Pack header
  1676. yield struct.pack(b">L", 2) # Pack version
  1677. yield struct.pack(b">L", num_objects) # Number of objects in pack
  1678. def write_pack_header(write, num_objects) -> None:
  1679. """Write a pack header for the given number of objects."""
  1680. if hasattr(write, "write"):
  1681. write = write.write
  1682. warnings.warn(
  1683. "write_pack_header() now takes a write rather than file argument",
  1684. DeprecationWarning,
  1685. stacklevel=2,
  1686. )
  1687. for chunk in pack_header_chunks(num_objects):
  1688. write(chunk)
  1689. def find_reusable_deltas(
  1690. container: PackedObjectContainer,
  1691. object_ids: set[bytes],
  1692. *,
  1693. other_haves: Optional[set[bytes]] = None,
  1694. progress=None,
  1695. ) -> Iterator[UnpackedObject]:
  1696. if other_haves is None:
  1697. other_haves = set()
  1698. reused = 0
  1699. for i, unpacked in enumerate(
  1700. container.iter_unpacked_subset(
  1701. object_ids, allow_missing=True, convert_ofs_delta=True
  1702. )
  1703. ):
  1704. if progress is not None and i % 1000 == 0:
  1705. progress(f"checking for reusable deltas: {i}/{len(object_ids)}\r".encode())
  1706. if unpacked.pack_type_num == REF_DELTA:
  1707. hexsha = sha_to_hex(unpacked.delta_base) # type: ignore
  1708. if hexsha in object_ids or hexsha in other_haves:
  1709. yield unpacked
  1710. reused += 1
  1711. if progress is not None:
  1712. progress((f"found {reused} deltas to reuse\n").encode())
  1713. def deltify_pack_objects(
  1714. objects: Union[Iterator[bytes], Iterator[tuple[ShaFile, Optional[bytes]]]],
  1715. *,
  1716. window_size: Optional[int] = None,
  1717. progress=None,
  1718. ) -> Iterator[UnpackedObject]:
  1719. """Generate deltas for pack objects.
  1720. Args:
  1721. objects: An iterable of (object, path) tuples to deltify.
  1722. window_size: Window size; None for default
  1723. Returns: Iterator over type_num, object id, delta_base, content
  1724. delta_base is None for full text entries
  1725. """
  1726. def objects_with_hints():
  1727. for e in objects:
  1728. if isinstance(e, ShaFile):
  1729. yield (e, (e.type_num, None))
  1730. else:
  1731. yield (e[0], (e[0].type_num, e[1]))
  1732. yield from deltas_from_sorted_objects(
  1733. sort_objects_for_delta(objects_with_hints()),
  1734. window_size=window_size,
  1735. progress=progress,
  1736. )
  1737. def sort_objects_for_delta(
  1738. objects: Union[Iterator[ShaFile], Iterator[tuple[ShaFile, Optional[PackHint]]]],
  1739. ) -> Iterator[ShaFile]:
  1740. magic = []
  1741. for entry in objects:
  1742. if isinstance(entry, tuple):
  1743. obj, hint = entry
  1744. if hint is None:
  1745. type_num = None
  1746. path = None
  1747. else:
  1748. (type_num, path) = hint
  1749. else:
  1750. obj = entry
  1751. magic.append((type_num, path, -obj.raw_length(), obj))
  1752. # Build a list of objects ordered by the magic Linus heuristic
  1753. # This helps us find good objects to diff against us
  1754. magic.sort()
  1755. return (x[3] for x in magic)
  1756. def deltas_from_sorted_objects(
  1757. objects, window_size: Optional[int] = None, progress=None
  1758. ):
  1759. # TODO(jelmer): Use threads
  1760. if window_size is None:
  1761. window_size = DEFAULT_PACK_DELTA_WINDOW_SIZE
  1762. possible_bases: deque[tuple[bytes, int, list[bytes]]] = deque()
  1763. for i, o in enumerate(objects):
  1764. if progress is not None and i % 1000 == 0:
  1765. progress((f"generating deltas: {i}\r").encode())
  1766. raw = o.as_raw_chunks()
  1767. winner = raw
  1768. winner_len = sum(map(len, winner))
  1769. winner_base = None
  1770. for base_id, base_type_num, base in possible_bases:
  1771. if base_type_num != o.type_num:
  1772. continue
  1773. delta_len = 0
  1774. delta = []
  1775. for chunk in create_delta(base, raw):
  1776. delta_len += len(chunk)
  1777. if delta_len >= winner_len:
  1778. break
  1779. delta.append(chunk)
  1780. else:
  1781. winner_base = base_id
  1782. winner = delta
  1783. winner_len = sum(map(len, winner))
  1784. yield UnpackedObject(
  1785. o.type_num,
  1786. sha=o.sha().digest(),
  1787. delta_base=winner_base,
  1788. decomp_len=winner_len,
  1789. decomp_chunks=winner,
  1790. )
  1791. possible_bases.appendleft((o.sha().digest(), o.type_num, raw))
  1792. while len(possible_bases) > window_size:
  1793. possible_bases.pop()
  1794. def pack_objects_to_data(
  1795. objects: Union[Sequence[ShaFile], Sequence[tuple[ShaFile, Optional[bytes]]]],
  1796. *,
  1797. deltify: Optional[bool] = None,
  1798. delta_window_size: Optional[int] = None,
  1799. ofs_delta: bool = True,
  1800. progress=None,
  1801. ) -> tuple[int, Iterator[UnpackedObject]]:
  1802. """Create pack data from objects.
  1803. Args:
  1804. objects: Pack objects
  1805. Returns: Tuples with (type_num, hexdigest, delta base, object chunks)
  1806. """
  1807. # TODO(jelmer): support deltaifying
  1808. count = len(objects)
  1809. if deltify is None:
  1810. # PERFORMANCE/TODO(jelmer): This should be enabled but is *much* too
  1811. # slow at the moment.
  1812. deltify = False
  1813. if deltify:
  1814. return (
  1815. count,
  1816. deltify_pack_objects(
  1817. iter(objects), # type: ignore
  1818. window_size=delta_window_size,
  1819. progress=progress,
  1820. ),
  1821. )
  1822. else:
  1823. def iter_without_path():
  1824. for o in objects:
  1825. if isinstance(o, tuple):
  1826. yield full_unpacked_object(o[0])
  1827. else:
  1828. yield full_unpacked_object(o)
  1829. return (count, iter_without_path())
  1830. def generate_unpacked_objects(
  1831. container: PackedObjectContainer,
  1832. object_ids: Sequence[tuple[ObjectID, Optional[PackHint]]],
  1833. delta_window_size: Optional[int] = None,
  1834. deltify: Optional[bool] = None,
  1835. reuse_deltas: bool = True,
  1836. ofs_delta: bool = True,
  1837. other_haves: Optional[set[bytes]] = None,
  1838. progress=None,
  1839. ) -> Iterator[UnpackedObject]:
  1840. """Create pack data from objects.
  1841. Returns: Tuples with (type_num, hexdigest, delta base, object chunks)
  1842. """
  1843. todo = dict(object_ids)
  1844. if reuse_deltas:
  1845. for unpack in find_reusable_deltas(
  1846. container, set(todo), other_haves=other_haves, progress=progress
  1847. ):
  1848. del todo[sha_to_hex(unpack.sha())]
  1849. yield unpack
  1850. if deltify is None:
  1851. # PERFORMANCE/TODO(jelmer): This should be enabled but is *much* too
  1852. # slow at the moment.
  1853. deltify = False
  1854. if deltify:
  1855. objects_to_delta = container.iterobjects_subset(
  1856. todo.keys(), allow_missing=False
  1857. )
  1858. yield from deltas_from_sorted_objects(
  1859. sort_objects_for_delta((o, todo[o.id]) for o in objects_to_delta),
  1860. window_size=delta_window_size,
  1861. progress=progress,
  1862. )
  1863. else:
  1864. for oid in todo:
  1865. yield full_unpacked_object(container[oid])
  1866. def full_unpacked_object(o: ShaFile) -> UnpackedObject:
  1867. return UnpackedObject(
  1868. o.type_num,
  1869. delta_base=None,
  1870. crc32=None,
  1871. decomp_chunks=o.as_raw_chunks(),
  1872. sha=o.sha().digest(),
  1873. )
  1874. def write_pack_from_container(
  1875. write,
  1876. container: PackedObjectContainer,
  1877. object_ids: Sequence[tuple[ObjectID, Optional[PackHint]]],
  1878. delta_window_size: Optional[int] = None,
  1879. deltify: Optional[bool] = None,
  1880. reuse_deltas: bool = True,
  1881. compression_level: int = -1,
  1882. other_haves: Optional[set[bytes]] = None,
  1883. ):
  1884. """Write a new pack data file.
  1885. Args:
  1886. write: write function to use
  1887. container: PackedObjectContainer
  1888. delta_window_size: Sliding window size for searching for deltas;
  1889. Set to None for default window size.
  1890. deltify: Whether to deltify objects
  1891. compression_level: the zlib compression level to use
  1892. Returns: Dict mapping id -> (offset, crc32 checksum), pack checksum
  1893. """
  1894. pack_contents_count = len(object_ids)
  1895. pack_contents = generate_unpacked_objects(
  1896. container,
  1897. object_ids,
  1898. delta_window_size=delta_window_size,
  1899. deltify=deltify,
  1900. reuse_deltas=reuse_deltas,
  1901. other_haves=other_haves,
  1902. )
  1903. return write_pack_data(
  1904. write,
  1905. pack_contents,
  1906. num_records=pack_contents_count,
  1907. compression_level=compression_level,
  1908. )
  1909. def write_pack_objects(
  1910. write,
  1911. objects: Union[Sequence[ShaFile], Sequence[tuple[ShaFile, Optional[bytes]]]],
  1912. *,
  1913. delta_window_size: Optional[int] = None,
  1914. deltify: Optional[bool] = None,
  1915. compression_level: int = -1,
  1916. ):
  1917. """Write a new pack data file.
  1918. Args:
  1919. write: write function to use
  1920. objects: Sequence of (object, path) tuples to write
  1921. delta_window_size: Sliding window size for searching for deltas;
  1922. Set to None for default window size.
  1923. deltify: Whether to deltify objects
  1924. compression_level: the zlib compression level to use
  1925. Returns: Dict mapping id -> (offset, crc32 checksum), pack checksum
  1926. """
  1927. pack_contents_count, pack_contents = pack_objects_to_data(objects, deltify=deltify)
  1928. return write_pack_data(
  1929. write,
  1930. pack_contents,
  1931. num_records=pack_contents_count,
  1932. compression_level=compression_level,
  1933. )
  1934. class PackChunkGenerator:
  1935. def __init__(
  1936. self,
  1937. num_records=None,
  1938. records=None,
  1939. progress=None,
  1940. compression_level=-1,
  1941. reuse_compressed=True,
  1942. ) -> None:
  1943. self.cs = sha1(b"")
  1944. self.entries: dict[Union[int, bytes], tuple[int, int]] = {}
  1945. self._it = self._pack_data_chunks(
  1946. num_records=num_records,
  1947. records=records,
  1948. progress=progress,
  1949. compression_level=compression_level,
  1950. reuse_compressed=reuse_compressed,
  1951. )
  1952. def sha1digest(self):
  1953. return self.cs.digest()
  1954. def __iter__(self):
  1955. return self._it
  1956. def _pack_data_chunks(
  1957. self,
  1958. records: Iterator[UnpackedObject],
  1959. *,
  1960. num_records=None,
  1961. progress=None,
  1962. compression_level: int = -1,
  1963. reuse_compressed: bool = True,
  1964. ) -> Iterator[bytes]:
  1965. """Iterate pack data file chunks.
  1966. Args:
  1967. records: Iterator over UnpackedObject
  1968. num_records: Number of records (defaults to len(records) if not specified)
  1969. progress: Function to report progress to
  1970. compression_level: the zlib compression level
  1971. Returns: Dict mapping id -> (offset, crc32 checksum), pack checksum
  1972. """
  1973. # Write the pack
  1974. if num_records is None:
  1975. num_records = len(records) # type: ignore
  1976. offset = 0
  1977. for chunk in pack_header_chunks(num_records):
  1978. yield chunk
  1979. self.cs.update(chunk)
  1980. offset += len(chunk)
  1981. actual_num_records = 0
  1982. for i, unpacked in enumerate(records):
  1983. type_num = unpacked.pack_type_num
  1984. if progress is not None and i % 1000 == 0:
  1985. progress((f"writing pack data: {i}/{num_records}\r").encode("ascii"))
  1986. raw: Union[list[bytes], tuple[int, list[bytes]], tuple[bytes, list[bytes]]]
  1987. if unpacked.delta_base is not None:
  1988. try:
  1989. base_offset, base_crc32 = self.entries[unpacked.delta_base]
  1990. except KeyError:
  1991. type_num = REF_DELTA
  1992. assert isinstance(unpacked.delta_base, bytes)
  1993. raw = (unpacked.delta_base, unpacked.decomp_chunks)
  1994. else:
  1995. type_num = OFS_DELTA
  1996. raw = (offset - base_offset, unpacked.decomp_chunks)
  1997. else:
  1998. raw = unpacked.decomp_chunks
  1999. if unpacked.comp_chunks is not None and reuse_compressed:
  2000. chunks = unpacked.comp_chunks
  2001. else:
  2002. chunks = pack_object_chunks(
  2003. type_num, raw, compression_level=compression_level
  2004. )
  2005. crc32 = 0
  2006. object_size = 0
  2007. for chunk in chunks:
  2008. yield chunk
  2009. crc32 = binascii.crc32(chunk, crc32)
  2010. self.cs.update(chunk)
  2011. object_size += len(chunk)
  2012. actual_num_records += 1
  2013. self.entries[unpacked.sha()] = (offset, crc32)
  2014. offset += object_size
  2015. if actual_num_records != num_records:
  2016. raise AssertionError(
  2017. f"actual records written differs: {actual_num_records} != {num_records}"
  2018. )
  2019. yield self.cs.digest()
  2020. def write_pack_data(
  2021. write,
  2022. records: Iterator[UnpackedObject],
  2023. *,
  2024. num_records=None,
  2025. progress=None,
  2026. compression_level=-1,
  2027. ):
  2028. """Write a new pack data file.
  2029. Args:
  2030. write: Write function to use
  2031. num_records: Number of records (defaults to len(records) if None)
  2032. records: Iterator over type_num, object_id, delta_base, raw
  2033. progress: Function to report progress to
  2034. compression_level: the zlib compression level
  2035. Returns: Dict mapping id -> (offset, crc32 checksum), pack checksum
  2036. """
  2037. chunk_generator = PackChunkGenerator(
  2038. num_records=num_records,
  2039. records=records,
  2040. progress=progress,
  2041. compression_level=compression_level,
  2042. )
  2043. for chunk in chunk_generator:
  2044. write(chunk)
  2045. return chunk_generator.entries, chunk_generator.sha1digest()
  2046. def write_pack_index_v1(f, entries, pack_checksum):
  2047. """Write a new pack index file.
  2048. Args:
  2049. f: A file-like object to write to
  2050. entries: List of tuples with object name (sha), offset_in_pack,
  2051. and crc32_checksum.
  2052. pack_checksum: Checksum of the pack file.
  2053. Returns: The SHA of the written index file
  2054. """
  2055. f = SHA1Writer(f)
  2056. fan_out_table = defaultdict(lambda: 0)
  2057. for name, _offset, _entry_checksum in entries:
  2058. fan_out_table[ord(name[:1])] += 1
  2059. # Fan-out table
  2060. for i in range(0x100):
  2061. f.write(struct.pack(">L", fan_out_table[i]))
  2062. fan_out_table[i + 1] += fan_out_table[i]
  2063. for name, offset, _entry_checksum in entries:
  2064. if not (offset <= 0xFFFFFFFF):
  2065. raise TypeError("pack format 1 only supports offsets < 2Gb")
  2066. f.write(struct.pack(">L20s", offset, name))
  2067. assert len(pack_checksum) == 20
  2068. f.write(pack_checksum)
  2069. return f.write_sha()
  2070. def _delta_encode_size(size) -> bytes:
  2071. ret = bytearray()
  2072. c = size & 0x7F
  2073. size >>= 7
  2074. while size:
  2075. ret.append(c | 0x80)
  2076. c = size & 0x7F
  2077. size >>= 7
  2078. ret.append(c)
  2079. return bytes(ret)
  2080. # The length of delta compression copy operations in version 2 packs is limited
  2081. # to 64K. To copy more, we use several copy operations. Version 3 packs allow
  2082. # 24-bit lengths in copy operations, but we always make version 2 packs.
  2083. _MAX_COPY_LEN = 0xFFFF
  2084. def _encode_copy_operation(start, length):
  2085. scratch = bytearray([0x80])
  2086. for i in range(4):
  2087. if start & 0xFF << i * 8:
  2088. scratch.append((start >> i * 8) & 0xFF)
  2089. scratch[0] |= 1 << i
  2090. for i in range(2):
  2091. if length & 0xFF << i * 8:
  2092. scratch.append((length >> i * 8) & 0xFF)
  2093. scratch[0] |= 1 << (4 + i)
  2094. return bytes(scratch)
  2095. def create_delta(base_buf, target_buf):
  2096. """Use python difflib to work out how to transform base_buf to target_buf.
  2097. Args:
  2098. base_buf: Base buffer
  2099. target_buf: Target buffer
  2100. """
  2101. if isinstance(base_buf, list):
  2102. base_buf = b"".join(base_buf)
  2103. if isinstance(target_buf, list):
  2104. target_buf = b"".join(target_buf)
  2105. assert isinstance(base_buf, bytes)
  2106. assert isinstance(target_buf, bytes)
  2107. # write delta header
  2108. yield _delta_encode_size(len(base_buf))
  2109. yield _delta_encode_size(len(target_buf))
  2110. # write out delta opcodes
  2111. seq = SequenceMatcher(isjunk=None, a=base_buf, b=target_buf)
  2112. for opcode, i1, i2, j1, j2 in seq.get_opcodes():
  2113. # Git patch opcodes don't care about deletes!
  2114. # if opcode == 'replace' or opcode == 'delete':
  2115. # pass
  2116. if opcode == "equal":
  2117. # If they are equal, unpacker will use data from base_buf
  2118. # Write out an opcode that says what range to use
  2119. copy_start = i1
  2120. copy_len = i2 - i1
  2121. while copy_len > 0:
  2122. to_copy = min(copy_len, _MAX_COPY_LEN)
  2123. yield _encode_copy_operation(copy_start, to_copy)
  2124. copy_start += to_copy
  2125. copy_len -= to_copy
  2126. if opcode == "replace" or opcode == "insert":
  2127. # If we are replacing a range or adding one, then we just
  2128. # output it to the stream (prefixed by its size)
  2129. s = j2 - j1
  2130. o = j1
  2131. while s > 127:
  2132. yield bytes([127])
  2133. yield memoryview(target_buf)[o : o + 127]
  2134. s -= 127
  2135. o += 127
  2136. yield bytes([s])
  2137. yield memoryview(target_buf)[o : o + s]
  2138. def apply_delta(src_buf, delta):
  2139. """Based on the similar function in git's patch-delta.c.
  2140. Args:
  2141. src_buf: Source buffer
  2142. delta: Delta instructions
  2143. """
  2144. if not isinstance(src_buf, bytes):
  2145. src_buf = b"".join(src_buf)
  2146. if not isinstance(delta, bytes):
  2147. delta = b"".join(delta)
  2148. out = []
  2149. index = 0
  2150. delta_length = len(delta)
  2151. def get_delta_header_size(delta, index):
  2152. size = 0
  2153. i = 0
  2154. while delta:
  2155. cmd = ord(delta[index : index + 1])
  2156. index += 1
  2157. size |= (cmd & ~0x80) << i
  2158. i += 7
  2159. if not cmd & 0x80:
  2160. break
  2161. return size, index
  2162. src_size, index = get_delta_header_size(delta, index)
  2163. dest_size, index = get_delta_header_size(delta, index)
  2164. if src_size != len(src_buf):
  2165. raise ApplyDeltaError(
  2166. f"Unexpected source buffer size: {src_size} vs {len(src_buf)}"
  2167. )
  2168. while index < delta_length:
  2169. cmd = ord(delta[index : index + 1])
  2170. index += 1
  2171. if cmd & 0x80:
  2172. cp_off = 0
  2173. for i in range(4):
  2174. if cmd & (1 << i):
  2175. x = ord(delta[index : index + 1])
  2176. index += 1
  2177. cp_off |= x << (i * 8)
  2178. cp_size = 0
  2179. # Version 3 packs can contain copy sizes larger than 64K.
  2180. for i in range(3):
  2181. if cmd & (1 << (4 + i)):
  2182. x = ord(delta[index : index + 1])
  2183. index += 1
  2184. cp_size |= x << (i * 8)
  2185. if cp_size == 0:
  2186. cp_size = 0x10000
  2187. if (
  2188. cp_off + cp_size < cp_size
  2189. or cp_off + cp_size > src_size
  2190. or cp_size > dest_size
  2191. ):
  2192. break
  2193. out.append(src_buf[cp_off : cp_off + cp_size])
  2194. elif cmd != 0:
  2195. out.append(delta[index : index + cmd])
  2196. index += cmd
  2197. else:
  2198. raise ApplyDeltaError("Invalid opcode 0")
  2199. if index != delta_length:
  2200. raise ApplyDeltaError(f"delta not empty: {delta[index:]!r}")
  2201. if dest_size != chunks_length(out):
  2202. raise ApplyDeltaError("dest size incorrect")
  2203. return out
  2204. def write_pack_index_v2(
  2205. f, entries: Iterable[PackIndexEntry], pack_checksum: bytes
  2206. ) -> bytes:
  2207. """Write a new pack index file.
  2208. Args:
  2209. f: File-like object to write to
  2210. entries: List of tuples with object name (sha), offset_in_pack, and
  2211. crc32_checksum.
  2212. pack_checksum: Checksum of the pack file.
  2213. Returns: The SHA of the index file written
  2214. """
  2215. f = SHA1Writer(f)
  2216. f.write(b"\377tOc") # Magic!
  2217. f.write(struct.pack(">L", 2))
  2218. fan_out_table: dict[int, int] = defaultdict(lambda: 0)
  2219. for name, offset, entry_checksum in entries:
  2220. fan_out_table[ord(name[:1])] += 1
  2221. # Fan-out table
  2222. largetable: list[int] = []
  2223. for i in range(0x100):
  2224. f.write(struct.pack(b">L", fan_out_table[i]))
  2225. fan_out_table[i + 1] += fan_out_table[i]
  2226. for name, offset, entry_checksum in entries:
  2227. f.write(name)
  2228. for name, offset, entry_checksum in entries:
  2229. f.write(struct.pack(b">L", entry_checksum))
  2230. for name, offset, entry_checksum in entries:
  2231. if offset < 2**31:
  2232. f.write(struct.pack(b">L", offset))
  2233. else:
  2234. f.write(struct.pack(b">L", 2**31 + len(largetable)))
  2235. largetable.append(offset)
  2236. for offset in largetable:
  2237. f.write(struct.pack(b">Q", offset))
  2238. assert len(pack_checksum) == 20
  2239. f.write(pack_checksum)
  2240. return f.write_sha()
  2241. def write_pack_index_v3(
  2242. f, entries: Iterable[PackIndexEntry], pack_checksum: bytes, hash_algorithm: int = 1
  2243. ) -> bytes:
  2244. """Write a new pack index file in v3 format.
  2245. Args:
  2246. f: File-like object to write to
  2247. entries: List of tuples with object name (sha), offset_in_pack, and
  2248. crc32_checksum.
  2249. pack_checksum: Checksum of the pack file.
  2250. hash_algorithm: Hash algorithm identifier (1 = SHA-1, 2 = SHA-256)
  2251. Returns: The SHA of the index file written
  2252. """
  2253. if hash_algorithm == 1:
  2254. hash_size = 20 # SHA-1
  2255. writer_cls = SHA1Writer
  2256. elif hash_algorithm == 2:
  2257. hash_size = 32 # SHA-256
  2258. # TODO: Add SHA256Writer when SHA-256 support is implemented
  2259. raise NotImplementedError("SHA-256 support not yet implemented")
  2260. else:
  2261. raise ValueError(f"Unknown hash algorithm {hash_algorithm}")
  2262. # Convert entries to list to allow multiple iterations
  2263. entries_list = list(entries)
  2264. # Calculate shortest unambiguous prefix length for object names
  2265. # For now, use full hash size (this could be optimized)
  2266. shortened_oid_len = hash_size
  2267. f = writer_cls(f)
  2268. f.write(b"\377tOc") # Magic!
  2269. f.write(struct.pack(">L", 3)) # Version 3
  2270. f.write(struct.pack(">L", hash_algorithm)) # Hash algorithm
  2271. f.write(struct.pack(">L", shortened_oid_len)) # Shortened OID length
  2272. fan_out_table: dict[int, int] = defaultdict(lambda: 0)
  2273. for name, offset, entry_checksum in entries_list:
  2274. if len(name) != hash_size:
  2275. raise ValueError(
  2276. f"Object name has wrong length: expected {hash_size}, got {len(name)}"
  2277. )
  2278. fan_out_table[ord(name[:1])] += 1
  2279. # Fan-out table
  2280. largetable: list[int] = []
  2281. for i in range(0x100):
  2282. f.write(struct.pack(b">L", fan_out_table[i]))
  2283. fan_out_table[i + 1] += fan_out_table[i]
  2284. # Object names table
  2285. for name, offset, entry_checksum in entries_list:
  2286. f.write(name)
  2287. # CRC32 checksums table
  2288. for name, offset, entry_checksum in entries_list:
  2289. f.write(struct.pack(b">L", entry_checksum))
  2290. # Offset table
  2291. for name, offset, entry_checksum in entries_list:
  2292. if offset < 2**31:
  2293. f.write(struct.pack(b">L", offset))
  2294. else:
  2295. f.write(struct.pack(b">L", 2**31 + len(largetable)))
  2296. largetable.append(offset)
  2297. # Large offset table
  2298. for offset in largetable:
  2299. f.write(struct.pack(b">Q", offset))
  2300. assert len(pack_checksum) == hash_size, (
  2301. f"Pack checksum has wrong length: expected {hash_size}, got {len(pack_checksum)}"
  2302. )
  2303. f.write(pack_checksum)
  2304. return f.write_sha()
  2305. def write_pack_index(
  2306. index_filename, entries, pack_checksum, progress=None, version=None
  2307. ):
  2308. """Write a pack index file.
  2309. Args:
  2310. index_filename: Index filename.
  2311. entries: List of (checksum, offset, crc32) tuples
  2312. pack_checksum: Checksum of the pack file.
  2313. progress: Progress function (not currently used)
  2314. version: Pack index version to use (1, 2, or 3). If None, defaults to DEFAULT_PACK_INDEX_VERSION.
  2315. Returns:
  2316. SHA of the written index file
  2317. """
  2318. if version is None:
  2319. version = DEFAULT_PACK_INDEX_VERSION
  2320. if version == 1:
  2321. return write_pack_index_v1(index_filename, entries, pack_checksum)
  2322. elif version == 2:
  2323. return write_pack_index_v2(index_filename, entries, pack_checksum)
  2324. elif version == 3:
  2325. return write_pack_index_v3(index_filename, entries, pack_checksum)
  2326. else:
  2327. raise ValueError(f"Unsupported pack index version: {version}")
  2328. class Pack:
  2329. """A Git pack object."""
  2330. _data_load: Optional[Callable[[], PackData]]
  2331. _idx_load: Optional[Callable[[], PackIndex]]
  2332. _data: Optional[PackData]
  2333. _idx: Optional[PackIndex]
  2334. def __init__(
  2335. self,
  2336. basename,
  2337. resolve_ext_ref: Optional[ResolveExtRefFn] = None,
  2338. *,
  2339. delta_window_size=None,
  2340. window_memory=None,
  2341. delta_cache_size=None,
  2342. depth=None,
  2343. threads=None,
  2344. big_file_threshold=None,
  2345. ) -> None:
  2346. self._basename = basename
  2347. self._data = None
  2348. self._idx = None
  2349. self._idx_path = self._basename + ".idx"
  2350. self._data_path = self._basename + ".pack"
  2351. self.delta_window_size = delta_window_size
  2352. self.window_memory = window_memory
  2353. self.delta_cache_size = delta_cache_size
  2354. self.depth = depth
  2355. self.threads = threads
  2356. self.big_file_threshold = big_file_threshold
  2357. self._data_load = lambda: PackData(
  2358. self._data_path,
  2359. delta_window_size=delta_window_size,
  2360. window_memory=window_memory,
  2361. delta_cache_size=delta_cache_size,
  2362. depth=depth,
  2363. threads=threads,
  2364. big_file_threshold=big_file_threshold,
  2365. )
  2366. self._idx_load = lambda: load_pack_index(self._idx_path)
  2367. self.resolve_ext_ref = resolve_ext_ref
  2368. @classmethod
  2369. def from_lazy_objects(cls, data_fn, idx_fn):
  2370. """Create a new pack object from callables to load pack data and
  2371. index objects.
  2372. """
  2373. ret = cls("")
  2374. ret._data_load = data_fn
  2375. ret._idx_load = idx_fn
  2376. return ret
  2377. @classmethod
  2378. def from_objects(cls, data, idx):
  2379. """Create a new pack object from pack data and index objects."""
  2380. ret = cls("")
  2381. ret._data = data
  2382. ret._data_load = None
  2383. ret._idx = idx
  2384. ret._idx_load = None
  2385. ret.check_length_and_checksum()
  2386. return ret
  2387. def name(self):
  2388. """The SHA over the SHAs of the objects in this pack."""
  2389. return self.index.objects_sha1()
  2390. @property
  2391. def data(self) -> PackData:
  2392. """The pack data object being used."""
  2393. if self._data is None:
  2394. assert self._data_load
  2395. self._data = self._data_load()
  2396. self.check_length_and_checksum()
  2397. return self._data
  2398. @property
  2399. def index(self) -> PackIndex:
  2400. """The index being used.
  2401. Note: This may be an in-memory index
  2402. """
  2403. if self._idx is None:
  2404. assert self._idx_load
  2405. self._idx = self._idx_load()
  2406. return self._idx
  2407. def close(self) -> None:
  2408. if self._data is not None:
  2409. self._data.close()
  2410. if self._idx is not None:
  2411. self._idx.close()
  2412. def __enter__(self):
  2413. return self
  2414. def __exit__(self, exc_type, exc_val, exc_tb):
  2415. self.close()
  2416. def __eq__(self, other):
  2417. return isinstance(self, type(other)) and self.index == other.index
  2418. def __len__(self) -> int:
  2419. """Number of entries in this pack."""
  2420. return len(self.index)
  2421. def __repr__(self) -> str:
  2422. return f"{self.__class__.__name__}({self._basename!r})"
  2423. def __iter__(self):
  2424. """Iterate over all the sha1s of the objects in this pack."""
  2425. return iter(self.index)
  2426. def check_length_and_checksum(self) -> None:
  2427. """Sanity check the length and checksum of the pack index and data."""
  2428. assert len(self.index) == len(self.data), (
  2429. f"Length mismatch: {len(self.index)} (index) != {len(self.data)} (data)"
  2430. )
  2431. idx_stored_checksum = self.index.get_pack_checksum()
  2432. data_stored_checksum = self.data.get_stored_checksum()
  2433. if (
  2434. idx_stored_checksum is not None
  2435. and idx_stored_checksum != data_stored_checksum
  2436. ):
  2437. raise ChecksumMismatch(
  2438. sha_to_hex(idx_stored_checksum),
  2439. sha_to_hex(data_stored_checksum),
  2440. )
  2441. def check(self) -> None:
  2442. """Check the integrity of this pack.
  2443. Raises:
  2444. ChecksumMismatch: if a checksum for the index or data is wrong
  2445. """
  2446. self.index.check()
  2447. self.data.check()
  2448. for obj in self.iterobjects():
  2449. obj.check()
  2450. # TODO: object connectivity checks
  2451. def get_stored_checksum(self) -> bytes:
  2452. return self.data.get_stored_checksum()
  2453. def pack_tuples(self):
  2454. return [(o, None) for o in self.iterobjects()]
  2455. def __contains__(self, sha1: bytes) -> bool:
  2456. """Check whether this pack contains a particular SHA1."""
  2457. try:
  2458. self.index.object_offset(sha1)
  2459. return True
  2460. except KeyError:
  2461. return False
  2462. def get_raw(self, sha1: bytes) -> tuple[int, bytes]:
  2463. offset = self.index.object_offset(sha1)
  2464. obj_type, obj = self.data.get_object_at(offset)
  2465. type_num, chunks = self.resolve_object(offset, obj_type, obj)
  2466. return type_num, b"".join(chunks)
  2467. def __getitem__(self, sha1: bytes) -> ShaFile:
  2468. """Retrieve the specified SHA1."""
  2469. type, uncomp = self.get_raw(sha1)
  2470. return ShaFile.from_raw_string(type, uncomp, sha=sha1)
  2471. def iterobjects(self) -> Iterator[ShaFile]:
  2472. """Iterate over the objects in this pack."""
  2473. return iter(
  2474. PackInflater.for_pack_data(self.data, resolve_ext_ref=self.resolve_ext_ref)
  2475. )
  2476. def iterobjects_subset(
  2477. self, shas: Iterable[ObjectID], *, allow_missing: bool = False
  2478. ) -> Iterator[ShaFile]:
  2479. return (
  2480. uo
  2481. for uo in PackInflater.for_pack_subset(
  2482. self,
  2483. shas,
  2484. allow_missing=allow_missing,
  2485. resolve_ext_ref=self.resolve_ext_ref,
  2486. )
  2487. if uo.id in shas
  2488. )
  2489. def iter_unpacked_subset(
  2490. self,
  2491. shas: Iterable[ObjectID],
  2492. *,
  2493. include_comp: bool = False,
  2494. allow_missing: bool = False,
  2495. convert_ofs_delta: bool = False,
  2496. ) -> Iterator[UnpackedObject]:
  2497. ofs_pending: dict[int, list[UnpackedObject]] = defaultdict(list)
  2498. ofs: dict[bytes, int] = {}
  2499. todo = set(shas)
  2500. for unpacked in self.iter_unpacked(include_comp=include_comp):
  2501. sha = unpacked.sha()
  2502. ofs[unpacked.offset] = sha
  2503. hexsha = sha_to_hex(sha)
  2504. if hexsha in todo:
  2505. if unpacked.pack_type_num == OFS_DELTA:
  2506. assert isinstance(unpacked.delta_base, int)
  2507. base_offset = unpacked.offset - unpacked.delta_base
  2508. try:
  2509. unpacked.delta_base = ofs[base_offset]
  2510. except KeyError:
  2511. ofs_pending[base_offset].append(unpacked)
  2512. continue
  2513. else:
  2514. unpacked.pack_type_num = REF_DELTA
  2515. yield unpacked
  2516. todo.remove(hexsha)
  2517. for child in ofs_pending.pop(unpacked.offset, []):
  2518. child.pack_type_num = REF_DELTA
  2519. child.delta_base = sha
  2520. yield child
  2521. assert not ofs_pending
  2522. if not allow_missing and todo:
  2523. raise UnresolvedDeltas(list(todo))
  2524. def iter_unpacked(self, include_comp=False):
  2525. ofs_to_entries = {
  2526. ofs: (sha, crc32) for (sha, ofs, crc32) in self.index.iterentries()
  2527. }
  2528. for unpacked in self.data.iter_unpacked(include_comp=include_comp):
  2529. (sha, crc32) = ofs_to_entries[unpacked.offset]
  2530. unpacked._sha = sha
  2531. unpacked.crc32 = crc32
  2532. yield unpacked
  2533. def keep(self, msg: Optional[bytes] = None) -> str:
  2534. """Add a .keep file for the pack, preventing git from garbage collecting it.
  2535. Args:
  2536. msg: A message written inside the .keep file; can be used later
  2537. to determine whether or not a .keep file is obsolete.
  2538. Returns: The path of the .keep file, as a string.
  2539. """
  2540. keepfile_name = f"{self._basename}.keep"
  2541. with GitFile(keepfile_name, "wb") as keepfile:
  2542. if msg:
  2543. keepfile.write(msg)
  2544. keepfile.write(b"\n")
  2545. return keepfile_name
  2546. def get_ref(self, sha: bytes) -> tuple[Optional[int], int, OldUnpackedObject]:
  2547. """Get the object for a ref SHA, only looking in this pack."""
  2548. # TODO: cache these results
  2549. try:
  2550. offset = self.index.object_offset(sha)
  2551. except KeyError:
  2552. offset = None
  2553. if offset:
  2554. type, obj = self.data.get_object_at(offset)
  2555. elif self.resolve_ext_ref:
  2556. type, obj = self.resolve_ext_ref(sha)
  2557. else:
  2558. raise KeyError(sha)
  2559. return offset, type, obj
  2560. def resolve_object(
  2561. self, offset: int, type: int, obj, get_ref=None
  2562. ) -> tuple[int, Iterable[bytes]]:
  2563. """Resolve an object, possibly resolving deltas when necessary.
  2564. Returns: Tuple with object type and contents.
  2565. """
  2566. # Walk down the delta chain, building a stack of deltas to reach
  2567. # the requested object.
  2568. base_offset = offset
  2569. base_type = type
  2570. base_obj = obj
  2571. delta_stack = []
  2572. while base_type in DELTA_TYPES:
  2573. prev_offset = base_offset
  2574. if get_ref is None:
  2575. get_ref = self.get_ref
  2576. if base_type == OFS_DELTA:
  2577. (delta_offset, delta) = base_obj
  2578. # TODO: clean up asserts and replace with nicer error messages
  2579. base_offset = base_offset - delta_offset
  2580. base_type, base_obj = self.data.get_object_at(base_offset)
  2581. assert isinstance(base_type, int)
  2582. elif base_type == REF_DELTA:
  2583. (basename, delta) = base_obj
  2584. assert isinstance(basename, bytes) and len(basename) == 20
  2585. base_offset, base_type, base_obj = get_ref(basename)
  2586. assert isinstance(base_type, int)
  2587. if base_offset == prev_offset: # object is based on itself
  2588. raise UnresolvedDeltas([basename])
  2589. delta_stack.append((prev_offset, base_type, delta))
  2590. # Now grab the base object (mustn't be a delta) and apply the
  2591. # deltas all the way up the stack.
  2592. chunks = base_obj
  2593. for prev_offset, _delta_type, delta in reversed(delta_stack):
  2594. chunks = apply_delta(chunks, delta)
  2595. if prev_offset is not None:
  2596. self.data._offset_cache[prev_offset] = base_type, chunks
  2597. return base_type, chunks
  2598. def entries(
  2599. self, progress: Optional[ProgressFn] = None
  2600. ) -> Iterator[PackIndexEntry]:
  2601. """Yield entries summarizing the contents of this pack.
  2602. Args:
  2603. progress: Progress function, called with current and total
  2604. object count.
  2605. Returns: iterator of tuples with (sha, offset, crc32)
  2606. """
  2607. return self.data.iterentries(
  2608. progress=progress, resolve_ext_ref=self.resolve_ext_ref
  2609. )
  2610. def sorted_entries(
  2611. self, progress: Optional[ProgressFn] = None
  2612. ) -> Iterator[PackIndexEntry]:
  2613. """Return entries in this pack, sorted by SHA.
  2614. Args:
  2615. progress: Progress function, called with current and total
  2616. object count
  2617. Returns: Iterator of tuples with (sha, offset, crc32)
  2618. """
  2619. return self.data.sorted_entries(
  2620. progress=progress, resolve_ext_ref=self.resolve_ext_ref
  2621. )
  2622. def get_unpacked_object(
  2623. self, sha: bytes, *, include_comp: bool = False, convert_ofs_delta: bool = True
  2624. ) -> UnpackedObject:
  2625. """Get the unpacked object for a sha.
  2626. Args:
  2627. sha: SHA of object to fetch
  2628. include_comp: Whether to include compression data in UnpackedObject
  2629. """
  2630. offset = self.index.object_offset(sha)
  2631. unpacked = self.data.get_unpacked_object_at(offset, include_comp=include_comp)
  2632. if unpacked.pack_type_num == OFS_DELTA and convert_ofs_delta:
  2633. assert isinstance(unpacked.delta_base, int)
  2634. unpacked.delta_base = self.index.object_sha1(offset - unpacked.delta_base)
  2635. unpacked.pack_type_num = REF_DELTA
  2636. return unpacked
  2637. def extend_pack(
  2638. f: BinaryIO,
  2639. object_ids: set[ObjectID],
  2640. get_raw,
  2641. *,
  2642. compression_level=-1,
  2643. progress=None,
  2644. ) -> tuple[bytes, list]:
  2645. """Extend a pack file with more objects.
  2646. The caller should make sure that object_ids does not contain any objects
  2647. that are already in the pack
  2648. """
  2649. # Update the header with the new number of objects.
  2650. f.seek(0)
  2651. _version, num_objects = read_pack_header(f.read)
  2652. if object_ids:
  2653. f.seek(0)
  2654. write_pack_header(f.write, num_objects + len(object_ids))
  2655. # Must flush before reading (http://bugs.python.org/issue3207)
  2656. f.flush()
  2657. # Rescan the rest of the pack, computing the SHA with the new header.
  2658. new_sha = compute_file_sha(f, end_ofs=-20)
  2659. # Must reposition before writing (http://bugs.python.org/issue3207)
  2660. f.seek(0, os.SEEK_CUR)
  2661. extra_entries = []
  2662. # Complete the pack.
  2663. for i, object_id in enumerate(object_ids):
  2664. if progress is not None:
  2665. progress(
  2666. (f"writing extra base objects: {i}/{len(object_ids)}\r").encode("ascii")
  2667. )
  2668. assert len(object_id) == 20
  2669. type_num, data = get_raw(object_id)
  2670. offset = f.tell()
  2671. crc32 = write_pack_object(
  2672. f.write,
  2673. type_num,
  2674. data,
  2675. sha=new_sha,
  2676. compression_level=compression_level,
  2677. )
  2678. extra_entries.append((object_id, offset, crc32))
  2679. pack_sha = new_sha.digest()
  2680. f.write(pack_sha)
  2681. return pack_sha, extra_entries
  2682. try:
  2683. from dulwich._pack import ( # type: ignore
  2684. apply_delta, # type: ignore
  2685. bisect_find_sha, # type: ignore
  2686. )
  2687. except ImportError:
  2688. pass