pack.py 129 KB

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