pack.py 145 KB

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