pack.py 119 KB

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