pack.py 124 KB

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