pack.py 134 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115
  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. __all__ = [
  32. "DEFAULT_PACK_DELTA_WINDOW_SIZE",
  33. "DEFAULT_PACK_INDEX_VERSION",
  34. "DELTA_TYPES",
  35. "OFS_DELTA",
  36. "PACK_SPOOL_FILE_MAX_SIZE",
  37. "REF_DELTA",
  38. "DeltaChainIterator",
  39. "FilePackIndex",
  40. "MemoryPackIndex",
  41. "ObjectContainer",
  42. "Pack",
  43. "PackChunkGenerator",
  44. "PackData",
  45. "PackFileDisappeared",
  46. "PackHint",
  47. "PackIndex",
  48. "PackIndex1",
  49. "PackIndex2",
  50. "PackIndex3",
  51. "PackIndexEntry",
  52. "PackIndexer",
  53. "PackInflater",
  54. "PackStreamCopier",
  55. "PackStreamReader",
  56. "PackedObjectContainer",
  57. "SHA1Reader",
  58. "SHA1Writer",
  59. "UnpackedObject",
  60. "UnpackedObjectIterator",
  61. "UnpackedObjectStream",
  62. "UnresolvedDeltas",
  63. "apply_delta",
  64. "bisect_find_sha",
  65. "chunks_length",
  66. "compute_file_sha",
  67. "deltas_from_sorted_objects",
  68. "deltify_pack_objects",
  69. "extend_pack",
  70. "find_reusable_deltas",
  71. "full_unpacked_object",
  72. "generate_unpacked_objects",
  73. "iter_sha1",
  74. "load_pack_index",
  75. "load_pack_index_file",
  76. "obj_sha",
  77. "pack_header_chunks",
  78. "pack_object_chunks",
  79. "pack_object_header",
  80. "pack_objects_to_data",
  81. "read_pack_header",
  82. "read_zlib_chunks",
  83. "sort_objects_for_delta",
  84. "take_msb_bytes",
  85. "unpack_object",
  86. "write_pack",
  87. "write_pack_data",
  88. "write_pack_from_container",
  89. "write_pack_header",
  90. "write_pack_index",
  91. "write_pack_object",
  92. "write_pack_objects",
  93. ]
  94. import binascii
  95. from collections import defaultdict, deque
  96. from contextlib import suppress
  97. from io import BytesIO, UnsupportedOperation
  98. try:
  99. from cdifflib import CSequenceMatcher as SequenceMatcher
  100. except ModuleNotFoundError:
  101. from difflib import SequenceMatcher
  102. import os
  103. import struct
  104. import sys
  105. import warnings
  106. import zlib
  107. from collections.abc import Callable, Iterable, Iterator, Sequence, Set
  108. from hashlib import sha1
  109. from itertools import chain
  110. from os import SEEK_CUR, SEEK_END
  111. from struct import unpack_from
  112. from types import TracebackType
  113. from typing import (
  114. IO,
  115. TYPE_CHECKING,
  116. Any,
  117. BinaryIO,
  118. Generic,
  119. Protocol,
  120. TypeVar,
  121. cast,
  122. )
  123. try:
  124. import mmap
  125. except ImportError:
  126. has_mmap = False
  127. else:
  128. has_mmap = True
  129. if TYPE_CHECKING:
  130. from _hashlib import HASH as HashObject
  131. from .bitmap import PackBitmap
  132. from .commit_graph import CommitGraph
  133. from .object_store import BaseObjectStore
  134. from .refs import Ref
  135. # For some reason the above try, except fails to set has_mmap = False for plan9
  136. if sys.platform == "Plan9":
  137. has_mmap = False
  138. from . import replace_me
  139. from .errors import ApplyDeltaError, ChecksumMismatch
  140. from .file import GitFile, _GitFile
  141. from .lru_cache import LRUSizeCache
  142. from .objects import (
  143. ObjectID,
  144. RawObjectID,
  145. ShaFile,
  146. hex_to_sha,
  147. object_header,
  148. sha_to_hex,
  149. )
  150. OFS_DELTA = 6
  151. REF_DELTA = 7
  152. DELTA_TYPES = (OFS_DELTA, REF_DELTA)
  153. DEFAULT_PACK_DELTA_WINDOW_SIZE = 10
  154. # Keep pack files under 16Mb in memory, otherwise write them out to disk
  155. PACK_SPOOL_FILE_MAX_SIZE = 16 * 1024 * 1024
  156. # Default pack index version to use when none is specified
  157. DEFAULT_PACK_INDEX_VERSION = 2
  158. OldUnpackedObject = tuple[bytes | int, list[bytes]] | list[bytes]
  159. ResolveExtRefFn = Callable[[bytes], tuple[int, OldUnpackedObject]]
  160. ProgressFn = Callable[[int, str], None]
  161. PackHint = tuple[int, bytes | None]
  162. class UnresolvedDeltas(Exception):
  163. """Delta objects could not be resolved."""
  164. def __init__(self, shas: list[bytes]) -> None:
  165. """Initialize UnresolvedDeltas exception.
  166. Args:
  167. shas: List of SHA hashes for unresolved delta objects
  168. """
  169. self.shas = shas
  170. class ObjectContainer(Protocol):
  171. """Protocol for objects that can contain git objects."""
  172. def add_object(self, obj: ShaFile) -> None:
  173. """Add a single object to this object store."""
  174. def add_objects(
  175. self,
  176. objects: Sequence[tuple[ShaFile, str | None]],
  177. progress: Callable[..., None] | None = None,
  178. ) -> "Pack | None":
  179. """Add a set of objects to this object store.
  180. Args:
  181. objects: Iterable over a list of (object, path) tuples
  182. progress: Progress callback for object insertion
  183. Returns: Optional Pack object of the objects written.
  184. """
  185. def __contains__(self, sha1: "ObjectID") -> bool:
  186. """Check if a hex sha is present."""
  187. def __getitem__(self, sha1: "ObjectID | RawObjectID") -> ShaFile:
  188. """Retrieve an object."""
  189. def get_commit_graph(self) -> "CommitGraph | None":
  190. """Get the commit graph for this object store.
  191. Returns:
  192. CommitGraph object if available, None otherwise
  193. """
  194. return None
  195. class PackedObjectContainer(ObjectContainer):
  196. """Container for objects packed in a pack file."""
  197. def get_unpacked_object(
  198. self, sha1: "ObjectID | RawObjectID", *, include_comp: bool = False
  199. ) -> "UnpackedObject":
  200. """Get a raw unresolved object.
  201. Args:
  202. sha1: SHA-1 hash of the object
  203. include_comp: Whether to include compressed data
  204. Returns:
  205. UnpackedObject instance
  206. """
  207. raise NotImplementedError(self.get_unpacked_object)
  208. def iterobjects_subset(
  209. self, shas: Iterable["ObjectID"], *, allow_missing: bool = False
  210. ) -> Iterator[ShaFile]:
  211. """Iterate over a subset of objects.
  212. Args:
  213. shas: Iterable of object SHAs to retrieve
  214. allow_missing: If True, skip missing objects
  215. Returns:
  216. Iterator of ShaFile objects
  217. """
  218. raise NotImplementedError(self.iterobjects_subset)
  219. def iter_unpacked_subset(
  220. self,
  221. shas: Iterable["ObjectID | RawObjectID"],
  222. *,
  223. include_comp: bool = False,
  224. allow_missing: bool = False,
  225. convert_ofs_delta: bool = True,
  226. ) -> Iterator["UnpackedObject"]:
  227. """Iterate over unpacked objects from a subset of SHAs.
  228. Args:
  229. shas: Set of object SHAs to retrieve
  230. include_comp: Include compressed data if True
  231. allow_missing: If True, skip missing objects
  232. convert_ofs_delta: If True, convert offset deltas to ref deltas
  233. Returns:
  234. Iterator of UnpackedObject instances
  235. """
  236. raise NotImplementedError(self.iter_unpacked_subset)
  237. class UnpackedObjectStream:
  238. """Abstract base class for a stream of unpacked objects."""
  239. def __iter__(self) -> Iterator["UnpackedObject"]:
  240. """Iterate over unpacked objects."""
  241. raise NotImplementedError(self.__iter__)
  242. def __len__(self) -> int:
  243. """Return the number of objects in the stream."""
  244. raise NotImplementedError(self.__len__)
  245. def take_msb_bytes(
  246. read: Callable[[int], bytes], crc32: int | None = None
  247. ) -> tuple[list[int], int | None]:
  248. """Read bytes marked with most significant bit.
  249. Args:
  250. read: Read function
  251. crc32: Optional CRC32 checksum to update
  252. Returns:
  253. Tuple of (list of bytes read, updated CRC32 or None)
  254. """
  255. ret: list[int] = []
  256. while len(ret) == 0 or ret[-1] & 0x80:
  257. b = read(1)
  258. if crc32 is not None:
  259. crc32 = binascii.crc32(b, crc32)
  260. ret.append(ord(b[:1]))
  261. return ret, crc32
  262. class PackFileDisappeared(Exception):
  263. """Raised when a pack file unexpectedly disappears."""
  264. def __init__(self, obj: object) -> None:
  265. """Initialize PackFileDisappeared exception.
  266. Args:
  267. obj: The object that triggered the exception
  268. """
  269. self.obj = obj
  270. class UnpackedObject:
  271. """Class encapsulating an object unpacked from a pack file.
  272. These objects should only be created from within unpack_object. Most
  273. members start out as empty and are filled in at various points by
  274. read_zlib_chunks, unpack_object, DeltaChainIterator, etc.
  275. End users of this object should take care that the function they're getting
  276. this object from is guaranteed to set the members they need.
  277. """
  278. __slots__ = [
  279. "_sha", # Cached binary SHA.
  280. "comp_chunks", # Compressed object chunks.
  281. "crc32", # CRC32.
  282. "decomp_chunks", # Decompressed object chunks.
  283. "decomp_len", # Decompressed length of this object.
  284. "delta_base", # Delta base offset or SHA.
  285. "obj_chunks", # Decompressed and delta-resolved chunks.
  286. "obj_type_num", # Type of this object.
  287. "offset", # Offset in its pack.
  288. "pack_type_num", # Type of this object in the pack (may be a delta).
  289. ]
  290. obj_type_num: int | None
  291. obj_chunks: list[bytes] | None
  292. delta_base: None | bytes | int
  293. decomp_chunks: list[bytes]
  294. comp_chunks: list[bytes] | None
  295. decomp_len: int | None
  296. crc32: int | None
  297. offset: int | None
  298. pack_type_num: int
  299. _sha: bytes | None
  300. # TODO(dborowitz): read_zlib_chunks and unpack_object could very well be
  301. # methods of this object.
  302. def __init__(
  303. self,
  304. pack_type_num: int,
  305. *,
  306. delta_base: None | bytes | int = None,
  307. decomp_len: int | None = None,
  308. crc32: int | None = None,
  309. sha: bytes | None = None,
  310. decomp_chunks: list[bytes] | None = None,
  311. offset: int | None = None,
  312. ) -> None:
  313. """Initialize an UnpackedObject.
  314. Args:
  315. pack_type_num: Type number of this object in the pack
  316. delta_base: Delta base (offset or SHA) if this is a delta object
  317. decomp_len: Decompressed length of this object
  318. crc32: CRC32 checksum
  319. sha: SHA-1 hash of the object
  320. decomp_chunks: Decompressed chunks
  321. offset: Offset in the pack file
  322. """
  323. self.offset = offset
  324. self._sha = sha
  325. self.pack_type_num = pack_type_num
  326. self.delta_base = delta_base
  327. self.comp_chunks = None
  328. self.decomp_chunks: list[bytes] = decomp_chunks or []
  329. if decomp_chunks is not None and decomp_len is None:
  330. self.decomp_len = sum(map(len, decomp_chunks))
  331. else:
  332. self.decomp_len = decomp_len
  333. self.crc32 = crc32
  334. if pack_type_num in DELTA_TYPES:
  335. self.obj_type_num = None
  336. self.obj_chunks = None
  337. else:
  338. self.obj_type_num = pack_type_num
  339. self.obj_chunks = self.decomp_chunks
  340. self.delta_base = delta_base
  341. def sha(self) -> RawObjectID:
  342. """Return the binary SHA of this object."""
  343. if self._sha is None:
  344. assert self.obj_type_num is not None and self.obj_chunks is not None
  345. self._sha = obj_sha(self.obj_type_num, self.obj_chunks)
  346. return RawObjectID(self._sha)
  347. def sha_file(self) -> ShaFile:
  348. """Return a ShaFile from this object."""
  349. assert self.obj_type_num is not None and self.obj_chunks is not None
  350. return ShaFile.from_raw_chunks(self.obj_type_num, self.obj_chunks)
  351. # Only provided for backwards compatibility with code that expects either
  352. # chunks or a delta tuple.
  353. def _obj(self) -> OldUnpackedObject:
  354. """Return the decompressed chunks, or (delta base, delta chunks)."""
  355. if self.pack_type_num in DELTA_TYPES:
  356. assert isinstance(self.delta_base, (bytes, int))
  357. return (self.delta_base, self.decomp_chunks)
  358. else:
  359. return self.decomp_chunks
  360. def __eq__(self, other: object) -> bool:
  361. """Check equality with another UnpackedObject."""
  362. if not isinstance(other, UnpackedObject):
  363. return False
  364. for slot in self.__slots__:
  365. if getattr(self, slot) != getattr(other, slot):
  366. return False
  367. return True
  368. def __ne__(self, other: object) -> bool:
  369. """Check inequality with another UnpackedObject."""
  370. return not (self == other)
  371. def __repr__(self) -> str:
  372. """Return string representation of this UnpackedObject."""
  373. data = [f"{s}={getattr(self, s)!r}" for s in self.__slots__]
  374. return "{}({})".format(self.__class__.__name__, ", ".join(data))
  375. _ZLIB_BUFSIZE = 65536 # 64KB buffer for better I/O performance
  376. def read_zlib_chunks(
  377. read_some: Callable[[int], bytes],
  378. unpacked: UnpackedObject,
  379. include_comp: bool = False,
  380. buffer_size: int = _ZLIB_BUFSIZE,
  381. ) -> bytes:
  382. """Read zlib data from a buffer.
  383. This function requires that the buffer have additional data following the
  384. compressed data, which is guaranteed to be the case for git pack files.
  385. Args:
  386. read_some: Read function that returns at least one byte, but may
  387. return less than the requested size.
  388. unpacked: An UnpackedObject to write result data to. If its crc32
  389. attr is not None, the CRC32 of the compressed bytes will be computed
  390. using this starting CRC32.
  391. After this function, will have the following attrs set:
  392. * comp_chunks (if include_comp is True)
  393. * decomp_chunks
  394. * decomp_len
  395. * crc32
  396. include_comp: If True, include compressed data in the result.
  397. buffer_size: Size of the read buffer.
  398. Returns: Leftover unused data from the decompression.
  399. Raises:
  400. zlib.error: if a decompression error occurred.
  401. """
  402. if unpacked.decomp_len is None or unpacked.decomp_len <= -1:
  403. raise ValueError("non-negative zlib data stream size expected")
  404. decomp_obj = zlib.decompressobj()
  405. comp_chunks = []
  406. decomp_chunks = unpacked.decomp_chunks
  407. decomp_len = 0
  408. crc32 = unpacked.crc32
  409. while True:
  410. add = read_some(buffer_size)
  411. if not add:
  412. raise zlib.error("EOF before end of zlib stream")
  413. comp_chunks.append(add)
  414. decomp = decomp_obj.decompress(add)
  415. decomp_len += len(decomp)
  416. decomp_chunks.append(decomp)
  417. unused = decomp_obj.unused_data
  418. if unused:
  419. left = len(unused)
  420. if crc32 is not None:
  421. crc32 = binascii.crc32(add[:-left], crc32)
  422. if include_comp:
  423. comp_chunks[-1] = add[:-left]
  424. break
  425. elif crc32 is not None:
  426. crc32 = binascii.crc32(add, crc32)
  427. if crc32 is not None:
  428. crc32 &= 0xFFFFFFFF
  429. if decomp_len != unpacked.decomp_len:
  430. raise zlib.error("decompressed data does not match expected size")
  431. unpacked.crc32 = crc32
  432. if include_comp:
  433. unpacked.comp_chunks = comp_chunks
  434. return unused
  435. def iter_sha1(iter: Iterable[bytes]) -> bytes:
  436. """Return the hexdigest of the SHA1 over a set of names.
  437. Args:
  438. iter: Iterator over string objects
  439. Returns: 40-byte hex sha1 digest
  440. """
  441. sha = sha1()
  442. for name in iter:
  443. sha.update(name)
  444. return sha.hexdigest().encode("ascii")
  445. def load_pack_index(path: str | os.PathLike[str], object_format: ObjectFormat| None = None) -> "PackIndex":
  446. """Load an index file by path.
  447. Args:
  448. path: Path to the index file
  449. object_format: Hash algorithm used by the repository
  450. Returns: A PackIndex loaded from the given path
  451. """
  452. with GitFile(path, "rb") as f:
  453. return load_pack_index_file(path, f, object_format=object_format)
  454. def _load_file_contents(
  455. f: IO[bytes] | _GitFile, size: int | None = None
  456. ) -> tuple[bytes | Any, int]:
  457. """Load contents from a file, preferring mmap when possible.
  458. Args:
  459. f: File-like object to load
  460. size: Expected size, or None to determine from file
  461. Returns: Tuple of (contents, size)
  462. """
  463. try:
  464. fd = f.fileno()
  465. except (UnsupportedOperation, AttributeError):
  466. fd = None
  467. # Attempt to use mmap if possible
  468. if fd is not None:
  469. if size is None:
  470. size = os.fstat(fd).st_size
  471. if has_mmap:
  472. try:
  473. contents = mmap.mmap(fd, size, access=mmap.ACCESS_READ)
  474. except (OSError, ValueError):
  475. # Can't mmap - perhaps a socket or invalid file descriptor
  476. pass
  477. else:
  478. return contents, size
  479. contents_bytes = f.read()
  480. size = len(contents_bytes)
  481. return contents_bytes, size
  482. def load_pack_index_file(
  483. path: str | os.PathLike[str], f: IO[bytes] | _GitFile
  484. object_format: ObjectFormat | = None,
  485. ) -> "PackIndex":
  486. """Load an index file from a file-like object.
  487. Args:
  488. path: Path for the index file
  489. f: File-like object
  490. object_format: Hash algorithm used by the repository
  491. Returns: A PackIndex loaded from the given file
  492. """
  493. contents, size = _load_file_contents(f)
  494. if contents[:4] == b"\377tOc":
  495. version = struct.unpack(b">L", contents[4:8])[0]
  496. if version == 2:
  497. return PackIndex2(
  498. path,
  499. file=f,
  500. contents=contents,
  501. size=size,
  502. object_format=object_format,
  503. )
  504. elif version == 3:
  505. return PackIndex3(path, file=f, contents=contents, size=size)
  506. else:
  507. raise KeyError(f"Unknown pack index format {version}")
  508. else:
  509. return PackIndex1(
  510. path, file=f, contents=contents, size=size, object_format=object_format
  511. )
  512. def bisect_find_sha(
  513. start: int, end: int, sha: bytes, unpack_name: Callable[[int], bytes]
  514. ) -> int | None:
  515. """Find a SHA in a data blob with sorted SHAs.
  516. Args:
  517. start: Start index of range to search
  518. end: End index of range to search
  519. sha: Sha to find
  520. unpack_name: Callback to retrieve SHA by index
  521. Returns: Index of the SHA, or None if it wasn't found
  522. """
  523. assert start <= end
  524. while start <= end:
  525. i = (start + end) // 2
  526. file_sha = unpack_name(i)
  527. if file_sha < sha:
  528. start = i + 1
  529. elif file_sha > sha:
  530. end = i - 1
  531. else:
  532. return i
  533. return None
  534. PackIndexEntry = tuple[RawObjectID, int, int | None]
  535. class PackIndex:
  536. """An index in to a packfile.
  537. Given a sha id of an object a pack index can tell you the location in the
  538. packfile of that object if it has it.
  539. """
  540. # Default to SHA-1 for backward compatibility
  541. object_format = 1
  542. hash_size = 20
  543. def __eq__(self, other: object) -> bool:
  544. """Check equality with another PackIndex."""
  545. if not isinstance(other, PackIndex):
  546. return False
  547. for (name1, _, _), (name2, _, _) in zip(
  548. self.iterentries(), other.iterentries()
  549. ):
  550. if name1 != name2:
  551. return False
  552. return True
  553. def __ne__(self, other: object) -> bool:
  554. """Check if this pack index is not equal to another."""
  555. return not self.__eq__(other)
  556. def __len__(self) -> int:
  557. """Return the number of entries in this pack index."""
  558. raise NotImplementedError(self.__len__)
  559. def __iter__(self) -> Iterator[ObjectID]:
  560. """Iterate over the SHAs in this pack."""
  561. return map(lambda sha: sha_to_hex(RawObjectID(sha)), self._itersha())
  562. def iterentries(self) -> Iterator[PackIndexEntry]:
  563. """Iterate over the entries in this pack index.
  564. Returns: iterator over tuples with object name, offset in packfile and
  565. crc32 checksum.
  566. """
  567. raise NotImplementedError(self.iterentries)
  568. def get_pack_checksum(self) -> bytes | None:
  569. """Return the SHA1 checksum stored for the corresponding packfile.
  570. Returns: 20-byte binary digest, or None if not available
  571. """
  572. raise NotImplementedError(self.get_pack_checksum)
  573. @replace_me(since="0.21.0", remove_in="0.23.0")
  574. def object_index(self, sha: ObjectID | RawObjectID) -> int:
  575. """Return the index for the given SHA.
  576. Args:
  577. sha: SHA-1 hash
  578. Returns:
  579. Index position
  580. """
  581. return self.object_offset(sha)
  582. def object_offset(self, sha: ObjectID | RawObjectID) -> int:
  583. """Return the offset in to the corresponding packfile for the object.
  584. Given the name of an object it will return the offset that object
  585. lives at within the corresponding pack file. If the pack file doesn't
  586. have the object then None will be returned.
  587. """
  588. raise NotImplementedError(self.object_offset)
  589. def object_sha1(self, index: int) -> bytes:
  590. """Return the SHA1 corresponding to the index in the pack file."""
  591. for name, offset, _crc32 in self.iterentries():
  592. if offset == index:
  593. return name
  594. else:
  595. raise KeyError(index)
  596. def _object_offset(self, sha: bytes) -> int:
  597. """See object_offset.
  598. Args:
  599. sha: A *binary* SHA string. (20 characters long)_
  600. """
  601. raise NotImplementedError(self._object_offset)
  602. def objects_sha1(self) -> bytes:
  603. """Return the hex SHA1 over all the shas of all objects in this pack.
  604. Note: This is used for the filename of the pack.
  605. """
  606. return iter_sha1(self._itersha())
  607. def _itersha(self) -> Iterator[bytes]:
  608. """Yield all the SHA1's of the objects in the index, sorted."""
  609. raise NotImplementedError(self._itersha)
  610. def iter_prefix(self, prefix: bytes) -> Iterator[RawObjectID]:
  611. """Iterate over all SHA1s with the given prefix.
  612. Args:
  613. prefix: Binary prefix to match
  614. Returns: Iterator of matching SHA1s
  615. """
  616. # Default implementation for PackIndex classes that don't override
  617. for sha, _, _ in self.iterentries():
  618. if sha.startswith(prefix):
  619. yield RawObjectID(sha)
  620. def close(self) -> None:
  621. """Close any open files."""
  622. def check(self) -> None:
  623. """Check the consistency of this pack index."""
  624. class MemoryPackIndex(PackIndex):
  625. """Pack index that is stored entirely in memory."""
  626. def __init__(
  627. self,
  628. entries: list[PackIndexEntry],
  629. pack_checksum: bytes | None = None,
  630. ) -> None:
  631. """Create a new MemoryPackIndex.
  632. Args:
  633. entries: Sequence of name, idx, crc32 (sorted)
  634. pack_checksum: Optional pack checksum
  635. """
  636. self._by_sha = {}
  637. self._by_offset = {}
  638. for name, offset, _crc32 in entries:
  639. self._by_sha[name] = offset
  640. self._by_offset[offset] = name
  641. self._entries = entries
  642. self._pack_checksum = pack_checksum
  643. def get_pack_checksum(self) -> bytes | None:
  644. """Return the SHA checksum stored for the corresponding packfile."""
  645. return self._pack_checksum
  646. def __len__(self) -> int:
  647. """Return the number of entries in this pack index."""
  648. return len(self._entries)
  649. def object_offset(self, sha: ObjectID | RawObjectID) -> int:
  650. """Return the offset for the given SHA.
  651. Args:
  652. sha: SHA to look up (binary or hex)
  653. Returns: Offset in the pack file
  654. """
  655. if len(sha) in (40, 64): # Hex string (SHA1 or SHA256)
  656. sha = hex_to_sha(cast(ObjectID, sha))
  657. return self._by_sha[cast(RawObjectID, sha)]
  658. def object_sha1(self, offset: int) -> bytes:
  659. """Return the SHA1 for the object at the given offset."""
  660. return self._by_offset[offset]
  661. def _itersha(self) -> Iterator[bytes]:
  662. """Iterate over all SHA1s in the index."""
  663. return iter(self._by_sha)
  664. def iterentries(self) -> Iterator[PackIndexEntry]:
  665. """Iterate over all index entries."""
  666. return iter(self._entries)
  667. @classmethod
  668. def for_pack(cls, pack_data: "PackData") -> "MemoryPackIndex":
  669. """Create a MemoryPackIndex from a PackData object."""
  670. return MemoryPackIndex(
  671. list(pack_data.sorted_entries()), pack_data.get_stored_checksum()
  672. )
  673. @classmethod
  674. def clone(cls, other_index: "PackIndex") -> "MemoryPackIndex":
  675. """Create a copy of another PackIndex in memory."""
  676. return cls(list(other_index.iterentries()), other_index.get_pack_checksum())
  677. class FilePackIndex(PackIndex):
  678. """Pack index that is based on a file.
  679. To do the loop it opens the file, and indexes first 256 4 byte groups
  680. with the first byte of the sha id. The value in the four byte group indexed
  681. is the end of the group that shares the same starting byte. Subtract one
  682. from the starting byte and index again to find the start of the group.
  683. The values are sorted by sha id within the group, so do the math to find
  684. the start and end offset and then bisect in to find if the value is
  685. present.
  686. """
  687. _fan_out_table: list[int]
  688. _file: IO[bytes] | _GitFile
  689. def __init__(
  690. self,
  691. filename: str | os.PathLike[str],
  692. file: IO[bytes] | _GitFile | None = None,
  693. contents: "bytes | mmap.mmap | None" = None,
  694. size: int | None = None,
  695. ) -> None:
  696. """Create a pack index object.
  697. Provide it with the name of the index file to consider, and it will map
  698. it whenever required.
  699. """
  700. self._filename = filename
  701. # Take the size now, so it can be checked each time we map the file to
  702. # ensure that it hasn't changed.
  703. if file is None:
  704. self._file = GitFile(filename, "rb")
  705. else:
  706. self._file = file
  707. if contents is None:
  708. self._contents, self._size = _load_file_contents(self._file, size)
  709. else:
  710. self._contents = contents
  711. self._size = size if size is not None else len(contents)
  712. @property
  713. def path(self) -> str:
  714. """Return the path to this index file."""
  715. return os.fspath(self._filename)
  716. def __eq__(self, other: object) -> bool:
  717. """Check equality with another FilePackIndex."""
  718. # Quick optimization:
  719. if (
  720. isinstance(other, FilePackIndex)
  721. and self._fan_out_table != other._fan_out_table
  722. ):
  723. return False
  724. return super().__eq__(other)
  725. def close(self) -> None:
  726. """Close the underlying file and any mmap."""
  727. self._file.close()
  728. close_fn = getattr(self._contents, "close", None)
  729. if close_fn is not None:
  730. close_fn()
  731. def __len__(self) -> int:
  732. """Return the number of entries in this pack index."""
  733. return self._fan_out_table[-1]
  734. def _unpack_entry(self, i: int) -> PackIndexEntry:
  735. """Unpack the i-th entry in the index file.
  736. Returns: Tuple with object name (SHA), offset in pack file and CRC32
  737. checksum (if known).
  738. """
  739. raise NotImplementedError(self._unpack_entry)
  740. def _unpack_name(self, i: int) -> bytes:
  741. """Unpack the i-th name from the index file."""
  742. raise NotImplementedError(self._unpack_name)
  743. def _unpack_offset(self, i: int) -> int:
  744. """Unpack the i-th object offset from the index file."""
  745. raise NotImplementedError(self._unpack_offset)
  746. def _unpack_crc32_checksum(self, i: int) -> int | None:
  747. """Unpack the crc32 checksum for the ith object from the index file."""
  748. raise NotImplementedError(self._unpack_crc32_checksum)
  749. def _itersha(self) -> Iterator[bytes]:
  750. """Iterate over all SHA1s in the index."""
  751. for i in range(len(self)):
  752. yield self._unpack_name(i)
  753. def iterentries(self) -> Iterator[PackIndexEntry]:
  754. """Iterate over the entries in this pack index.
  755. Returns: iterator over tuples with object name, offset in packfile and
  756. crc32 checksum.
  757. """
  758. for i in range(len(self)):
  759. yield self._unpack_entry(i)
  760. def _read_fan_out_table(self, start_offset: int) -> list[int]:
  761. """Read the fan-out table from the index.
  762. The fan-out table contains 256 entries mapping first byte values
  763. to the number of objects with SHA1s less than or equal to that byte.
  764. Args:
  765. start_offset: Offset in the file where the fan-out table starts
  766. Returns: List of 256 integers
  767. """
  768. ret = []
  769. for i in range(0x100):
  770. fanout_entry = self._contents[
  771. start_offset + i * 4 : start_offset + (i + 1) * 4
  772. ]
  773. ret.append(struct.unpack(">L", fanout_entry)[0])
  774. return ret
  775. def check(self) -> None:
  776. """Check that the stored checksum matches the actual checksum."""
  777. actual = self.calculate_checksum()
  778. stored = self.get_stored_checksum()
  779. if actual != stored:
  780. raise ChecksumMismatch(stored, actual)
  781. def calculate_checksum(self) -> bytes:
  782. """Calculate the SHA1 checksum over this pack index.
  783. Returns: This is a 20-byte binary digest
  784. """
  785. return sha1(self._contents[:-20]).digest()
  786. def get_pack_checksum(self) -> bytes:
  787. """Return the SHA1 checksum stored for the corresponding packfile.
  788. Returns: 20-byte binary digest
  789. """
  790. return bytes(self._contents[-40:-20])
  791. def get_stored_checksum(self) -> bytes:
  792. """Return the SHA1 checksum stored for this index.
  793. Returns: 20-byte binary digest
  794. """
  795. return bytes(self._contents[-20:])
  796. def object_offset(self, sha: ObjectID | RawObjectID) -> int:
  797. """Return the offset in to the corresponding packfile for the object.
  798. Given the name of an object it will return the offset that object
  799. lives at within the corresponding pack file. If the pack file doesn't
  800. have the object then None will be returned.
  801. """
  802. if len(sha) == 40:
  803. sha = hex_to_sha(cast(ObjectID, sha))
  804. try:
  805. return self._object_offset(sha)
  806. except ValueError as exc:
  807. closed = getattr(self._contents, "closed", None)
  808. if closed in (None, True):
  809. raise PackFileDisappeared(self) from exc
  810. raise
  811. def _object_offset(self, sha: bytes) -> int:
  812. """See object_offset.
  813. Args:
  814. sha: A *binary* SHA string. (20 characters long)_
  815. """
  816. hash_size = getattr(self, "hash_size", 20) # Default to SHA1 for v1
  817. assert len(sha) == hash_size
  818. idx = ord(sha[:1])
  819. if idx == 0:
  820. start = 0
  821. else:
  822. start = self._fan_out_table[idx - 1]
  823. end = self._fan_out_table[idx]
  824. i = bisect_find_sha(start, end, sha, self._unpack_name)
  825. if i is None:
  826. raise KeyError(sha)
  827. return self._unpack_offset(i)
  828. def iter_prefix(self, prefix: bytes) -> Iterator[RawObjectID]:
  829. """Iterate over all SHA1s with the given prefix."""
  830. start = ord(prefix[:1])
  831. if start == 0:
  832. start = 0
  833. else:
  834. start = self._fan_out_table[start - 1]
  835. end = ord(prefix[:1]) + 1
  836. if end == 0x100:
  837. end = len(self)
  838. else:
  839. end = self._fan_out_table[end]
  840. assert start <= end
  841. started = False
  842. for i in range(start, end):
  843. name: bytes = self._unpack_name(i)
  844. if name.startswith(prefix):
  845. yield RawObjectID(name)
  846. started = True
  847. elif started:
  848. break
  849. class PackIndex1(FilePackIndex):
  850. """Version 1 Pack Index file."""
  851. def __init__(
  852. self,
  853. filename: str | os.PathLike[str],
  854. file: IO[bytes] | _GitFile | None = None,
  855. contents: bytes | None = None,
  856. size: int | None = None,
  857. object_format: ObjectFormat | None = None,
  858. ) -> None:
  859. """Initialize a version 1 pack index.
  860. Args:
  861. filename: Path to the index file
  862. file: Optional file object
  863. contents: Optional mmap'd contents
  864. size: Optional size of the index
  865. hash_algorithm: Hash algorithm used by the repository
  866. """
  867. super().__init__(filename, file, contents, size)
  868. self.version = 1
  869. self._fan_out_table = self._read_fan_out_table(0)
  870. # Use provided hash algorithm if available, otherwise default to SHA1
  871. if object_format:
  872. self.hash_size = object_format.oid_length
  873. else:
  874. self.hash_size = 20 # Default to SHA1
  875. self._entry_size = 4 + self.hash_size
  876. def _unpack_entry(self, i: int) -> tuple[RawObjectID, int, None]:
  877. base_offset = (0x100 * 4) + (i * self._entry_size)
  878. if self.hash_size == 20:
  879. (offset, name) = unpack_from(">L20s", self._contents, base_offset)
  880. else: # SHA256
  881. offset = unpack_from(">L", self._contents, base_offset)[0]
  882. name = self._contents[base_offset + 4 : base_offset + 4 + self.hash_size]
  883. return (RawObjectID(name), offset, None)
  884. def _unpack_name(self, i: int) -> bytes:
  885. offset = (0x100 * 4) + (i * self._entry_size) + 4
  886. return self._contents[offset : offset + self.hash_size]
  887. def _unpack_offset(self, i: int) -> int:
  888. offset = (0x100 * 4) + (i * self._entry_size)
  889. return unpack_from(">L", self._contents, offset)[0]
  890. def _unpack_crc32_checksum(self, i: int) -> None:
  891. # Not stored in v1 index files
  892. return None
  893. class PackIndex2(FilePackIndex):
  894. """Version 2 Pack Index file."""
  895. def __init__(
  896. self,
  897. filename: str | os.PathLike[str],
  898. file: IO[bytes] | _GitFile | None = None,
  899. contents: bytes | None = None,
  900. size: int | None = None,
  901. object_format: ObjectFormat | None = None,
  902. ) -> None:
  903. """Initialize a version 2 pack index.
  904. Args:
  905. filename: Path to the index file
  906. file: Optional file object
  907. contents: Optional mmap'd contents
  908. size: Optional size of the index
  909. hash_algorithm: Hash algorithm used by the repository
  910. """
  911. super().__init__(filename, file, contents, size)
  912. if self._contents[:4] != b"\377tOc":
  913. raise AssertionError("Not a v2 pack index file")
  914. (self.version,) = unpack_from(b">L", self._contents, 4)
  915. if self.version != 2:
  916. raise AssertionError(f"Version was {self.version}")
  917. self._fan_out_table = self._read_fan_out_table(8)
  918. # Use provided hash algorithm if available, otherwise default to SHA1
  919. if object_format:
  920. self.hash_size = object_format.oid_length
  921. else:
  922. self.hash_size = 20 # Default to SHA1
  923. self._name_table_offset = 8 + 0x100 * 4
  924. self._crc32_table_offset = self._name_table_offset + self.hash_size * len(self)
  925. self._pack_offset_table_offset = self._crc32_table_offset + 4 * len(self)
  926. self._pack_offset_largetable_offset = self._pack_offset_table_offset + 4 * len(
  927. self
  928. )
  929. def _unpack_entry(self, i: int) -> tuple[RawObjectID, int, int]:
  930. return (
  931. RawObjectID(self._unpack_name(i)),
  932. self._unpack_offset(i),
  933. self._unpack_crc32_checksum(i),
  934. )
  935. def _unpack_name(self, i: int) -> bytes:
  936. offset = self._name_table_offset + i * self.hash_size
  937. return self._contents[offset : offset + self.hash_size]
  938. def _unpack_offset(self, i: int) -> int:
  939. offset = self._pack_offset_table_offset + i * 4
  940. offset = unpack_from(">L", self._contents, offset)[0]
  941. if offset & (2**31):
  942. offset = self._pack_offset_largetable_offset + (offset & (2**31 - 1)) * 8
  943. offset = unpack_from(">Q", self._contents, offset)[0]
  944. return offset
  945. def _unpack_crc32_checksum(self, i: int) -> int:
  946. return unpack_from(">L", self._contents, self._crc32_table_offset + i * 4)[0]
  947. def get_pack_checksum(self) -> bytes:
  948. """Return the checksum stored for the corresponding packfile.
  949. Returns: binary digest (always 20 bytes - SHA1)
  950. """
  951. # Pack checksums are always SHA1, even in SHA256 repositories
  952. return bytes(self._contents[-40:-20])
  953. class PackIndex3(FilePackIndex):
  954. """Version 3 Pack Index file.
  955. Supports variable hash sizes for SHA-1 (20 bytes) and SHA-256 (32 bytes).
  956. """
  957. def __init__(
  958. self,
  959. filename: str | os.PathLike[str],
  960. file: IO[bytes] | _GitFile | None = None,
  961. contents: bytes | None = None,
  962. size: int | None = None,
  963. ) -> None:
  964. """Initialize a version 3 pack index.
  965. Args:
  966. filename: Path to the index file
  967. file: Optional file object
  968. contents: Optional mmap'd contents
  969. size: Optional size of the index
  970. """
  971. super().__init__(filename, file, contents, size)
  972. if self._contents[:4] != b"\377tOc":
  973. raise AssertionError("Not a v3 pack index file")
  974. (self.version,) = unpack_from(b">L", self._contents, 4)
  975. if self.version != 3:
  976. raise AssertionError(f"Version was {self.version}")
  977. # Read hash algorithm identifier (1 = SHA-1, 2 = SHA-256)
  978. (self.object_format,) = unpack_from(b">L", self._contents, 8)
  979. if self.object_format == 1:
  980. self.hash_size = 20 # SHA-1
  981. elif self.object_format == 2:
  982. self.hash_size = 32 # SHA-256
  983. else:
  984. raise AssertionError(f"Unknown hash algorithm {self.object_format}")
  985. # Read length of shortened object names
  986. (self.shortened_oid_len,) = unpack_from(b">L", self._contents, 12)
  987. # Calculate offsets based on variable hash size
  988. self._fan_out_table = self._read_fan_out_table(
  989. 16
  990. ) # After header (4 + 4 + 4 + 4)
  991. self._name_table_offset = 16 + 0x100 * 4
  992. self._crc32_table_offset = self._name_table_offset + self.hash_size * len(self)
  993. self._pack_offset_table_offset = self._crc32_table_offset + 4 * len(self)
  994. self._pack_offset_largetable_offset = self._pack_offset_table_offset + 4 * len(
  995. self
  996. )
  997. def _unpack_entry(self, i: int) -> tuple[RawObjectID, int, int]:
  998. return (
  999. RawObjectID(self._unpack_name(i)),
  1000. self._unpack_offset(i),
  1001. self._unpack_crc32_checksum(i),
  1002. )
  1003. def _unpack_name(self, i: int) -> bytes:
  1004. offset = self._name_table_offset + i * self.hash_size
  1005. return self._contents[offset : offset + self.hash_size]
  1006. def _unpack_offset(self, i: int) -> int:
  1007. offset_pos = self._pack_offset_table_offset + i * 4
  1008. offset = unpack_from(">L", self._contents, offset_pos)[0]
  1009. assert isinstance(offset, int)
  1010. if offset & (2**31):
  1011. large_offset_pos = (
  1012. self._pack_offset_largetable_offset + (offset & (2**31 - 1)) * 8
  1013. )
  1014. offset = unpack_from(">Q", self._contents, large_offset_pos)[0]
  1015. assert isinstance(offset, int)
  1016. return offset
  1017. def _unpack_crc32_checksum(self, i: int) -> int:
  1018. result = unpack_from(">L", self._contents, self._crc32_table_offset + i * 4)[0]
  1019. assert isinstance(result, int)
  1020. return result
  1021. def read_pack_header(read: Callable[[int], bytes]) -> tuple[int, int]:
  1022. """Read the header of a pack file.
  1023. Args:
  1024. read: Read function
  1025. Returns: Tuple of (pack version, number of objects). If no data is
  1026. available to read, returns (None, None).
  1027. """
  1028. header = read(12)
  1029. if not header:
  1030. raise AssertionError("file too short to contain pack")
  1031. if header[:4] != b"PACK":
  1032. raise AssertionError(f"Invalid pack header {header!r}")
  1033. (version,) = unpack_from(b">L", header, 4)
  1034. if version not in (2, 3):
  1035. raise AssertionError(f"Version was {version}")
  1036. (num_objects,) = unpack_from(b">L", header, 8)
  1037. return (version, num_objects)
  1038. def chunks_length(chunks: bytes | Iterable[bytes]) -> int:
  1039. """Get the total length of a sequence of chunks.
  1040. Args:
  1041. chunks: Either a single bytes object or an iterable of bytes
  1042. Returns: Total length in bytes
  1043. """
  1044. if isinstance(chunks, bytes):
  1045. return len(chunks)
  1046. else:
  1047. return sum(map(len, chunks))
  1048. def unpack_object(
  1049. read_all: Callable[[int], bytes],
  1050. read_some: Callable[[int], bytes] | None = None,
  1051. compute_crc32: bool = False,
  1052. include_comp: bool = False,
  1053. zlib_bufsize: int = _ZLIB_BUFSIZE,
  1054. ) -> tuple[UnpackedObject, bytes]:
  1055. """Unpack a Git object.
  1056. Args:
  1057. read_all: Read function that blocks until the number of requested
  1058. bytes are read.
  1059. read_some: Read function that returns at least one byte, but may not
  1060. return the number of bytes requested.
  1061. compute_crc32: If True, compute the CRC32 of the compressed data. If
  1062. False, the returned CRC32 will be None.
  1063. include_comp: If True, include compressed data in the result.
  1064. zlib_bufsize: An optional buffer size for zlib operations.
  1065. Returns: A tuple of (unpacked, unused), where unused is the unused data
  1066. leftover from decompression, and unpacked in an UnpackedObject with
  1067. the following attrs set:
  1068. * obj_chunks (for non-delta types)
  1069. * pack_type_num
  1070. * delta_base (for delta types)
  1071. * comp_chunks (if include_comp is True)
  1072. * decomp_chunks
  1073. * decomp_len
  1074. * crc32 (if compute_crc32 is True)
  1075. """
  1076. if read_some is None:
  1077. read_some = read_all
  1078. if compute_crc32:
  1079. crc32 = 0
  1080. else:
  1081. crc32 = None
  1082. raw, crc32 = take_msb_bytes(read_all, crc32=crc32)
  1083. type_num = (raw[0] >> 4) & 0x07
  1084. size = raw[0] & 0x0F
  1085. for i, byte in enumerate(raw[1:]):
  1086. size += (byte & 0x7F) << ((i * 7) + 4)
  1087. delta_base: int | bytes | None
  1088. raw_base = len(raw)
  1089. if type_num == OFS_DELTA:
  1090. raw, crc32 = take_msb_bytes(read_all, crc32=crc32)
  1091. raw_base += len(raw)
  1092. if raw[-1] & 0x80:
  1093. raise AssertionError
  1094. delta_base_offset = raw[0] & 0x7F
  1095. for byte in raw[1:]:
  1096. delta_base_offset += 1
  1097. delta_base_offset <<= 7
  1098. delta_base_offset += byte & 0x7F
  1099. delta_base = delta_base_offset
  1100. elif type_num == REF_DELTA:
  1101. delta_base_obj = read_all(20)
  1102. if crc32 is not None:
  1103. crc32 = binascii.crc32(delta_base_obj, crc32)
  1104. delta_base = delta_base_obj
  1105. raw_base += 20
  1106. else:
  1107. delta_base = None
  1108. unpacked = UnpackedObject(
  1109. type_num, delta_base=delta_base, decomp_len=size, crc32=crc32
  1110. )
  1111. unused = read_zlib_chunks(
  1112. read_some,
  1113. unpacked,
  1114. buffer_size=zlib_bufsize,
  1115. include_comp=include_comp,
  1116. )
  1117. return unpacked, unused
  1118. def _compute_object_size(value: tuple[int, Any]) -> int:
  1119. """Compute the size of a unresolved object for use with LRUSizeCache."""
  1120. (num, obj) = value
  1121. if num in DELTA_TYPES:
  1122. return chunks_length(obj[1])
  1123. return chunks_length(obj)
  1124. class PackStreamReader:
  1125. """Class to read a pack stream.
  1126. The pack is read from a ReceivableProtocol using read() or recv() as
  1127. appropriate.
  1128. """
  1129. def __init__(
  1130. self,
  1131. read_all: Callable[[int], bytes],
  1132. read_some: Callable[[int], bytes] | None = None,
  1133. zlib_bufsize: int = _ZLIB_BUFSIZE,
  1134. ) -> None:
  1135. """Initialize pack stream reader.
  1136. Args:
  1137. read_all: Function to read all requested bytes
  1138. read_some: Function to read some bytes (optional)
  1139. zlib_bufsize: Buffer size for zlib decompression
  1140. """
  1141. self.read_all = read_all
  1142. if read_some is None:
  1143. self.read_some = read_all
  1144. else:
  1145. self.read_some = read_some
  1146. self.sha = sha1()
  1147. self._offset = 0
  1148. self._rbuf = BytesIO()
  1149. # trailer is a deque to avoid memory allocation on small reads
  1150. self._trailer: deque[int] = deque()
  1151. self._zlib_bufsize = zlib_bufsize
  1152. def _read(self, read: Callable[[int], bytes], size: int) -> bytes:
  1153. """Read up to size bytes using the given callback.
  1154. As a side effect, update the verifier's hash (excluding the last 20
  1155. bytes read).
  1156. Args:
  1157. read: The read callback to read from.
  1158. size: The maximum number of bytes to read; the particular
  1159. behavior is callback-specific.
  1160. Returns: Bytes read
  1161. """
  1162. data = read(size)
  1163. # maintain a trailer of the last 20 bytes we've read
  1164. n = len(data)
  1165. self._offset += n
  1166. tn = len(self._trailer)
  1167. if n >= 20:
  1168. to_pop = tn
  1169. to_add = 20
  1170. else:
  1171. to_pop = max(n + tn - 20, 0)
  1172. to_add = n
  1173. self.sha.update(
  1174. bytes(bytearray([self._trailer.popleft() for _ in range(to_pop)]))
  1175. )
  1176. self._trailer.extend(data[-to_add:])
  1177. # hash everything but the trailer
  1178. self.sha.update(data[:-to_add])
  1179. return data
  1180. def _buf_len(self) -> int:
  1181. buf = self._rbuf
  1182. start = buf.tell()
  1183. buf.seek(0, SEEK_END)
  1184. end = buf.tell()
  1185. buf.seek(start)
  1186. return end - start
  1187. @property
  1188. def offset(self) -> int:
  1189. """Return current offset in the stream."""
  1190. return self._offset - self._buf_len()
  1191. def read(self, size: int) -> bytes:
  1192. """Read, blocking until size bytes are read."""
  1193. buf_len = self._buf_len()
  1194. if buf_len >= size:
  1195. return self._rbuf.read(size)
  1196. buf_data = self._rbuf.read()
  1197. self._rbuf = BytesIO()
  1198. return buf_data + self._read(self.read_all, size - buf_len)
  1199. def recv(self, size: int) -> bytes:
  1200. """Read up to size bytes, blocking until one byte is read."""
  1201. buf_len = self._buf_len()
  1202. if buf_len:
  1203. data = self._rbuf.read(size)
  1204. if size >= buf_len:
  1205. self._rbuf = BytesIO()
  1206. return data
  1207. return self._read(self.read_some, size)
  1208. def __len__(self) -> int:
  1209. """Return the number of objects in this pack."""
  1210. return self._num_objects
  1211. def read_objects(self, compute_crc32: bool = False) -> Iterator[UnpackedObject]:
  1212. """Read the objects in this pack file.
  1213. Args:
  1214. compute_crc32: If True, compute the CRC32 of the compressed
  1215. data. If False, the returned CRC32 will be None.
  1216. Returns: Iterator over UnpackedObjects with the following members set:
  1217. offset
  1218. obj_type_num
  1219. obj_chunks (for non-delta types)
  1220. delta_base (for delta types)
  1221. decomp_chunks
  1222. decomp_len
  1223. crc32 (if compute_crc32 is True)
  1224. Raises:
  1225. ChecksumMismatch: if the checksum of the pack contents does not
  1226. match the checksum in the pack trailer.
  1227. zlib.error: if an error occurred during zlib decompression.
  1228. IOError: if an error occurred writing to the output file.
  1229. """
  1230. _pack_version, self._num_objects = read_pack_header(self.read)
  1231. for _ in range(self._num_objects):
  1232. offset = self.offset
  1233. unpacked, unused = unpack_object(
  1234. self.read,
  1235. read_some=self.recv,
  1236. compute_crc32=compute_crc32,
  1237. zlib_bufsize=self._zlib_bufsize,
  1238. )
  1239. unpacked.offset = offset
  1240. # prepend any unused data to current read buffer
  1241. buf = BytesIO()
  1242. buf.write(unused)
  1243. buf.write(self._rbuf.read())
  1244. buf.seek(0)
  1245. self._rbuf = buf
  1246. yield unpacked
  1247. if self._buf_len() < 20:
  1248. # If the read buffer is full, then the last read() got the whole
  1249. # trailer off the wire. If not, it means there is still some of the
  1250. # trailer to read. We need to read() all 20 bytes; N come from the
  1251. # read buffer and (20 - N) come from the wire.
  1252. self.read(20)
  1253. pack_sha = bytearray(self._trailer)
  1254. if pack_sha != self.sha.digest():
  1255. raise ChecksumMismatch(
  1256. sha_to_hex(RawObjectID(bytes(pack_sha))), self.sha.hexdigest()
  1257. )
  1258. class PackStreamCopier(PackStreamReader):
  1259. """Class to verify a pack stream as it is being read.
  1260. The pack is read from a ReceivableProtocol using read() or recv() as
  1261. appropriate and written out to the given file-like object.
  1262. """
  1263. def __init__(
  1264. self,
  1265. read_all: Callable[[int], bytes],
  1266. read_some: Callable[[int], bytes] | None,
  1267. outfile: IO[bytes],
  1268. delta_iter: "DeltaChainIterator[UnpackedObject] | None" = None,
  1269. ) -> None:
  1270. """Initialize the copier.
  1271. Args:
  1272. read_all: Read function that blocks until the number of
  1273. requested bytes are read.
  1274. read_some: Read function that returns at least one byte, but may
  1275. not return the number of bytes requested.
  1276. outfile: File-like object to write output through.
  1277. delta_iter: Optional DeltaChainIterator to record deltas as we
  1278. read them.
  1279. """
  1280. super().__init__(read_all, read_some=read_some)
  1281. self.outfile = outfile
  1282. self._delta_iter = delta_iter
  1283. def _read(self, read: Callable[[int], bytes], size: int) -> bytes:
  1284. """Read data from the read callback and write it to the file."""
  1285. data = super()._read(read, size)
  1286. self.outfile.write(data)
  1287. return data
  1288. def verify(self, progress: Callable[..., None] | None = None) -> None:
  1289. """Verify a pack stream and write it to the output file.
  1290. See PackStreamReader.iterobjects for a list of exceptions this may
  1291. throw.
  1292. """
  1293. i = 0 # default count of entries if read_objects() is empty
  1294. for i, unpacked in enumerate(self.read_objects()):
  1295. if self._delta_iter:
  1296. self._delta_iter.record(unpacked)
  1297. if progress is not None:
  1298. progress(f"copying pack entries: {i}/{len(self)}\r".encode("ascii"))
  1299. if progress is not None:
  1300. progress(f"copied {i} pack entries\n".encode("ascii"))
  1301. def obj_sha(type: int, chunks: bytes | Iterable[bytes]) -> bytes:
  1302. """Compute the SHA for a numeric type and object chunks."""
  1303. sha = sha1()
  1304. sha.update(object_header(type, chunks_length(chunks)))
  1305. if isinstance(chunks, bytes):
  1306. sha.update(chunks)
  1307. else:
  1308. for chunk in chunks:
  1309. sha.update(chunk)
  1310. return sha.digest()
  1311. def compute_file_sha(
  1312. f: IO[bytes], start_ofs: int = 0, end_ofs: int = 0, buffer_size: int = 1 << 16
  1313. ) -> "HashObject":
  1314. """Hash a portion of a file into a new SHA.
  1315. Args:
  1316. f: A file-like object to read from that supports seek().
  1317. start_ofs: The offset in the file to start reading at.
  1318. end_ofs: The offset in the file to end reading at, relative to the
  1319. end of the file.
  1320. buffer_size: A buffer size for reading.
  1321. Returns: A new SHA object updated with data read from the file.
  1322. """
  1323. sha = sha1()
  1324. f.seek(0, SEEK_END)
  1325. length = f.tell()
  1326. if (end_ofs < 0 and length + end_ofs < start_ofs) or end_ofs > length:
  1327. raise AssertionError(
  1328. f"Attempt to read beyond file length. start_ofs: {start_ofs}, end_ofs: {end_ofs}, file length: {length}"
  1329. )
  1330. todo = length + end_ofs - start_ofs
  1331. f.seek(start_ofs)
  1332. while todo:
  1333. data = f.read(min(todo, buffer_size))
  1334. sha.update(data)
  1335. todo -= len(data)
  1336. return sha
  1337. class PackData:
  1338. """The data contained in a packfile.
  1339. Pack files can be accessed both sequentially for exploding a pack, and
  1340. directly with the help of an index to retrieve a specific object.
  1341. The objects within are either complete or a delta against another.
  1342. The header is variable length. If the MSB of each byte is set then it
  1343. indicates that the subsequent byte is still part of the header.
  1344. For the first byte the next MS bits are the type, which tells you the type
  1345. of object, and whether it is a delta. The LS byte is the lowest bits of the
  1346. size. For each subsequent byte the LS 7 bits are the next MS bits of the
  1347. size, i.e. the last byte of the header contains the MS bits of the size.
  1348. For the complete objects the data is stored as zlib deflated data.
  1349. The size in the header is the uncompressed object size, so to uncompress
  1350. you need to just keep feeding data to zlib until you get an object back,
  1351. or it errors on bad data. This is done here by just giving the complete
  1352. buffer from the start of the deflated object on. This is bad, but until I
  1353. get mmap sorted out it will have to do.
  1354. Currently there are no integrity checks done. Also no attempt is made to
  1355. try and detect the delta case, or a request for an object at the wrong
  1356. position. It will all just throw a zlib or KeyError.
  1357. """
  1358. def __init__(
  1359. self,
  1360. filename: str | os.PathLike[str],
  1361. file: IO[bytes] | None = None,
  1362. size: int | None = None,
  1363. *,
  1364. delta_window_size: int | None = None,
  1365. window_memory: int | None = None,
  1366. delta_cache_size: int | None = None,
  1367. depth: int | None = None,
  1368. threads: int | None = None,
  1369. big_file_threshold: int | None = None,
  1370. ) -> None:
  1371. """Create a PackData object representing the pack in the given filename.
  1372. The file must exist and stay readable until the object is disposed of.
  1373. It must also stay the same size. It will be mapped whenever needed.
  1374. Currently there is a restriction on the size of the pack as the python
  1375. mmap implementation is flawed.
  1376. """
  1377. self._filename = filename
  1378. self._size = size
  1379. self._header_size = 12
  1380. self.delta_window_size = delta_window_size
  1381. self.window_memory = window_memory
  1382. self.delta_cache_size = delta_cache_size
  1383. self.depth = depth
  1384. self.threads = threads
  1385. self.big_file_threshold = big_file_threshold
  1386. self._file: IO[bytes]
  1387. if file is None:
  1388. self._file = GitFile(self._filename, "rb")
  1389. else:
  1390. self._file = file
  1391. (_version, self._num_objects) = read_pack_header(self._file.read)
  1392. # Use delta_cache_size config if available, otherwise default
  1393. cache_size = delta_cache_size or (1024 * 1024 * 20)
  1394. self._offset_cache = LRUSizeCache[int, tuple[int, OldUnpackedObject]](
  1395. cache_size, compute_size=_compute_object_size
  1396. )
  1397. @property
  1398. def filename(self) -> str:
  1399. """Get the filename of the pack file.
  1400. Returns:
  1401. Base filename without directory path
  1402. """
  1403. return os.path.basename(self._filename)
  1404. @property
  1405. def path(self) -> str | os.PathLike[str]:
  1406. """Get the full path of the pack file.
  1407. Returns:
  1408. Full path to the pack file
  1409. """
  1410. return self._filename
  1411. @classmethod
  1412. def from_file(cls, file: IO[bytes], size: int | None = None) -> "PackData":
  1413. """Create a PackData object from an open file.
  1414. Args:
  1415. file: Open file object
  1416. size: Optional file size
  1417. Returns:
  1418. PackData instance
  1419. """
  1420. return cls(str(file), file=file, size=size)
  1421. @classmethod
  1422. def from_path(cls, path: str | os.PathLike[str]) -> "PackData":
  1423. """Create a PackData object from a file path.
  1424. Args:
  1425. path: Path to the pack file
  1426. Returns:
  1427. PackData instance
  1428. """
  1429. return cls(filename=path)
  1430. def close(self) -> None:
  1431. """Close the underlying pack file."""
  1432. self._file.close()
  1433. def __enter__(self) -> "PackData":
  1434. """Enter context manager."""
  1435. return self
  1436. def __exit__(
  1437. self,
  1438. exc_type: type | None,
  1439. exc_val: BaseException | None,
  1440. exc_tb: TracebackType | None,
  1441. ) -> None:
  1442. """Exit context manager."""
  1443. self.close()
  1444. def __eq__(self, other: object) -> bool:
  1445. """Check equality with another object."""
  1446. if isinstance(other, PackData):
  1447. return self.get_stored_checksum() == other.get_stored_checksum()
  1448. return False
  1449. def _get_size(self) -> int:
  1450. if self._size is not None:
  1451. return self._size
  1452. self._size = os.path.getsize(self._filename)
  1453. if self._size < self._header_size:
  1454. errmsg = f"{self._filename} is too small for a packfile ({self._size} < {self._header_size})"
  1455. raise AssertionError(errmsg)
  1456. return self._size
  1457. def __len__(self) -> int:
  1458. """Returns the number of objects in this pack."""
  1459. return self._num_objects
  1460. def calculate_checksum(self) -> bytes:
  1461. """Calculate the checksum for this pack.
  1462. Returns: 20-byte binary SHA1 digest
  1463. """
  1464. return compute_file_sha(self._file, end_ofs=-20).digest()
  1465. def iter_unpacked(self, *, include_comp: bool = False) -> Iterator[UnpackedObject]:
  1466. """Iterate over unpacked objects in the pack."""
  1467. self._file.seek(self._header_size)
  1468. if self._num_objects is None:
  1469. return
  1470. for _ in range(self._num_objects):
  1471. offset = self._file.tell()
  1472. unpacked, unused = unpack_object(
  1473. self._file.read, compute_crc32=False, include_comp=include_comp
  1474. )
  1475. unpacked.offset = offset
  1476. yield unpacked
  1477. # Back up over unused data.
  1478. self._file.seek(-len(unused), SEEK_CUR)
  1479. def iterentries(
  1480. self,
  1481. progress: Callable[[int, int], None] | None = None,
  1482. resolve_ext_ref: ResolveExtRefFn | None = None,
  1483. ) -> Iterator[PackIndexEntry]:
  1484. """Yield entries summarizing the contents of this pack.
  1485. Args:
  1486. progress: Progress function, called with current and total
  1487. object count.
  1488. resolve_ext_ref: Optional function to resolve external references
  1489. Returns: iterator of tuples with (sha, offset, crc32)
  1490. """
  1491. num_objects = self._num_objects
  1492. indexer = PackIndexer.for_pack_data(self, resolve_ext_ref=resolve_ext_ref)
  1493. for i, result in enumerate(indexer):
  1494. if progress is not None:
  1495. progress(i, num_objects)
  1496. yield result
  1497. def sorted_entries(
  1498. self,
  1499. progress: ProgressFn | None = None,
  1500. resolve_ext_ref: ResolveExtRefFn | None = None,
  1501. ) -> list[tuple[RawObjectID, int, int]]:
  1502. """Return entries in this pack, sorted by SHA.
  1503. Args:
  1504. progress: Progress function, called with current and total
  1505. object count
  1506. resolve_ext_ref: Optional function to resolve external references
  1507. Returns: Iterator of tuples with (sha, offset, crc32)
  1508. """
  1509. return sorted(
  1510. self.iterentries(progress=progress, resolve_ext_ref=resolve_ext_ref) # type: ignore
  1511. )
  1512. def create_index_v1(
  1513. self,
  1514. filename: str,
  1515. progress: Callable[..., None] | None = None,
  1516. resolve_ext_ref: ResolveExtRefFn | None = None,
  1517. ) -> bytes:
  1518. """Create a version 1 file for this data file.
  1519. Args:
  1520. filename: Index filename.
  1521. progress: Progress report function
  1522. resolve_ext_ref: Optional function to resolve external references
  1523. Returns: Checksum of index file
  1524. """
  1525. entries = self.sorted_entries(
  1526. progress=progress, resolve_ext_ref=resolve_ext_ref
  1527. )
  1528. checksum = self.calculate_checksum()
  1529. with GitFile(filename, "wb") as f:
  1530. write_pack_index_v1(
  1531. f,
  1532. entries,
  1533. checksum,
  1534. )
  1535. return checksum
  1536. def create_index_v2(
  1537. self,
  1538. filename: str,
  1539. progress: Callable[..., None] | None = None,
  1540. resolve_ext_ref: ResolveExtRefFn | None = None,
  1541. ) -> bytes:
  1542. """Create a version 2 index file for this data file.
  1543. Args:
  1544. filename: Index filename.
  1545. progress: Progress report function
  1546. resolve_ext_ref: Optional function to resolve external references
  1547. Returns: Checksum of index file
  1548. """
  1549. entries = self.sorted_entries(
  1550. progress=progress, resolve_ext_ref=resolve_ext_ref
  1551. )
  1552. with GitFile(filename, "wb") as f:
  1553. return write_pack_index_v2(f, entries, self.calculate_checksum())
  1554. def create_index_v3(
  1555. self,
  1556. filename: str,
  1557. progress: Callable[..., None] | None = None,
  1558. resolve_ext_ref: ResolveExtRefFn | None = None,
  1559. hash_format: int | None = None,
  1560. ) -> bytes:
  1561. """Create a version 3 index file for this data file.
  1562. Args:
  1563. filename: Index filename.
  1564. progress: Progress report function
  1565. resolve_ext_ref: Function to resolve external references
  1566. hash_format: Hash algorithm identifier (1 = SHA-1, 2 = SHA-256)
  1567. Returns: Checksum of index file
  1568. """
  1569. entries = self.sorted_entries(
  1570. progress=progress, resolve_ext_ref=resolve_ext_ref
  1571. )
  1572. with GitFile(filename, "wb") as f:
  1573. return write_pack_index_v3(
  1574. f, entries, self.calculate_checksum(), hash_format
  1575. )
  1576. def create_index(
  1577. self,
  1578. filename: str,
  1579. progress: Callable[..., None] | None = None,
  1580. version: int = 2,
  1581. resolve_ext_ref: ResolveExtRefFn | None = None,
  1582. hash_format: int | None = None,
  1583. ) -> bytes:
  1584. """Create an index file for this data file.
  1585. Args:
  1586. filename: Index filename.
  1587. progress: Progress report function
  1588. version: Index version (1, 2, or 3)
  1589. resolve_ext_ref: Function to resolve external references
  1590. hash_format: Hash algorithm identifier for v3 (1 = SHA-1, 2 = SHA-256)
  1591. Returns: Checksum of index file
  1592. """
  1593. if version == 1:
  1594. return self.create_index_v1(
  1595. filename, progress, resolve_ext_ref=resolve_ext_ref
  1596. )
  1597. elif version == 2:
  1598. return self.create_index_v2(
  1599. filename, progress, resolve_ext_ref=resolve_ext_ref
  1600. )
  1601. elif version == 3:
  1602. return self.create_index_v3(
  1603. filename,
  1604. progress,
  1605. resolve_ext_ref=resolve_ext_ref,
  1606. hash_format=hash_format,
  1607. )
  1608. else:
  1609. raise ValueError(f"unknown index format {version}")
  1610. def get_stored_checksum(self) -> bytes:
  1611. """Return the expected checksum stored in this pack."""
  1612. self._file.seek(-20, SEEK_END)
  1613. return self._file.read(20)
  1614. def check(self) -> None:
  1615. """Check the consistency of this pack."""
  1616. actual = self.calculate_checksum()
  1617. stored = self.get_stored_checksum()
  1618. if actual != stored:
  1619. raise ChecksumMismatch(stored, actual)
  1620. def get_unpacked_object_at(
  1621. self, offset: int, *, include_comp: bool = False
  1622. ) -> UnpackedObject:
  1623. """Given offset in the packfile return a UnpackedObject."""
  1624. assert offset >= self._header_size
  1625. self._file.seek(offset)
  1626. unpacked, _ = unpack_object(self._file.read, include_comp=include_comp)
  1627. unpacked.offset = offset
  1628. return unpacked
  1629. def get_object_at(self, offset: int) -> tuple[int, OldUnpackedObject]:
  1630. """Given an offset in to the packfile return the object that is there.
  1631. Using the associated index the location of an object can be looked up,
  1632. and then the packfile can be asked directly for that object using this
  1633. function.
  1634. """
  1635. try:
  1636. return self._offset_cache[offset]
  1637. except KeyError:
  1638. pass
  1639. unpacked = self.get_unpacked_object_at(offset, include_comp=False)
  1640. return (unpacked.pack_type_num, unpacked._obj())
  1641. T = TypeVar("T")
  1642. class DeltaChainIterator(Generic[T]):
  1643. """Abstract iterator over pack data based on delta chains.
  1644. Each object in the pack is guaranteed to be inflated exactly once,
  1645. regardless of how many objects reference it as a delta base. As a result,
  1646. memory usage is proportional to the length of the longest delta chain.
  1647. Subclasses can override _result to define the result type of the iterator.
  1648. By default, results are UnpackedObjects with the following members set:
  1649. * offset
  1650. * obj_type_num
  1651. * obj_chunks
  1652. * pack_type_num
  1653. * delta_base (for delta types)
  1654. * comp_chunks (if _include_comp is True)
  1655. * decomp_chunks
  1656. * decomp_len
  1657. * crc32 (if _compute_crc32 is True)
  1658. """
  1659. _compute_crc32 = False
  1660. _include_comp = False
  1661. def __init__(
  1662. self,
  1663. file_obj: IO[bytes] | None,
  1664. *,
  1665. resolve_ext_ref: ResolveExtRefFn | None = None,
  1666. ) -> None:
  1667. """Initialize DeltaChainIterator.
  1668. Args:
  1669. file_obj: File object to read pack data from
  1670. resolve_ext_ref: Optional function to resolve external references
  1671. """
  1672. self._file = file_obj
  1673. self._resolve_ext_ref = resolve_ext_ref
  1674. self._pending_ofs: dict[int, list[int]] = defaultdict(list)
  1675. self._pending_ref: dict[bytes, list[int]] = defaultdict(list)
  1676. self._full_ofs: list[tuple[int, int]] = []
  1677. self._ext_refs: list[RawObjectID] = []
  1678. @classmethod
  1679. def for_pack_data(
  1680. cls, pack_data: PackData, resolve_ext_ref: ResolveExtRefFn | None = None
  1681. ) -> "DeltaChainIterator[T]":
  1682. """Create a DeltaChainIterator from pack data.
  1683. Args:
  1684. pack_data: PackData object to iterate
  1685. resolve_ext_ref: Optional function to resolve external refs
  1686. Returns:
  1687. DeltaChainIterator instance
  1688. """
  1689. walker = cls(None, resolve_ext_ref=resolve_ext_ref)
  1690. walker.set_pack_data(pack_data)
  1691. for unpacked in pack_data.iter_unpacked(include_comp=False):
  1692. walker.record(unpacked)
  1693. return walker
  1694. @classmethod
  1695. def for_pack_subset(
  1696. cls,
  1697. pack: "Pack",
  1698. shas: Iterable[ObjectID | RawObjectID],
  1699. *,
  1700. allow_missing: bool = False,
  1701. resolve_ext_ref: ResolveExtRefFn | None = None,
  1702. ) -> "DeltaChainIterator[T]":
  1703. """Create a DeltaChainIterator for a subset of objects.
  1704. Args:
  1705. pack: Pack object containing the data
  1706. shas: Iterable of object SHAs to include
  1707. allow_missing: If True, skip missing objects
  1708. resolve_ext_ref: Optional function to resolve external refs
  1709. Returns:
  1710. DeltaChainIterator instance
  1711. """
  1712. walker = cls(None, resolve_ext_ref=resolve_ext_ref)
  1713. walker.set_pack_data(pack.data)
  1714. todo = set()
  1715. for sha in shas:
  1716. try:
  1717. off = pack.index.object_offset(sha)
  1718. except KeyError:
  1719. if not allow_missing:
  1720. raise
  1721. else:
  1722. todo.add(off)
  1723. done = set()
  1724. while todo:
  1725. off = todo.pop()
  1726. unpacked = pack.data.get_unpacked_object_at(off)
  1727. walker.record(unpacked)
  1728. done.add(off)
  1729. base_ofs = None
  1730. if unpacked.pack_type_num == OFS_DELTA:
  1731. assert unpacked.offset is not None
  1732. assert unpacked.delta_base is not None
  1733. assert isinstance(unpacked.delta_base, int)
  1734. base_ofs = unpacked.offset - unpacked.delta_base
  1735. elif unpacked.pack_type_num == REF_DELTA:
  1736. with suppress(KeyError):
  1737. assert isinstance(unpacked.delta_base, bytes)
  1738. base_ofs = pack.index.object_index(RawObjectID(unpacked.delta_base))
  1739. if base_ofs is not None and base_ofs not in done:
  1740. todo.add(base_ofs)
  1741. return walker
  1742. def record(self, unpacked: UnpackedObject) -> None:
  1743. """Record an unpacked object for later processing.
  1744. Args:
  1745. unpacked: UnpackedObject to record
  1746. """
  1747. type_num = unpacked.pack_type_num
  1748. offset = unpacked.offset
  1749. assert offset is not None
  1750. if type_num == OFS_DELTA:
  1751. assert unpacked.delta_base is not None
  1752. assert isinstance(unpacked.delta_base, int)
  1753. base_offset = offset - unpacked.delta_base
  1754. self._pending_ofs[base_offset].append(offset)
  1755. elif type_num == REF_DELTA:
  1756. assert isinstance(unpacked.delta_base, bytes)
  1757. self._pending_ref[unpacked.delta_base].append(offset)
  1758. else:
  1759. self._full_ofs.append((offset, type_num))
  1760. def set_pack_data(self, pack_data: PackData) -> None:
  1761. """Set the pack data for iteration.
  1762. Args:
  1763. pack_data: PackData object to use
  1764. """
  1765. self._file = pack_data._file
  1766. def _walk_all_chains(self) -> Iterator[T]:
  1767. for offset, type_num in self._full_ofs:
  1768. yield from self._follow_chain(offset, type_num, None)
  1769. yield from self._walk_ref_chains()
  1770. assert not self._pending_ofs, repr(self._pending_ofs)
  1771. def _ensure_no_pending(self) -> None:
  1772. if self._pending_ref:
  1773. raise UnresolvedDeltas(
  1774. [sha_to_hex(RawObjectID(s)) for s in self._pending_ref]
  1775. )
  1776. def _walk_ref_chains(self) -> Iterator[T]:
  1777. if not self._resolve_ext_ref:
  1778. self._ensure_no_pending()
  1779. return
  1780. for base_sha, pending in sorted(self._pending_ref.items()):
  1781. if base_sha not in self._pending_ref:
  1782. continue
  1783. try:
  1784. type_num, chunks = self._resolve_ext_ref(base_sha)
  1785. except KeyError:
  1786. # Not an external ref, but may depend on one. Either it will
  1787. # get popped via a _follow_chain call, or we will raise an
  1788. # error below.
  1789. continue
  1790. self._ext_refs.append(RawObjectID(base_sha))
  1791. self._pending_ref.pop(base_sha)
  1792. for new_offset in pending:
  1793. yield from self._follow_chain(new_offset, type_num, chunks) # type: ignore[arg-type]
  1794. self._ensure_no_pending()
  1795. def _result(self, unpacked: UnpackedObject) -> T:
  1796. raise NotImplementedError
  1797. def _resolve_object(
  1798. self, offset: int, obj_type_num: int, base_chunks: list[bytes] | None
  1799. ) -> UnpackedObject:
  1800. assert self._file is not None
  1801. self._file.seek(offset)
  1802. unpacked, _ = unpack_object(
  1803. self._file.read,
  1804. include_comp=self._include_comp,
  1805. compute_crc32=self._compute_crc32,
  1806. )
  1807. unpacked.offset = offset
  1808. if base_chunks is None:
  1809. assert unpacked.pack_type_num == obj_type_num
  1810. else:
  1811. assert unpacked.pack_type_num in DELTA_TYPES
  1812. unpacked.obj_type_num = obj_type_num
  1813. unpacked.obj_chunks = apply_delta(base_chunks, unpacked.decomp_chunks)
  1814. return unpacked
  1815. def _follow_chain(
  1816. self, offset: int, obj_type_num: int, base_chunks: list[bytes] | None
  1817. ) -> Iterator[T]:
  1818. # Unlike PackData.get_object_at, there is no need to cache offsets as
  1819. # this approach by design inflates each object exactly once.
  1820. todo = [(offset, obj_type_num, base_chunks)]
  1821. while todo:
  1822. (offset, obj_type_num, base_chunks) = todo.pop()
  1823. unpacked = self._resolve_object(offset, obj_type_num, base_chunks)
  1824. yield self._result(unpacked)
  1825. assert unpacked.offset is not None
  1826. unblocked = chain(
  1827. self._pending_ofs.pop(unpacked.offset, []),
  1828. self._pending_ref.pop(unpacked.sha(), []),
  1829. )
  1830. todo.extend(
  1831. (new_offset, unpacked.obj_type_num, unpacked.obj_chunks) # type: ignore
  1832. for new_offset in unblocked
  1833. )
  1834. def __iter__(self) -> Iterator[T]:
  1835. """Iterate over objects in the pack."""
  1836. return self._walk_all_chains()
  1837. def ext_refs(self) -> list[RawObjectID]:
  1838. """Return external references."""
  1839. return self._ext_refs
  1840. class UnpackedObjectIterator(DeltaChainIterator[UnpackedObject]):
  1841. """Delta chain iterator that yield unpacked objects."""
  1842. def _result(self, unpacked: UnpackedObject) -> UnpackedObject:
  1843. """Return the unpacked object.
  1844. Args:
  1845. unpacked: The unpacked object
  1846. Returns:
  1847. The unpacked object unchanged
  1848. """
  1849. return unpacked
  1850. class PackIndexer(DeltaChainIterator[PackIndexEntry]):
  1851. """Delta chain iterator that yields index entries."""
  1852. _compute_crc32 = True
  1853. def _result(self, unpacked: UnpackedObject) -> PackIndexEntry:
  1854. """Convert unpacked object to pack index entry.
  1855. Args:
  1856. unpacked: The unpacked object
  1857. Returns:
  1858. Tuple of (sha, offset, crc32) for index entry
  1859. """
  1860. assert unpacked.offset is not None
  1861. return unpacked.sha(), unpacked.offset, unpacked.crc32
  1862. class PackInflater(DeltaChainIterator[ShaFile]):
  1863. """Delta chain iterator that yields ShaFile objects."""
  1864. def _result(self, unpacked: UnpackedObject) -> ShaFile:
  1865. """Convert unpacked object to ShaFile.
  1866. Args:
  1867. unpacked: The unpacked object
  1868. Returns:
  1869. ShaFile object from the unpacked data
  1870. """
  1871. return unpacked.sha_file()
  1872. class SHA1Reader(BinaryIO):
  1873. """Wrapper for file-like object that remembers the SHA1 of its data."""
  1874. def __init__(self, f: IO[bytes]) -> None:
  1875. """Initialize SHA1Reader.
  1876. Args:
  1877. f: File-like object to wrap
  1878. """
  1879. self.f = f
  1880. self.sha1 = sha1(b"")
  1881. def read(self, size: int = -1) -> bytes:
  1882. """Read bytes and update SHA1.
  1883. Args:
  1884. size: Number of bytes to read, -1 for all
  1885. Returns:
  1886. Bytes read from file
  1887. """
  1888. data = self.f.read(size)
  1889. self.sha1.update(data)
  1890. return data
  1891. def check_sha(self, allow_empty: bool = False) -> None:
  1892. """Check if the SHA1 matches the expected value.
  1893. Args:
  1894. allow_empty: Allow empty SHA1 hash
  1895. Raises:
  1896. ChecksumMismatch: If SHA1 doesn't match
  1897. """
  1898. stored = self.f.read(20)
  1899. # If git option index.skipHash is set the index will be empty
  1900. if stored != self.sha1.digest() and (
  1901. not allow_empty
  1902. or sha_to_hex(RawObjectID(stored))
  1903. != b"0000000000000000000000000000000000000000"
  1904. ):
  1905. raise ChecksumMismatch(
  1906. self.sha1.hexdigest(), sha_to_hex(RawObjectID(stored))
  1907. )
  1908. def close(self) -> None:
  1909. """Close the underlying file."""
  1910. return self.f.close()
  1911. def tell(self) -> int:
  1912. """Return current file position."""
  1913. return self.f.tell()
  1914. # BinaryIO abstract methods
  1915. def readable(self) -> bool:
  1916. """Check if file is readable."""
  1917. return True
  1918. def writable(self) -> bool:
  1919. """Check if file is writable."""
  1920. return False
  1921. def seekable(self) -> bool:
  1922. """Check if file is seekable."""
  1923. return getattr(self.f, "seekable", lambda: False)()
  1924. def seek(self, offset: int, whence: int = 0) -> int:
  1925. """Seek to position in file.
  1926. Args:
  1927. offset: Position offset
  1928. whence: Reference point (0=start, 1=current, 2=end)
  1929. Returns:
  1930. New file position
  1931. """
  1932. return self.f.seek(offset, whence)
  1933. def flush(self) -> None:
  1934. """Flush the file buffer."""
  1935. if hasattr(self.f, "flush"):
  1936. self.f.flush()
  1937. def readline(self, size: int = -1) -> bytes:
  1938. """Read a line from the file.
  1939. Args:
  1940. size: Maximum bytes to read
  1941. Returns:
  1942. Line read from file
  1943. """
  1944. return self.f.readline(size)
  1945. def readlines(self, hint: int = -1) -> list[bytes]:
  1946. """Read all lines from the file.
  1947. Args:
  1948. hint: Approximate number of bytes to read
  1949. Returns:
  1950. List of lines
  1951. """
  1952. return self.f.readlines(hint)
  1953. def writelines(self, lines: Iterable[bytes], /) -> None: # type: ignore[override]
  1954. """Write multiple lines to the file (not supported)."""
  1955. raise UnsupportedOperation("writelines")
  1956. def write(self, data: bytes, /) -> int: # type: ignore[override]
  1957. """Write data to the file (not supported)."""
  1958. raise UnsupportedOperation("write")
  1959. def __enter__(self) -> "SHA1Reader":
  1960. """Enter context manager."""
  1961. return self
  1962. def __exit__(
  1963. self,
  1964. type: type | None,
  1965. value: BaseException | None,
  1966. traceback: TracebackType | None,
  1967. ) -> None:
  1968. """Exit context manager and close file."""
  1969. self.close()
  1970. def __iter__(self) -> "SHA1Reader":
  1971. """Return iterator for reading file lines."""
  1972. return self
  1973. def __next__(self) -> bytes:
  1974. """Get next line from file.
  1975. Returns:
  1976. Next line
  1977. Raises:
  1978. StopIteration: When no more lines
  1979. """
  1980. line = self.readline()
  1981. if not line:
  1982. raise StopIteration
  1983. return line
  1984. def fileno(self) -> int:
  1985. """Return file descriptor number."""
  1986. return self.f.fileno()
  1987. def isatty(self) -> bool:
  1988. """Check if file is a terminal."""
  1989. return getattr(self.f, "isatty", lambda: False)()
  1990. def truncate(self, size: int | None = None) -> int:
  1991. """Not supported for read-only file.
  1992. Raises:
  1993. UnsupportedOperation: Always raised
  1994. """
  1995. raise UnsupportedOperation("truncate")
  1996. class SHA1Writer(BinaryIO):
  1997. """Wrapper for file-like object that remembers the SHA1 of its data."""
  1998. def __init__(self, f: BinaryIO | IO[bytes]) -> None:
  1999. """Initialize SHA1Writer.
  2000. Args:
  2001. f: File-like object to wrap
  2002. """
  2003. self.f = f
  2004. self.length = 0
  2005. self.sha1 = sha1(b"")
  2006. self.digest: bytes | None = None
  2007. def write(self, data: bytes | bytearray | memoryview, /) -> int: # type: ignore[override]
  2008. """Write data and update SHA1.
  2009. Args:
  2010. data: Data to write
  2011. Returns:
  2012. Number of bytes written
  2013. """
  2014. self.sha1.update(data)
  2015. written = self.f.write(data)
  2016. self.length += written
  2017. return written
  2018. def write_sha(self) -> bytes:
  2019. """Write the SHA1 digest to the file.
  2020. Returns:
  2021. The SHA1 digest bytes
  2022. """
  2023. sha = self.sha1.digest()
  2024. assert len(sha) == 20
  2025. self.f.write(sha)
  2026. self.length += len(sha)
  2027. return sha
  2028. def close(self) -> None:
  2029. """Close the pack file and finalize the SHA."""
  2030. self.digest = self.write_sha()
  2031. self.f.close()
  2032. def offset(self) -> int:
  2033. """Get the total number of bytes written.
  2034. Returns:
  2035. Total bytes written
  2036. """
  2037. return self.length
  2038. def tell(self) -> int:
  2039. """Return current file position."""
  2040. return self.f.tell()
  2041. # BinaryIO abstract methods
  2042. def readable(self) -> bool:
  2043. """Check if file is readable."""
  2044. return False
  2045. def writable(self) -> bool:
  2046. """Check if file is writable."""
  2047. return True
  2048. def seekable(self) -> bool:
  2049. """Check if file is seekable."""
  2050. return getattr(self.f, "seekable", lambda: False)()
  2051. def seek(self, offset: int, whence: int = 0) -> int:
  2052. """Seek to position in file.
  2053. Args:
  2054. offset: Position offset
  2055. whence: Reference point (0=start, 1=current, 2=end)
  2056. Returns:
  2057. New file position
  2058. """
  2059. return self.f.seek(offset, whence)
  2060. def flush(self) -> None:
  2061. """Flush the file buffer."""
  2062. if hasattr(self.f, "flush"):
  2063. self.f.flush()
  2064. def readline(self, size: int = -1) -> bytes:
  2065. """Not supported for write-only file.
  2066. Raises:
  2067. UnsupportedOperation: Always raised
  2068. """
  2069. raise UnsupportedOperation("readline")
  2070. def readlines(self, hint: int = -1) -> list[bytes]:
  2071. """Not supported for write-only file.
  2072. Raises:
  2073. UnsupportedOperation: Always raised
  2074. """
  2075. raise UnsupportedOperation("readlines")
  2076. def writelines(self, lines: Iterable[bytes], /) -> None: # type: ignore[override]
  2077. """Write multiple lines to the file.
  2078. Args:
  2079. lines: Iterable of lines to write
  2080. """
  2081. for line in lines:
  2082. self.write(line)
  2083. def read(self, size: int = -1) -> bytes:
  2084. """Not supported for write-only file.
  2085. Raises:
  2086. UnsupportedOperation: Always raised
  2087. """
  2088. raise UnsupportedOperation("read")
  2089. def __enter__(self) -> "SHA1Writer":
  2090. """Enter context manager."""
  2091. return self
  2092. def __exit__(
  2093. self,
  2094. type: type | None,
  2095. value: BaseException | None,
  2096. traceback: TracebackType | None,
  2097. ) -> None:
  2098. """Exit context manager and close file."""
  2099. self.close()
  2100. def __iter__(self) -> "SHA1Writer":
  2101. """Return iterator."""
  2102. return self
  2103. def __next__(self) -> bytes:
  2104. """Not supported for write-only file.
  2105. Raises:
  2106. UnsupportedOperation: Always raised
  2107. """
  2108. raise UnsupportedOperation("__next__")
  2109. def fileno(self) -> int:
  2110. """Return file descriptor number."""
  2111. return self.f.fileno()
  2112. def isatty(self) -> bool:
  2113. """Check if file is a terminal."""
  2114. return getattr(self.f, "isatty", lambda: False)()
  2115. def truncate(self, size: int | None = None) -> int:
  2116. """Not supported for write-only file.
  2117. Raises:
  2118. UnsupportedOperation: Always raised
  2119. """
  2120. raise UnsupportedOperation("truncate")
  2121. def pack_object_header(
  2122. type_num: int, delta_base: bytes | int | None, size: int
  2123. ) -> bytearray:
  2124. """Create a pack object header for the given object info.
  2125. Args:
  2126. type_num: Numeric type of the object.
  2127. delta_base: Delta base offset or ref, or None for whole objects.
  2128. size: Uncompressed object size.
  2129. Returns: A header for a packed object.
  2130. """
  2131. header = []
  2132. c = (type_num << 4) | (size & 15)
  2133. size >>= 4
  2134. while size:
  2135. header.append(c | 0x80)
  2136. c = size & 0x7F
  2137. size >>= 7
  2138. header.append(c)
  2139. if type_num == OFS_DELTA:
  2140. assert isinstance(delta_base, int)
  2141. ret = [delta_base & 0x7F]
  2142. delta_base >>= 7
  2143. while delta_base:
  2144. delta_base -= 1
  2145. ret.insert(0, 0x80 | (delta_base & 0x7F))
  2146. delta_base >>= 7
  2147. header.extend(ret)
  2148. elif type_num == REF_DELTA:
  2149. assert isinstance(delta_base, bytes)
  2150. assert len(delta_base) == 20
  2151. header += delta_base
  2152. return bytearray(header)
  2153. def pack_object_chunks(
  2154. type: int,
  2155. object: list[bytes] | tuple[bytes | int, list[bytes]],
  2156. compression_level: int = -1,
  2157. ) -> Iterator[bytes]:
  2158. """Generate chunks for a pack object.
  2159. Args:
  2160. type: Numeric type of the object
  2161. object: Object to write
  2162. compression_level: the zlib compression level
  2163. Returns: Chunks
  2164. """
  2165. if type in DELTA_TYPES:
  2166. if isinstance(object, tuple):
  2167. delta_base, object = object
  2168. else:
  2169. raise TypeError("Delta types require a tuple of (delta_base, object)")
  2170. else:
  2171. delta_base = None
  2172. # Convert object to list of bytes chunks
  2173. if isinstance(object, bytes):
  2174. chunks = [object]
  2175. elif isinstance(object, list):
  2176. chunks = object
  2177. elif isinstance(object, ShaFile):
  2178. chunks = object.as_raw_chunks()
  2179. else:
  2180. # Shouldn't reach here with proper typing
  2181. raise TypeError(f"Unexpected object type: {object.__class__.__name__}")
  2182. yield bytes(pack_object_header(type, delta_base, sum(map(len, chunks))))
  2183. compressor = zlib.compressobj(level=compression_level)
  2184. for data in chunks:
  2185. yield compressor.compress(data)
  2186. yield compressor.flush()
  2187. def write_pack_object(
  2188. write: Callable[[bytes], int],
  2189. type: int,
  2190. object: list[bytes] | tuple[bytes | int, list[bytes]],
  2191. sha: "HashObject | None" = None,
  2192. compression_level: int = -1,
  2193. ) -> int:
  2194. """Write pack object to a file.
  2195. Args:
  2196. write: Write function to use
  2197. type: Numeric type of the object
  2198. object: Object to write
  2199. sha: Optional SHA-1 hasher to update
  2200. compression_level: the zlib compression level
  2201. Returns: CRC32 checksum of the written object
  2202. """
  2203. crc32 = 0
  2204. for chunk in pack_object_chunks(type, object, compression_level=compression_level):
  2205. write(chunk)
  2206. if sha is not None:
  2207. sha.update(chunk)
  2208. crc32 = binascii.crc32(chunk, crc32)
  2209. return crc32 & 0xFFFFFFFF
  2210. def write_pack(
  2211. filename: str,
  2212. objects: Sequence[ShaFile] | Sequence[tuple[ShaFile, bytes | None]],
  2213. *,
  2214. deltify: bool | None = None,
  2215. delta_window_size: int | None = None,
  2216. compression_level: int = -1,
  2217. ) -> tuple[bytes, bytes]:
  2218. """Write a new pack data file.
  2219. Args:
  2220. filename: Path to the new pack file (without .pack extension)
  2221. objects: Objects to write to the pack
  2222. delta_window_size: Delta window size
  2223. deltify: Whether to deltify pack objects
  2224. compression_level: the zlib compression level
  2225. Returns: Tuple with checksum of pack file and index file
  2226. """
  2227. with GitFile(filename + ".pack", "wb") as f:
  2228. entries, data_sum = write_pack_objects(
  2229. f,
  2230. objects,
  2231. delta_window_size=delta_window_size,
  2232. deltify=deltify,
  2233. compression_level=compression_level,
  2234. )
  2235. entries_list = sorted([(k, v[0], v[1]) for (k, v) in entries.items()])
  2236. with GitFile(filename + ".idx", "wb") as f:
  2237. idx_sha = write_pack_index(f, entries_list, data_sum)
  2238. return data_sum, idx_sha
  2239. def pack_header_chunks(num_objects: int) -> Iterator[bytes]:
  2240. """Yield chunks for a pack header."""
  2241. yield b"PACK" # Pack header
  2242. yield struct.pack(b">L", 2) # Pack version
  2243. yield struct.pack(b">L", num_objects) # Number of objects in pack
  2244. def write_pack_header(
  2245. write: Callable[[bytes], int] | IO[bytes], num_objects: int
  2246. ) -> None:
  2247. """Write a pack header for the given number of objects."""
  2248. write_fn: Callable[[bytes], int]
  2249. if hasattr(write, "write"):
  2250. write_fn = write.write
  2251. warnings.warn(
  2252. "write_pack_header() now takes a write rather than file argument",
  2253. DeprecationWarning,
  2254. stacklevel=2,
  2255. )
  2256. else:
  2257. write_fn = write
  2258. for chunk in pack_header_chunks(num_objects):
  2259. write_fn(chunk)
  2260. def find_reusable_deltas(
  2261. container: PackedObjectContainer,
  2262. object_ids: Set[ObjectID],
  2263. *,
  2264. other_haves: Set[ObjectID] | None = None,
  2265. progress: Callable[..., None] | None = None,
  2266. ) -> Iterator[UnpackedObject]:
  2267. """Find deltas in a pack that can be reused.
  2268. Args:
  2269. container: Pack container to search for deltas
  2270. object_ids: Set of object IDs to find deltas for
  2271. other_haves: Set of other object IDs we have
  2272. progress: Optional progress reporting callback
  2273. Returns:
  2274. Iterator of UnpackedObject entries that can be reused
  2275. """
  2276. if other_haves is None:
  2277. other_haves = set()
  2278. reused = 0
  2279. for i, unpacked in enumerate(
  2280. container.iter_unpacked_subset(
  2281. object_ids, allow_missing=True, convert_ofs_delta=True
  2282. )
  2283. ):
  2284. if progress is not None and i % 1000 == 0:
  2285. progress(f"checking for reusable deltas: {i}/{len(object_ids)}\r".encode())
  2286. if unpacked.pack_type_num == REF_DELTA:
  2287. hexsha = sha_to_hex(unpacked.delta_base) # type: ignore
  2288. if hexsha in object_ids or hexsha in other_haves:
  2289. yield unpacked
  2290. reused += 1
  2291. if progress is not None:
  2292. progress((f"found {reused} deltas to reuse\n").encode())
  2293. def deltify_pack_objects(
  2294. objects: Iterator[ShaFile] | Iterator[tuple[ShaFile, bytes | None]],
  2295. *,
  2296. window_size: int | None = None,
  2297. progress: Callable[..., None] | None = None,
  2298. ) -> Iterator[UnpackedObject]:
  2299. """Generate deltas for pack objects.
  2300. Args:
  2301. objects: An iterable of (object, path) tuples to deltify.
  2302. window_size: Window size; None for default
  2303. progress: Optional progress reporting callback
  2304. Returns: Iterator over type_num, object id, delta_base, content
  2305. delta_base is None for full text entries
  2306. """
  2307. def objects_with_hints() -> Iterator[tuple[ShaFile, tuple[int, bytes | None]]]:
  2308. for e in objects:
  2309. if isinstance(e, ShaFile):
  2310. yield (e, (e.type_num, None))
  2311. else:
  2312. yield (e[0], (e[0].type_num, e[1]))
  2313. sorted_objs = sort_objects_for_delta(objects_with_hints())
  2314. yield from deltas_from_sorted_objects(
  2315. sorted_objs,
  2316. window_size=window_size,
  2317. progress=progress,
  2318. )
  2319. def sort_objects_for_delta(
  2320. objects: Iterator[ShaFile] | Iterator[tuple[ShaFile, PackHint | None]],
  2321. ) -> Iterator[tuple[ShaFile, bytes | None]]:
  2322. """Sort objects for optimal delta compression.
  2323. Args:
  2324. objects: Iterator of objects or (object, hint) tuples
  2325. Returns:
  2326. Iterator of sorted (ShaFile, path) tuples
  2327. """
  2328. magic = []
  2329. for entry in objects:
  2330. if isinstance(entry, tuple):
  2331. obj, hint = entry
  2332. if hint is None:
  2333. type_num = None
  2334. path = None
  2335. else:
  2336. (type_num, path) = hint
  2337. else:
  2338. obj = entry
  2339. type_num = None
  2340. path = None
  2341. magic.append((type_num, path, -obj.raw_length(), obj))
  2342. # Build a list of objects ordered by the magic Linus heuristic
  2343. # This helps us find good objects to diff against us
  2344. magic.sort()
  2345. return ((x[3], x[1]) for x in magic)
  2346. def deltas_from_sorted_objects(
  2347. objects: Iterator[tuple[ShaFile, bytes | None]],
  2348. window_size: int | None = None,
  2349. progress: Callable[..., None] | None = None,
  2350. ) -> Iterator[UnpackedObject]:
  2351. """Create deltas from sorted objects.
  2352. Args:
  2353. objects: Iterator of sorted objects to deltify
  2354. window_size: Delta window size; None for default
  2355. progress: Optional progress reporting callback
  2356. Returns:
  2357. Iterator of UnpackedObject entries
  2358. """
  2359. # TODO(jelmer): Use threads
  2360. if window_size is None:
  2361. window_size = DEFAULT_PACK_DELTA_WINDOW_SIZE
  2362. possible_bases: deque[tuple[bytes, int, list[bytes]]] = deque()
  2363. for i, (o, path) in enumerate(objects):
  2364. if progress is not None and i % 1000 == 0:
  2365. progress((f"generating deltas: {i}\r").encode())
  2366. raw = o.as_raw_chunks()
  2367. winner = raw
  2368. winner_len = sum(map(len, winner))
  2369. winner_base = None
  2370. for base_id, base_type_num, base in possible_bases:
  2371. if base_type_num != o.type_num:
  2372. continue
  2373. delta_len = 0
  2374. delta = []
  2375. for chunk in create_delta(b"".join(base), b"".join(raw)):
  2376. delta_len += len(chunk)
  2377. if delta_len >= winner_len:
  2378. break
  2379. delta.append(chunk)
  2380. else:
  2381. winner_base = base_id
  2382. winner = delta
  2383. winner_len = sum(map(len, winner))
  2384. yield UnpackedObject(
  2385. o.type_num,
  2386. sha=o.sha().digest(),
  2387. delta_base=winner_base,
  2388. decomp_len=winner_len,
  2389. decomp_chunks=winner,
  2390. )
  2391. possible_bases.appendleft((o.sha().digest(), o.type_num, raw))
  2392. while len(possible_bases) > window_size:
  2393. possible_bases.pop()
  2394. def pack_objects_to_data(
  2395. objects: Sequence[ShaFile]
  2396. | Sequence[tuple[ShaFile, bytes | None]]
  2397. | Sequence[tuple[ShaFile, PackHint | None]],
  2398. *,
  2399. deltify: bool | None = None,
  2400. delta_window_size: int | None = None,
  2401. ofs_delta: bool = True,
  2402. progress: Callable[..., None] | None = None,
  2403. ) -> tuple[int, Iterator[UnpackedObject]]:
  2404. """Create pack data from objects.
  2405. Args:
  2406. objects: Pack objects
  2407. deltify: Whether to deltify pack objects
  2408. delta_window_size: Delta window size
  2409. ofs_delta: Whether to use offset deltas
  2410. progress: Optional progress reporting callback
  2411. Returns: Tuples with (type_num, hexdigest, delta base, object chunks)
  2412. """
  2413. count = len(objects)
  2414. if deltify is None:
  2415. # PERFORMANCE/TODO(jelmer): This should be enabled but the python
  2416. # implementation is *much* too slow at the moment.
  2417. # Maybe consider enabling it just if the rust extension is available?
  2418. deltify = False
  2419. if deltify:
  2420. return (
  2421. count,
  2422. deltify_pack_objects(
  2423. iter(objects), # type: ignore
  2424. window_size=delta_window_size,
  2425. progress=progress,
  2426. ),
  2427. )
  2428. else:
  2429. def iter_without_path() -> Iterator[UnpackedObject]:
  2430. for o in objects:
  2431. if isinstance(o, tuple):
  2432. yield full_unpacked_object(o[0])
  2433. else:
  2434. yield full_unpacked_object(o)
  2435. return (count, iter_without_path())
  2436. def generate_unpacked_objects(
  2437. container: PackedObjectContainer,
  2438. object_ids: Sequence[tuple[ObjectID, PackHint | None]],
  2439. delta_window_size: int | None = None,
  2440. deltify: bool | None = None,
  2441. reuse_deltas: bool = True,
  2442. ofs_delta: bool = True,
  2443. other_haves: set[ObjectID] | None = None,
  2444. progress: Callable[..., None] | None = None,
  2445. ) -> Iterator[UnpackedObject]:
  2446. """Create pack data from objects.
  2447. Returns: Tuples with (type_num, hexdigest, delta base, object chunks)
  2448. """
  2449. todo = dict(object_ids)
  2450. if reuse_deltas:
  2451. for unpack in find_reusable_deltas(
  2452. container, set(todo), other_haves=other_haves, progress=progress
  2453. ):
  2454. del todo[sha_to_hex(RawObjectID(unpack.sha()))]
  2455. yield unpack
  2456. if deltify is None:
  2457. # PERFORMANCE/TODO(jelmer): This should be enabled but is *much* too
  2458. # slow at the moment.
  2459. deltify = False
  2460. if deltify:
  2461. objects_to_delta = container.iterobjects_subset(
  2462. todo.keys(), allow_missing=False
  2463. )
  2464. sorted_objs = sort_objects_for_delta((o, todo[o.id]) for o in objects_to_delta)
  2465. yield from deltas_from_sorted_objects(
  2466. sorted_objs,
  2467. window_size=delta_window_size,
  2468. progress=progress,
  2469. )
  2470. else:
  2471. for oid in todo:
  2472. yield full_unpacked_object(container[oid])
  2473. def full_unpacked_object(o: ShaFile) -> UnpackedObject:
  2474. """Create an UnpackedObject from a ShaFile.
  2475. Args:
  2476. o: ShaFile object to convert
  2477. Returns:
  2478. UnpackedObject with full object data
  2479. """
  2480. return UnpackedObject(
  2481. o.type_num,
  2482. delta_base=None,
  2483. crc32=None,
  2484. decomp_chunks=o.as_raw_chunks(),
  2485. sha=o.sha().digest(),
  2486. )
  2487. def write_pack_from_container(
  2488. write: Callable[[bytes], None]
  2489. | Callable[[bytes | bytearray | memoryview], int]
  2490. | IO[bytes],
  2491. container: PackedObjectContainer,
  2492. object_ids: Sequence[tuple[ObjectID, PackHint | None]],
  2493. delta_window_size: int | None = None,
  2494. deltify: bool | None = None,
  2495. reuse_deltas: bool = True,
  2496. compression_level: int = -1,
  2497. other_haves: set[ObjectID] | None = None,
  2498. ) -> tuple[dict[bytes, tuple[int, int]], bytes]:
  2499. """Write a new pack data file.
  2500. Args:
  2501. write: write function to use
  2502. container: PackedObjectContainer
  2503. object_ids: Sequence of (object_id, hint) tuples to write
  2504. delta_window_size: Sliding window size for searching for deltas;
  2505. Set to None for default window size.
  2506. deltify: Whether to deltify objects
  2507. reuse_deltas: Whether to reuse existing deltas
  2508. compression_level: the zlib compression level to use
  2509. other_haves: Set of additional object IDs the receiver has
  2510. Returns: Dict mapping id -> (offset, crc32 checksum), pack checksum
  2511. """
  2512. pack_contents_count = len(object_ids)
  2513. pack_contents = generate_unpacked_objects(
  2514. container,
  2515. object_ids,
  2516. delta_window_size=delta_window_size,
  2517. deltify=deltify,
  2518. reuse_deltas=reuse_deltas,
  2519. other_haves=other_haves,
  2520. )
  2521. return write_pack_data(
  2522. write,
  2523. pack_contents,
  2524. num_records=pack_contents_count,
  2525. compression_level=compression_level,
  2526. )
  2527. def write_pack_objects(
  2528. write: Callable[[bytes], None] | IO[bytes],
  2529. objects: Sequence[ShaFile] | Sequence[tuple[ShaFile, bytes | None]],
  2530. *,
  2531. delta_window_size: int | None = None,
  2532. deltify: bool | None = None,
  2533. compression_level: int = -1,
  2534. ) -> tuple[dict[bytes, tuple[int, int]], bytes]:
  2535. """Write a new pack data file.
  2536. Args:
  2537. write: write function to use
  2538. objects: Sequence of (object, path) tuples to write
  2539. delta_window_size: Sliding window size for searching for deltas;
  2540. Set to None for default window size.
  2541. deltify: Whether to deltify objects
  2542. compression_level: the zlib compression level to use
  2543. Returns: Dict mapping id -> (offset, crc32 checksum), pack checksum
  2544. """
  2545. pack_contents_count, pack_contents = pack_objects_to_data(objects, deltify=deltify)
  2546. return write_pack_data(
  2547. write,
  2548. pack_contents,
  2549. num_records=pack_contents_count,
  2550. compression_level=compression_level,
  2551. )
  2552. class PackChunkGenerator:
  2553. """Generator for pack data chunks."""
  2554. def __init__(
  2555. self,
  2556. num_records: int | None = None,
  2557. records: Iterator[UnpackedObject] | None = None,
  2558. progress: Callable[..., None] | None = None,
  2559. compression_level: int = -1,
  2560. reuse_compressed: bool = True,
  2561. ) -> None:
  2562. """Initialize PackChunkGenerator.
  2563. Args:
  2564. num_records: Expected number of records
  2565. records: Iterator of pack records
  2566. progress: Optional progress callback
  2567. compression_level: Compression level (-1 for default)
  2568. reuse_compressed: Whether to reuse compressed chunks
  2569. """
  2570. self.cs = sha1(b"")
  2571. self.entries: dict[bytes, tuple[int, int]] = {}
  2572. if records is None:
  2573. records = iter([]) # Empty iterator if None
  2574. self._it = self._pack_data_chunks(
  2575. records=records,
  2576. num_records=num_records,
  2577. progress=progress,
  2578. compression_level=compression_level,
  2579. reuse_compressed=reuse_compressed,
  2580. )
  2581. def sha1digest(self) -> bytes:
  2582. """Return the SHA1 digest of the pack data."""
  2583. return self.cs.digest()
  2584. def __iter__(self) -> Iterator[bytes]:
  2585. """Iterate over pack data chunks."""
  2586. return self._it
  2587. def _pack_data_chunks(
  2588. self,
  2589. records: Iterator[UnpackedObject],
  2590. *,
  2591. num_records: int | None = None,
  2592. progress: Callable[..., None] | None = None,
  2593. compression_level: int = -1,
  2594. reuse_compressed: bool = True,
  2595. ) -> Iterator[bytes]:
  2596. """Iterate pack data file chunks.
  2597. Args:
  2598. records: Iterator over UnpackedObject
  2599. num_records: Number of records (defaults to len(records) if not specified)
  2600. progress: Function to report progress to
  2601. compression_level: the zlib compression level
  2602. reuse_compressed: Whether to reuse compressed chunks
  2603. Returns: Dict mapping id -> (offset, crc32 checksum), pack checksum
  2604. """
  2605. # Write the pack
  2606. if num_records is None:
  2607. num_records = len(records) # type: ignore
  2608. offset = 0
  2609. for chunk in pack_header_chunks(num_records):
  2610. yield chunk
  2611. self.cs.update(chunk)
  2612. offset += len(chunk)
  2613. actual_num_records = 0
  2614. for i, unpacked in enumerate(records):
  2615. type_num = unpacked.pack_type_num
  2616. if progress is not None and i % 1000 == 0:
  2617. progress((f"writing pack data: {i}/{num_records}\r").encode("ascii"))
  2618. raw: list[bytes] | tuple[int, list[bytes]] | tuple[bytes, list[bytes]]
  2619. if unpacked.delta_base is not None:
  2620. assert isinstance(unpacked.delta_base, bytes), (
  2621. f"Expected bytes, got {type(unpacked.delta_base)}"
  2622. )
  2623. try:
  2624. base_offset, _base_crc32 = self.entries[unpacked.delta_base]
  2625. except KeyError:
  2626. type_num = REF_DELTA
  2627. assert isinstance(unpacked.delta_base, bytes)
  2628. raw = (unpacked.delta_base, unpacked.decomp_chunks)
  2629. else:
  2630. type_num = OFS_DELTA
  2631. raw = (offset - base_offset, unpacked.decomp_chunks)
  2632. else:
  2633. raw = unpacked.decomp_chunks
  2634. chunks: list[bytes] | Iterator[bytes]
  2635. if unpacked.comp_chunks is not None and reuse_compressed:
  2636. chunks = unpacked.comp_chunks
  2637. else:
  2638. chunks = pack_object_chunks(
  2639. type_num, raw, compression_level=compression_level
  2640. )
  2641. crc32 = 0
  2642. object_size = 0
  2643. for chunk in chunks:
  2644. yield chunk
  2645. crc32 = binascii.crc32(chunk, crc32)
  2646. self.cs.update(chunk)
  2647. object_size += len(chunk)
  2648. actual_num_records += 1
  2649. self.entries[unpacked.sha()] = (offset, crc32)
  2650. offset += object_size
  2651. if actual_num_records != num_records:
  2652. raise AssertionError(
  2653. f"actual records written differs: {actual_num_records} != {num_records}"
  2654. )
  2655. yield self.cs.digest()
  2656. def write_pack_data(
  2657. write: Callable[[bytes], None]
  2658. | Callable[[bytes | bytearray | memoryview], int]
  2659. | IO[bytes],
  2660. records: Iterator[UnpackedObject],
  2661. *,
  2662. num_records: int | None = None,
  2663. progress: Callable[..., None] | None = None,
  2664. compression_level: int = -1,
  2665. ) -> tuple[dict[bytes, tuple[int, int]], bytes]:
  2666. """Write a new pack data file.
  2667. Args:
  2668. write: Write function to use
  2669. num_records: Number of records (defaults to len(records) if None)
  2670. records: Iterator over type_num, object_id, delta_base, raw
  2671. progress: Function to report progress to
  2672. compression_level: the zlib compression level
  2673. Returns: Dict mapping id -> (offset, crc32 checksum), pack checksum
  2674. """
  2675. chunk_generator = PackChunkGenerator(
  2676. num_records=num_records,
  2677. records=records,
  2678. progress=progress,
  2679. compression_level=compression_level,
  2680. )
  2681. for chunk in chunk_generator:
  2682. if callable(write):
  2683. write(chunk)
  2684. else:
  2685. write.write(chunk)
  2686. return chunk_generator.entries, chunk_generator.sha1digest()
  2687. def write_pack_index_v1(
  2688. f: IO[bytes],
  2689. entries: Iterable[tuple[bytes, int, int | None]],
  2690. pack_checksum: bytes,
  2691. ) -> bytes:
  2692. """Write a new pack index file.
  2693. Args:
  2694. f: A file-like object to write to
  2695. entries: List of tuples with object name (sha), offset_in_pack,
  2696. and crc32_checksum.
  2697. pack_checksum: Checksum of the pack file.
  2698. Returns: The SHA of the written index file
  2699. """
  2700. f = SHA1Writer(f)
  2701. fan_out_table: dict[int, int] = defaultdict(lambda: 0)
  2702. for name, _offset, _entry_checksum in entries:
  2703. fan_out_table[ord(name[:1])] += 1
  2704. # Fan-out table
  2705. for i in range(0x100):
  2706. f.write(struct.pack(">L", fan_out_table[i]))
  2707. fan_out_table[i + 1] += fan_out_table[i]
  2708. for name, offset, _entry_checksum in entries:
  2709. if len(name) != 20:
  2710. raise TypeError("pack index v1 only supports SHA-1 names")
  2711. if not (offset <= 0xFFFFFFFF):
  2712. raise TypeError("pack format 1 only supports offsets < 2Gb")
  2713. f.write(struct.pack(">L20s", offset, name))
  2714. assert len(pack_checksum) == 20
  2715. f.write(pack_checksum)
  2716. return f.write_sha()
  2717. def _delta_encode_size(size: int) -> bytes:
  2718. ret = bytearray()
  2719. c = size & 0x7F
  2720. size >>= 7
  2721. while size:
  2722. ret.append(c | 0x80)
  2723. c = size & 0x7F
  2724. size >>= 7
  2725. ret.append(c)
  2726. return bytes(ret)
  2727. # The length of delta compression copy operations in version 2 packs is limited
  2728. # to 64K. To copy more, we use several copy operations. Version 3 packs allow
  2729. # 24-bit lengths in copy operations, but we always make version 2 packs.
  2730. _MAX_COPY_LEN = 0xFFFF
  2731. def _encode_copy_operation(start: int, length: int) -> bytes:
  2732. scratch = bytearray([0x80])
  2733. for i in range(4):
  2734. if start & 0xFF << i * 8:
  2735. scratch.append((start >> i * 8) & 0xFF)
  2736. scratch[0] |= 1 << i
  2737. for i in range(2):
  2738. if length & 0xFF << i * 8:
  2739. scratch.append((length >> i * 8) & 0xFF)
  2740. scratch[0] |= 1 << (4 + i)
  2741. return bytes(scratch)
  2742. def _create_delta_py(base_buf: bytes, target_buf: bytes) -> Iterator[bytes]:
  2743. """Use python difflib to work out how to transform base_buf to target_buf.
  2744. Args:
  2745. base_buf: Base buffer
  2746. target_buf: Target buffer
  2747. """
  2748. if isinstance(base_buf, list):
  2749. base_buf = b"".join(base_buf)
  2750. if isinstance(target_buf, list):
  2751. target_buf = b"".join(target_buf)
  2752. assert isinstance(base_buf, bytes)
  2753. assert isinstance(target_buf, bytes)
  2754. # write delta header
  2755. yield _delta_encode_size(len(base_buf))
  2756. yield _delta_encode_size(len(target_buf))
  2757. # write out delta opcodes
  2758. seq = SequenceMatcher(isjunk=None, a=base_buf, b=target_buf)
  2759. for opcode, i1, i2, j1, j2 in seq.get_opcodes():
  2760. # Git patch opcodes don't care about deletes!
  2761. # if opcode == 'replace' or opcode == 'delete':
  2762. # pass
  2763. if opcode == "equal":
  2764. # If they are equal, unpacker will use data from base_buf
  2765. # Write out an opcode that says what range to use
  2766. copy_start = i1
  2767. copy_len = i2 - i1
  2768. while copy_len > 0:
  2769. to_copy = min(copy_len, _MAX_COPY_LEN)
  2770. yield _encode_copy_operation(copy_start, to_copy)
  2771. copy_start += to_copy
  2772. copy_len -= to_copy
  2773. if opcode == "replace" or opcode == "insert":
  2774. # If we are replacing a range or adding one, then we just
  2775. # output it to the stream (prefixed by its size)
  2776. s = j2 - j1
  2777. o = j1
  2778. while s > 127:
  2779. yield bytes([127])
  2780. yield memoryview(target_buf)[o : o + 127]
  2781. s -= 127
  2782. o += 127
  2783. yield bytes([s])
  2784. yield memoryview(target_buf)[o : o + s]
  2785. # Default to pure Python implementation
  2786. create_delta = _create_delta_py
  2787. def apply_delta(
  2788. src_buf: bytes | list[bytes], delta: bytes | list[bytes]
  2789. ) -> list[bytes]:
  2790. """Based on the similar function in git's patch-delta.c.
  2791. Args:
  2792. src_buf: Source buffer
  2793. delta: Delta instructions
  2794. """
  2795. if not isinstance(src_buf, bytes):
  2796. src_buf = b"".join(src_buf)
  2797. if not isinstance(delta, bytes):
  2798. delta = b"".join(delta)
  2799. out = []
  2800. index = 0
  2801. delta_length = len(delta)
  2802. def get_delta_header_size(delta: bytes, index: int) -> tuple[int, int]:
  2803. size = 0
  2804. i = 0
  2805. while delta:
  2806. cmd = ord(delta[index : index + 1])
  2807. index += 1
  2808. size |= (cmd & ~0x80) << i
  2809. i += 7
  2810. if not cmd & 0x80:
  2811. break
  2812. return size, index
  2813. src_size, index = get_delta_header_size(delta, index)
  2814. dest_size, index = get_delta_header_size(delta, index)
  2815. if src_size != len(src_buf):
  2816. raise ApplyDeltaError(
  2817. f"Unexpected source buffer size: {src_size} vs {len(src_buf)}"
  2818. )
  2819. while index < delta_length:
  2820. cmd = ord(delta[index : index + 1])
  2821. index += 1
  2822. if cmd & 0x80:
  2823. cp_off = 0
  2824. for i in range(4):
  2825. if cmd & (1 << i):
  2826. x = ord(delta[index : index + 1])
  2827. index += 1
  2828. cp_off |= x << (i * 8)
  2829. cp_size = 0
  2830. # Version 3 packs can contain copy sizes larger than 64K.
  2831. for i in range(3):
  2832. if cmd & (1 << (4 + i)):
  2833. x = ord(delta[index : index + 1])
  2834. index += 1
  2835. cp_size |= x << (i * 8)
  2836. if cp_size == 0:
  2837. cp_size = 0x10000
  2838. if (
  2839. cp_off + cp_size < cp_size
  2840. or cp_off + cp_size > src_size
  2841. or cp_size > dest_size
  2842. ):
  2843. break
  2844. out.append(src_buf[cp_off : cp_off + cp_size])
  2845. elif cmd != 0:
  2846. out.append(delta[index : index + cmd])
  2847. index += cmd
  2848. else:
  2849. raise ApplyDeltaError("Invalid opcode 0")
  2850. if index != delta_length:
  2851. raise ApplyDeltaError(f"delta not empty: {delta[index:]!r}")
  2852. if dest_size != chunks_length(out):
  2853. raise ApplyDeltaError("dest size incorrect")
  2854. return out
  2855. def write_pack_index_v2(
  2856. f: IO[bytes],
  2857. entries: Iterable[tuple[bytes, int, int | None]],
  2858. pack_checksum: bytes,
  2859. ) -> bytes:
  2860. """Write a new pack index file.
  2861. Args:
  2862. f: File-like object to write to
  2863. entries: List of tuples with object name (sha), offset_in_pack, and
  2864. crc32_checksum.
  2865. pack_checksum: Checksum of the pack file.
  2866. Returns: The SHA of the index file written
  2867. """
  2868. f = SHA1Writer(f)
  2869. f.write(b"\377tOc") # Magic!
  2870. f.write(struct.pack(">L", 2))
  2871. fan_out_table: dict[int, int] = defaultdict(lambda: 0)
  2872. for name, offset, entry_checksum in entries:
  2873. fan_out_table[ord(name[:1])] += 1
  2874. try:
  2875. hash_size = len(next(iter(entries))[0])
  2876. except StopIteration:
  2877. hash_size = 20 # Default to SHA-1 size if no entries
  2878. # Fan-out table
  2879. largetable: list[int] = []
  2880. for i in range(0x100):
  2881. f.write(struct.pack(b">L", fan_out_table[i]))
  2882. fan_out_table[i + 1] += fan_out_table[i]
  2883. for name, offset, entry_checksum in entries:
  2884. if len(name) != hash_size:
  2885. raise TypeError(
  2886. f"Object name has wrong length: expected {hash_size}, got {len(name)}"
  2887. )
  2888. f.write(name)
  2889. for name, offset, entry_checksum in entries:
  2890. f.write(struct.pack(b">L", entry_checksum))
  2891. for name, offset, entry_checksum in entries:
  2892. if offset < 2**31:
  2893. f.write(struct.pack(b">L", offset))
  2894. else:
  2895. f.write(struct.pack(b">L", 2**31 + len(largetable)))
  2896. largetable.append(offset)
  2897. for offset in largetable:
  2898. f.write(struct.pack(b">Q", offset))
  2899. assert len(pack_checksum) == 20
  2900. f.write(pack_checksum)
  2901. return f.write_sha()
  2902. def write_pack_index_v3(
  2903. f: IO[bytes],
  2904. entries: Iterable[tuple[bytes, int, int | None]],
  2905. pack_checksum: bytes,
  2906. hash_format: int = 1,
  2907. ) -> bytes:
  2908. """Write a new pack index file in v3 format.
  2909. Args:
  2910. f: File-like object to write to
  2911. entries: List of tuples with object name (sha), offset_in_pack, and
  2912. crc32_checksum.
  2913. pack_checksum: Checksum of the pack file.
  2914. hash_format: Hash algorithm identifier (1 = SHA-1, 2 = SHA-256)
  2915. Returns: The SHA of the index file written
  2916. """
  2917. if hash_format == 1:
  2918. hash_size = 20 # SHA-1
  2919. writer_cls = SHA1Writer
  2920. elif hash_format == 2:
  2921. hash_size = 32 # SHA-256
  2922. # TODO: Add SHA256Writer when SHA-256 support is implemented
  2923. raise NotImplementedError("SHA-256 support not yet implemented")
  2924. else:
  2925. raise ValueError(f"Unknown hash algorithm {hash_format}")
  2926. # Convert entries to list to allow multiple iterations
  2927. entries_list = list(entries)
  2928. # Calculate shortest unambiguous prefix length for object names
  2929. # For now, use full hash size (this could be optimized)
  2930. shortened_oid_len = hash_size
  2931. f = writer_cls(f)
  2932. f.write(b"\377tOc") # Magic!
  2933. f.write(struct.pack(">L", 3)) # Version 3
  2934. f.write(struct.pack(">L", hash_format)) # Hash algorithm
  2935. f.write(struct.pack(">L", shortened_oid_len)) # Shortened OID length
  2936. fan_out_table: dict[int, int] = defaultdict(lambda: 0)
  2937. for name, offset, entry_checksum in entries_list:
  2938. if len(name) != hash_size:
  2939. raise ValueError(
  2940. f"Object name has wrong length: expected {hash_size}, got {len(name)}"
  2941. )
  2942. fan_out_table[ord(name[:1])] += 1
  2943. # Fan-out table
  2944. largetable: list[int] = []
  2945. for i in range(0x100):
  2946. f.write(struct.pack(b">L", fan_out_table[i]))
  2947. fan_out_table[i + 1] += fan_out_table[i]
  2948. # Object names table
  2949. for name, offset, entry_checksum in entries_list:
  2950. f.write(name)
  2951. # CRC32 checksums table
  2952. for name, offset, entry_checksum in entries_list:
  2953. f.write(struct.pack(b">L", entry_checksum))
  2954. # Offset table
  2955. for name, offset, entry_checksum in entries_list:
  2956. if offset < 2**31:
  2957. f.write(struct.pack(b">L", offset))
  2958. else:
  2959. f.write(struct.pack(b">L", 2**31 + len(largetable)))
  2960. largetable.append(offset)
  2961. # Large offset table
  2962. for offset in largetable:
  2963. f.write(struct.pack(b">Q", offset))
  2964. assert len(pack_checksum) == hash_size, (
  2965. f"Pack checksum has wrong length: expected {hash_size}, got {len(pack_checksum)}"
  2966. )
  2967. f.write(pack_checksum)
  2968. return f.write_sha()
  2969. def write_pack_index(
  2970. f: IO[bytes],
  2971. entries: Iterable[tuple[bytes, int, int | None]],
  2972. pack_checksum: bytes,
  2973. progress: Callable[..., None] | None = None,
  2974. version: int | None = None,
  2975. ) -> bytes:
  2976. """Write a pack index file.
  2977. Args:
  2978. f: File-like object to write to.
  2979. entries: List of (checksum, offset, crc32) tuples
  2980. pack_checksum: Checksum of the pack file.
  2981. progress: Progress function (not currently used)
  2982. version: Pack index version to use (1, 2, or 3). If None, defaults to DEFAULT_PACK_INDEX_VERSION.
  2983. Returns:
  2984. SHA of the written index file
  2985. Raises:
  2986. ValueError: If an unsupported version is specified
  2987. """
  2988. if version is None:
  2989. version = DEFAULT_PACK_INDEX_VERSION
  2990. if version == 1:
  2991. return write_pack_index_v1(f, entries, pack_checksum)
  2992. elif version == 2:
  2993. return write_pack_index_v2(f, entries, pack_checksum)
  2994. elif version == 3:
  2995. return write_pack_index_v3(f, entries, pack_checksum)
  2996. else:
  2997. raise ValueError(f"Unsupported pack index version: {version}")
  2998. class Pack:
  2999. """A Git pack object."""
  3000. _data_load: Callable[[], PackData] | None
  3001. _idx_load: Callable[[], PackIndex] | None
  3002. _data: PackData | None
  3003. _idx: PackIndex | None
  3004. _bitmap: "PackBitmap | None"
  3005. def __init__(
  3006. self,
  3007. basename: str,
  3008. resolve_ext_ref: ResolveExtRefFn | None = None,
  3009. *,
  3010. delta_window_size: int | None = None,
  3011. window_memory: int | None = None,
  3012. delta_cache_size: int | None = None,
  3013. depth: int | None = None,
  3014. threads: int | None = None,
  3015. big_file_threshold: int | None = None,
  3016. object_format: ObjectFormat | None = None,
  3017. ) -> None:
  3018. """Initialize a Pack object.
  3019. Args:
  3020. basename: Base path for pack files (without .pack/.idx extension)
  3021. resolve_ext_ref: Optional function to resolve external references
  3022. delta_window_size: Size of the delta compression window
  3023. window_memory: Memory limit for delta compression window
  3024. delta_cache_size: Size of the delta cache
  3025. depth: Maximum depth for delta chains
  3026. threads: Number of threads to use for operations
  3027. big_file_threshold: Size threshold for big file handling
  3028. object_format: Hash algorithm to use (defaults to SHA1)
  3029. """
  3030. self._basename = basename
  3031. self._data = None
  3032. self._idx = None
  3033. self._bitmap = None
  3034. self._idx_path = self._basename + ".idx"
  3035. self._data_path = self._basename + ".pack"
  3036. self._bitmap_path = self._basename + ".bitmap"
  3037. self.delta_window_size = delta_window_size
  3038. self.window_memory = window_memory
  3039. self.delta_cache_size = delta_cache_size
  3040. self.depth = depth
  3041. self.threads = threads
  3042. self.big_file_threshold = big_file_threshold
  3043. self._data_load = lambda: PackData(
  3044. self._data_path,
  3045. delta_window_size=delta_window_size,
  3046. window_memory=window_memory,
  3047. delta_cache_size=delta_cache_size,
  3048. depth=depth,
  3049. threads=threads,
  3050. big_file_threshold=big_file_threshold,
  3051. )
  3052. self._idx_load = lambda: load_pack_index(
  3053. self._idx_path, object_format=object_format
  3054. )
  3055. self.resolve_ext_ref = resolve_ext_ref
  3056. # Always set object_format, defaulting to default
  3057. from .object_format import DEFAULT_OBJECT_FORMAT
  3058. self.object_format = object_format if object_format else DEFAULT_OBJECT_FORMAT
  3059. @classmethod
  3060. def from_lazy_objects(
  3061. cls, data_fn: Callable[[], PackData], idx_fn: Callable[[], PackIndex],
  3062. object_format: ObjectFormat | None = None
  3063. ) -> "Pack":
  3064. """Create a new pack object from callables to load pack data and index objects."""
  3065. ret = cls("", object_format=object_format)
  3066. ret._data_load = data_fn
  3067. ret._idx_load = idx_fn
  3068. return ret
  3069. @classmethod
  3070. def from_objects(cls, data: PackData, idx: PackIndex, object_format | ObjectFormat | None = None) -> "Pack":
  3071. """Create a new pack object from pack data and index objects."""
  3072. ret = cls("", object_format=object_format)
  3073. ret._data = data
  3074. ret._data_load = None
  3075. ret._idx = idx
  3076. ret._idx_load = None
  3077. ret.check_length_and_checksum()
  3078. return ret
  3079. def name(self) -> bytes:
  3080. """The SHA over the SHAs of the objects in this pack."""
  3081. return self.index.objects_sha1()
  3082. @property
  3083. def data(self) -> PackData:
  3084. """The pack data object being used."""
  3085. if self._data is None:
  3086. assert self._data_load
  3087. self._data = self._data_load()
  3088. self.check_length_and_checksum()
  3089. return self._data
  3090. @property
  3091. def index(self) -> PackIndex:
  3092. """The index being used.
  3093. Note: This may be an in-memory index
  3094. """
  3095. if self._idx is None:
  3096. assert self._idx_load
  3097. self._idx = self._idx_load()
  3098. return self._idx
  3099. @property
  3100. def bitmap(self) -> "PackBitmap | None":
  3101. """The bitmap being used, if available.
  3102. Returns:
  3103. PackBitmap instance or None if no bitmap exists
  3104. Raises:
  3105. ValueError: If bitmap file is invalid or corrupt
  3106. """
  3107. if self._bitmap is None:
  3108. from .bitmap import read_bitmap
  3109. self._bitmap = read_bitmap(self._bitmap_path, pack_index=self.index)
  3110. return self._bitmap
  3111. def ensure_bitmap(
  3112. self,
  3113. object_store: "BaseObjectStore",
  3114. refs: dict["Ref", "ObjectID"],
  3115. commit_interval: int | None = None,
  3116. progress: Callable[[str], None] | None = None,
  3117. ) -> "PackBitmap":
  3118. """Ensure a bitmap exists for this pack, generating one if needed.
  3119. Args:
  3120. object_store: Object store to read objects from
  3121. refs: Dictionary of ref names to commit SHAs
  3122. commit_interval: Include every Nth commit in bitmap index
  3123. progress: Optional progress reporting callback
  3124. Returns:
  3125. PackBitmap instance (either existing or newly generated)
  3126. """
  3127. from .bitmap import generate_bitmap, write_bitmap
  3128. # Check if bitmap already exists
  3129. try:
  3130. existing = self.bitmap
  3131. if existing is not None:
  3132. return existing
  3133. except FileNotFoundError:
  3134. pass # No bitmap, we'll generate one
  3135. # Generate new bitmap
  3136. if progress:
  3137. progress(f"Generating bitmap for {self.name().decode('utf-8')}...\n")
  3138. pack_bitmap = generate_bitmap(
  3139. self.index,
  3140. object_store,
  3141. refs,
  3142. self.get_stored_checksum(),
  3143. commit_interval=commit_interval,
  3144. progress=progress,
  3145. )
  3146. # Write bitmap file
  3147. write_bitmap(self._bitmap_path, pack_bitmap)
  3148. if progress:
  3149. progress(f"Wrote {self._bitmap_path}\n")
  3150. # Update cached bitmap
  3151. self._bitmap = pack_bitmap
  3152. return pack_bitmap
  3153. def close(self) -> None:
  3154. """Close the pack file and index."""
  3155. if self._data is not None:
  3156. self._data.close()
  3157. if self._idx is not None:
  3158. self._idx.close()
  3159. def __enter__(self) -> "Pack":
  3160. """Enter context manager."""
  3161. return self
  3162. def __exit__(
  3163. self,
  3164. exc_type: type | None,
  3165. exc_val: BaseException | None,
  3166. exc_tb: TracebackType | None,
  3167. ) -> None:
  3168. """Exit context manager."""
  3169. self.close()
  3170. def __eq__(self, other: object) -> bool:
  3171. """Check equality with another pack."""
  3172. if not isinstance(other, Pack):
  3173. return False
  3174. return self.index == other.index
  3175. def __len__(self) -> int:
  3176. """Number of entries in this pack."""
  3177. return len(self.index)
  3178. def __repr__(self) -> str:
  3179. """Return string representation of this pack."""
  3180. return f"{self.__class__.__name__}({self._basename!r})"
  3181. def __iter__(self) -> Iterator[ObjectID]:
  3182. """Iterate over all the sha1s of the objects in this pack."""
  3183. return iter(self.index)
  3184. def check_length_and_checksum(self) -> None:
  3185. """Sanity check the length and checksum of the pack index and data."""
  3186. assert len(self.index) == len(self.data), (
  3187. f"Length mismatch: {len(self.index)} (index) != {len(self.data)} (data)"
  3188. )
  3189. idx_stored_checksum = self.index.get_pack_checksum()
  3190. data_stored_checksum = self.data.get_stored_checksum()
  3191. if (
  3192. idx_stored_checksum is not None
  3193. and idx_stored_checksum != data_stored_checksum
  3194. ):
  3195. raise ChecksumMismatch(
  3196. sha_to_hex(RawObjectID(idx_stored_checksum)),
  3197. sha_to_hex(RawObjectID(data_stored_checksum)),
  3198. )
  3199. def check(self) -> None:
  3200. """Check the integrity of this pack.
  3201. Raises:
  3202. ChecksumMismatch: if a checksum for the index or data is wrong
  3203. """
  3204. self.index.check()
  3205. self.data.check()
  3206. for obj in self.iterobjects():
  3207. obj.check()
  3208. # TODO: object connectivity checks
  3209. def get_stored_checksum(self) -> bytes:
  3210. """Return the stored checksum of the pack data."""
  3211. return self.data.get_stored_checksum()
  3212. def pack_tuples(self) -> list[tuple[ShaFile, None]]:
  3213. """Return pack tuples for all objects in pack."""
  3214. return [(o, None) for o in self.iterobjects()]
  3215. def __contains__(self, sha1: ObjectID | RawObjectID) -> bool:
  3216. """Check whether this pack contains a particular SHA1."""
  3217. try:
  3218. self.index.object_offset(sha1)
  3219. return True
  3220. except KeyError:
  3221. return False
  3222. def get_raw(self, sha1: RawObjectID | ObjectID) -> tuple[int, bytes]:
  3223. """Get raw object data by SHA1."""
  3224. offset = self.index.object_offset(sha1)
  3225. obj_type, obj = self.data.get_object_at(offset)
  3226. type_num, chunks = self.resolve_object(offset, obj_type, obj)
  3227. return type_num, b"".join(chunks) # type: ignore[arg-type]
  3228. def __getitem__(self, sha1: "ObjectID | RawObjectID") -> ShaFile:
  3229. """Retrieve the specified SHA1."""
  3230. type, uncomp = self.get_raw(sha1)
  3231. return ShaFile.from_raw_string(type, uncomp, sha=sha1)
  3232. def iterobjects(self) -> Iterator[ShaFile]:
  3233. """Iterate over the objects in this pack."""
  3234. return iter(
  3235. PackInflater.for_pack_data(self.data, resolve_ext_ref=self.resolve_ext_ref)
  3236. )
  3237. def iterobjects_subset(
  3238. self, shas: Iterable[ObjectID], *, allow_missing: bool = False
  3239. ) -> Iterator[ShaFile]:
  3240. """Iterate over a subset of objects in this pack."""
  3241. return (
  3242. uo
  3243. for uo in PackInflater.for_pack_subset(
  3244. self,
  3245. shas,
  3246. allow_missing=allow_missing,
  3247. resolve_ext_ref=self.resolve_ext_ref,
  3248. )
  3249. if uo.id in shas
  3250. )
  3251. def iter_unpacked_subset(
  3252. self,
  3253. shas: Iterable[ObjectID | RawObjectID],
  3254. *,
  3255. include_comp: bool = False,
  3256. allow_missing: bool = False,
  3257. convert_ofs_delta: bool = False,
  3258. ) -> Iterator[UnpackedObject]:
  3259. """Iterate over unpacked objects in subset."""
  3260. ofs_pending: dict[int, list[UnpackedObject]] = defaultdict(list)
  3261. ofs: dict[int, bytes] = {}
  3262. todo: set[ObjectID | RawObjectID] = set(shas)
  3263. for unpacked in self.iter_unpacked(include_comp=include_comp):
  3264. sha = unpacked.sha()
  3265. if unpacked.offset is not None:
  3266. ofs[unpacked.offset] = sha
  3267. hexsha = sha_to_hex(RawObjectID(sha))
  3268. if hexsha in todo:
  3269. if unpacked.pack_type_num == OFS_DELTA:
  3270. assert isinstance(unpacked.delta_base, int)
  3271. assert unpacked.offset is not None
  3272. base_offset = unpacked.offset - unpacked.delta_base
  3273. try:
  3274. unpacked.delta_base = ofs[base_offset]
  3275. except KeyError:
  3276. ofs_pending[base_offset].append(unpacked)
  3277. continue
  3278. else:
  3279. unpacked.pack_type_num = REF_DELTA
  3280. yield unpacked
  3281. todo.remove(hexsha)
  3282. if unpacked.offset is not None:
  3283. for child in ofs_pending.pop(unpacked.offset, []):
  3284. child.pack_type_num = REF_DELTA
  3285. child.delta_base = sha
  3286. yield child
  3287. assert not ofs_pending
  3288. if not allow_missing and todo:
  3289. raise UnresolvedDeltas(list(todo))
  3290. def iter_unpacked(self, include_comp: bool = False) -> Iterator[UnpackedObject]:
  3291. """Iterate over all unpacked objects in this pack."""
  3292. ofs_to_entries = {
  3293. ofs: (sha, crc32) for (sha, ofs, crc32) in self.index.iterentries()
  3294. }
  3295. for unpacked in self.data.iter_unpacked(include_comp=include_comp):
  3296. assert unpacked.offset is not None
  3297. (sha, crc32) = ofs_to_entries[unpacked.offset]
  3298. unpacked._sha = sha
  3299. unpacked.crc32 = crc32
  3300. yield unpacked
  3301. def keep(self, msg: bytes | None = None) -> str:
  3302. """Add a .keep file for the pack, preventing git from garbage collecting it.
  3303. Args:
  3304. msg: A message written inside the .keep file; can be used later
  3305. to determine whether or not a .keep file is obsolete.
  3306. Returns: The path of the .keep file, as a string.
  3307. """
  3308. keepfile_name = f"{self._basename}.keep"
  3309. with GitFile(keepfile_name, "wb") as keepfile:
  3310. if msg:
  3311. keepfile.write(msg)
  3312. keepfile.write(b"\n")
  3313. return keepfile_name
  3314. def get_ref(
  3315. self, sha: RawObjectID | ObjectID
  3316. ) -> tuple[int | None, int, OldUnpackedObject]:
  3317. """Get the object for a ref SHA, only looking in this pack."""
  3318. # TODO: cache these results
  3319. try:
  3320. offset = self.index.object_offset(sha)
  3321. except KeyError:
  3322. offset = None
  3323. if offset:
  3324. type, obj = self.data.get_object_at(offset)
  3325. elif self.resolve_ext_ref:
  3326. type, obj = self.resolve_ext_ref(sha)
  3327. else:
  3328. raise KeyError(sha)
  3329. return offset, type, obj
  3330. def resolve_object(
  3331. self,
  3332. offset: int,
  3333. type: int,
  3334. obj: OldUnpackedObject,
  3335. get_ref: Callable[
  3336. [RawObjectID | ObjectID], tuple[int | None, int, OldUnpackedObject]
  3337. ]
  3338. | None = None,
  3339. ) -> tuple[int, OldUnpackedObject]:
  3340. """Resolve an object, possibly resolving deltas when necessary.
  3341. Returns: Tuple with object type and contents.
  3342. """
  3343. # Walk down the delta chain, building a stack of deltas to reach
  3344. # the requested object.
  3345. base_offset: int | None = offset
  3346. base_type = type
  3347. base_obj = obj
  3348. delta_stack = []
  3349. while base_type in DELTA_TYPES:
  3350. prev_offset = base_offset
  3351. if get_ref is None:
  3352. get_ref = self.get_ref
  3353. if base_type == OFS_DELTA:
  3354. (delta_offset, delta) = base_obj
  3355. # TODO: clean up asserts and replace with nicer error messages
  3356. assert isinstance(delta_offset, int), (
  3357. f"Expected int, got {delta_offset.__class__}"
  3358. )
  3359. assert base_offset is not None
  3360. base_offset = base_offset - delta_offset
  3361. base_type, base_obj = self.data.get_object_at(base_offset)
  3362. assert isinstance(base_type, int)
  3363. elif base_type == REF_DELTA:
  3364. (basename, delta) = base_obj
  3365. assert isinstance(basename, bytes) and len(basename) == 20
  3366. base_offset, base_type, base_obj = get_ref(cast(RawObjectID, basename))
  3367. assert isinstance(base_type, int)
  3368. if base_offset == prev_offset: # object is based on itself
  3369. raise UnresolvedDeltas([basename])
  3370. delta_stack.append((prev_offset, base_type, delta))
  3371. # Now grab the base object (mustn't be a delta) and apply the
  3372. # deltas all the way up the stack.
  3373. chunks = base_obj
  3374. for prev_offset, _delta_type, delta in reversed(delta_stack):
  3375. # Convert chunks to bytes for apply_delta if needed
  3376. if isinstance(chunks, list):
  3377. chunks_bytes = b"".join(chunks)
  3378. elif isinstance(chunks, tuple):
  3379. # For tuple type, second element is the actual data
  3380. _, chunk_data = chunks
  3381. if isinstance(chunk_data, list):
  3382. chunks_bytes = b"".join(chunk_data)
  3383. else:
  3384. chunks_bytes = chunk_data
  3385. else:
  3386. chunks_bytes = chunks
  3387. # Apply delta and get result as list
  3388. chunks = apply_delta(chunks_bytes, delta)
  3389. if prev_offset is not None:
  3390. self.data._offset_cache[prev_offset] = base_type, chunks
  3391. return base_type, chunks
  3392. def entries(
  3393. self, progress: ProgressFn | None = None
  3394. ) -> Iterator[PackIndexEntry]:
  3395. """Yield entries summarizing the contents of this pack.
  3396. Args:
  3397. progress: Progress function, called with current and total
  3398. object count.
  3399. Returns: iterator of tuples with (sha, offset, crc32)
  3400. """
  3401. return self.data.iterentries(
  3402. progress=progress, resolve_ext_ref=self.resolve_ext_ref
  3403. )
  3404. def sorted_entries(
  3405. self, progress: ProgressFn | None = None
  3406. ) -> Iterator[PackIndexEntry]:
  3407. """Return entries in this pack, sorted by SHA.
  3408. Args:
  3409. progress: Progress function, called with current and total
  3410. object count
  3411. Returns: Iterator of tuples with (sha, offset, crc32)
  3412. """
  3413. return iter(
  3414. self.data.sorted_entries(
  3415. progress=progress, resolve_ext_ref=self.resolve_ext_ref
  3416. )
  3417. )
  3418. def get_unpacked_object(
  3419. self,
  3420. sha: ObjectID | RawObjectID,
  3421. *,
  3422. include_comp: bool = False,
  3423. convert_ofs_delta: bool = True,
  3424. ) -> UnpackedObject:
  3425. """Get the unpacked object for a sha.
  3426. Args:
  3427. sha: SHA of object to fetch
  3428. include_comp: Whether to include compression data in UnpackedObject
  3429. convert_ofs_delta: Whether to convert offset deltas to ref deltas
  3430. """
  3431. offset = self.index.object_offset(sha)
  3432. unpacked = self.data.get_unpacked_object_at(offset, include_comp=include_comp)
  3433. if unpacked.pack_type_num == OFS_DELTA and convert_ofs_delta:
  3434. assert isinstance(unpacked.delta_base, int)
  3435. unpacked.delta_base = self.index.object_sha1(offset - unpacked.delta_base)
  3436. unpacked.pack_type_num = REF_DELTA
  3437. return unpacked
  3438. def extend_pack(
  3439. f: BinaryIO,
  3440. object_ids: Set["RawObjectID"],
  3441. get_raw: Callable[["RawObjectID | ObjectID"], tuple[int, bytes]],
  3442. *,
  3443. compression_level: int = -1,
  3444. progress: Callable[[bytes], None] | None = None,
  3445. ) -> tuple[bytes, list[tuple["RawObjectID", int, int]]]:
  3446. """Extend a pack file with more objects.
  3447. The caller should make sure that object_ids does not contain any objects
  3448. that are already in the pack
  3449. """
  3450. # Update the header with the new number of objects.
  3451. f.seek(0)
  3452. _version, num_objects = read_pack_header(f.read)
  3453. if object_ids:
  3454. f.seek(0)
  3455. write_pack_header(f.write, num_objects + len(object_ids))
  3456. # Must flush before reading (http://bugs.python.org/issue3207)
  3457. f.flush()
  3458. # Rescan the rest of the pack, computing the SHA with the new header.
  3459. new_sha = compute_file_sha(f, end_ofs=-20)
  3460. # Must reposition before writing (http://bugs.python.org/issue3207)
  3461. f.seek(0, os.SEEK_CUR)
  3462. extra_entries = []
  3463. # Complete the pack.
  3464. for i, object_id in enumerate(object_ids):
  3465. if progress is not None:
  3466. progress(
  3467. (f"writing extra base objects: {i}/{len(object_ids)}\r").encode("ascii")
  3468. )
  3469. assert len(object_id) == 20
  3470. type_num, data = get_raw(object_id)
  3471. offset = f.tell()
  3472. crc32 = write_pack_object(
  3473. f.write,
  3474. type_num,
  3475. [data], # Convert bytes to list[bytes]
  3476. sha=new_sha,
  3477. compression_level=compression_level,
  3478. )
  3479. extra_entries.append((object_id, offset, crc32))
  3480. pack_sha = new_sha.digest()
  3481. f.write(pack_sha)
  3482. return pack_sha, extra_entries
  3483. try:
  3484. from dulwich._pack import ( # type: ignore
  3485. apply_delta,
  3486. bisect_find_sha,
  3487. )
  3488. except ImportError:
  3489. pass
  3490. # Try to import the Rust version of create_delta
  3491. try:
  3492. from dulwich._pack import create_delta as _create_delta_rs
  3493. except ImportError:
  3494. pass
  3495. else:
  3496. # Wrap the Rust version to match the Python API (returns bytes instead of Iterator)
  3497. def _create_delta_rs_wrapper(base_buf: bytes, target_buf: bytes) -> Iterator[bytes]:
  3498. """Wrapper for Rust create_delta to match Python API."""
  3499. yield _create_delta_rs(base_buf, target_buf)
  3500. create_delta = _create_delta_rs_wrapper