pack.py 124 KB

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