pack.py 120 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675
  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: Callable, read_some: Callable, outfile: Any, delta_iter: Optional[Any] = 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: Callable, size: int) -> bytes:
  1121. """Read data from the read callback and write it to the file."""
  1122. data = super()._read(read, size)
  1123. self.outfile.write(data)
  1124. return data
  1125. def verify(self, progress: Optional[Callable] = None) -> None:
  1126. """Verify a pack stream and write it to the output file.
  1127. See PackStreamReader.iterobjects for a list of exceptions this may
  1128. throw.
  1129. """
  1130. i = 0 # default count of entries if read_objects() is empty
  1131. for i, unpacked in enumerate(self.read_objects()):
  1132. if self._delta_iter:
  1133. self._delta_iter.record(unpacked)
  1134. if progress is not None:
  1135. progress(f"copying pack entries: {i}/{len(self)}\r".encode("ascii"))
  1136. if progress is not None:
  1137. progress(f"copied {i} pack entries\n".encode("ascii"))
  1138. def obj_sha(type: int, chunks: Union[bytes, Iterable[bytes]]) -> bytes:
  1139. """Compute the SHA for a numeric type and object chunks."""
  1140. sha = sha1()
  1141. sha.update(object_header(type, chunks_length(chunks)))
  1142. if isinstance(chunks, bytes):
  1143. sha.update(chunks)
  1144. else:
  1145. for chunk in chunks:
  1146. sha.update(chunk)
  1147. return sha.digest()
  1148. def compute_file_sha(f: IO[bytes], start_ofs: int = 0, end_ofs: int = 0, buffer_size: int = 1 << 16) -> "sha1":
  1149. """Hash a portion of a file into a new SHA.
  1150. Args:
  1151. f: A file-like object to read from that supports seek().
  1152. start_ofs: The offset in the file to start reading at.
  1153. end_ofs: The offset in the file to end reading at, relative to the
  1154. end of the file.
  1155. buffer_size: A buffer size for reading.
  1156. Returns: A new SHA object updated with data read from the file.
  1157. """
  1158. sha = sha1()
  1159. f.seek(0, SEEK_END)
  1160. length = f.tell()
  1161. if (end_ofs < 0 and length + end_ofs < start_ofs) or end_ofs > length:
  1162. raise AssertionError(
  1163. f"Attempt to read beyond file length. start_ofs: {start_ofs}, end_ofs: {end_ofs}, file length: {length}"
  1164. )
  1165. todo = length + end_ofs - start_ofs
  1166. f.seek(start_ofs)
  1167. while todo:
  1168. data = f.read(min(todo, buffer_size))
  1169. sha.update(data)
  1170. todo -= len(data)
  1171. return sha
  1172. class PackData:
  1173. """The data contained in a packfile.
  1174. Pack files can be accessed both sequentially for exploding a pack, and
  1175. directly with the help of an index to retrieve a specific object.
  1176. The objects within are either complete or a delta against another.
  1177. The header is variable length. If the MSB of each byte is set then it
  1178. indicates that the subsequent byte is still part of the header.
  1179. For the first byte the next MS bits are the type, which tells you the type
  1180. of object, and whether it is a delta. The LS byte is the lowest bits of the
  1181. size. For each subsequent byte the LS 7 bits are the next MS bits of the
  1182. size, i.e. the last byte of the header contains the MS bits of the size.
  1183. For the complete objects the data is stored as zlib deflated data.
  1184. The size in the header is the uncompressed object size, so to uncompress
  1185. you need to just keep feeding data to zlib until you get an object back,
  1186. or it errors on bad data. This is done here by just giving the complete
  1187. buffer from the start of the deflated object on. This is bad, but until I
  1188. get mmap sorted out it will have to do.
  1189. Currently there are no integrity checks done. Also no attempt is made to
  1190. try and detect the delta case, or a request for an object at the wrong
  1191. position. It will all just throw a zlib or KeyError.
  1192. """
  1193. def __init__(
  1194. self,
  1195. filename: Union[str, os.PathLike],
  1196. file: Optional[Any] = None,
  1197. size: Optional[int] = None,
  1198. *,
  1199. delta_window_size: Optional[int] = None,
  1200. window_memory: Optional[int] = None,
  1201. delta_cache_size: Optional[int] = None,
  1202. depth: Optional[int] = None,
  1203. threads: Optional[int] = None,
  1204. big_file_threshold: Optional[int] = None,
  1205. ) -> None:
  1206. """Create a PackData object representing the pack in the given filename.
  1207. The file must exist and stay readable until the object is disposed of.
  1208. It must also stay the same size. It will be mapped whenever needed.
  1209. Currently there is a restriction on the size of the pack as the python
  1210. mmap implementation is flawed.
  1211. """
  1212. self._filename = filename
  1213. self._size = size
  1214. self._header_size = 12
  1215. self.delta_window_size = delta_window_size
  1216. self.window_memory = window_memory
  1217. self.delta_cache_size = delta_cache_size
  1218. self.depth = depth
  1219. self.threads = threads
  1220. self.big_file_threshold = big_file_threshold
  1221. if file is None:
  1222. self._file = GitFile(self._filename, "rb")
  1223. else:
  1224. self._file = file
  1225. (version, self._num_objects) = read_pack_header(self._file.read)
  1226. # Use delta_cache_size config if available, otherwise default
  1227. cache_size = delta_cache_size or (1024 * 1024 * 20)
  1228. self._offset_cache = LRUSizeCache[int, tuple[int, OldUnpackedObject]](
  1229. cache_size, compute_size=_compute_object_size
  1230. )
  1231. @property
  1232. def filename(self) -> str:
  1233. """Get the filename of the pack file.
  1234. Returns:
  1235. Base filename without directory path
  1236. """
  1237. return os.path.basename(self._filename)
  1238. @property
  1239. def path(self) -> str:
  1240. """Get the full path of the pack file.
  1241. Returns:
  1242. Full path to the pack file
  1243. """
  1244. return self._filename
  1245. @classmethod
  1246. def from_file(cls, file: Any, size: Optional[int] = None) -> 'PackData':
  1247. """Create a PackData object from an open file.
  1248. Args:
  1249. file: Open file object
  1250. size: Optional file size
  1251. Returns:
  1252. PackData instance
  1253. """
  1254. return cls(str(file), file=file, size=size)
  1255. @classmethod
  1256. def from_path(cls, path: Union[str, os.PathLike]) -> 'PackData':
  1257. """Create a PackData object from a file path.
  1258. Args:
  1259. path: Path to the pack file
  1260. Returns:
  1261. PackData instance
  1262. """
  1263. return cls(filename=path)
  1264. def close(self) -> None:
  1265. """Close the underlying pack file."""
  1266. self._file.close()
  1267. def __enter__(self) -> 'PackData':
  1268. """Enter context manager."""
  1269. return self
  1270. def __exit__(self, exc_type: Optional[type], exc_val: Optional[BaseException], exc_tb: Optional[Any]) -> None:
  1271. """Exit context manager."""
  1272. self.close()
  1273. def __eq__(self, other: Any) -> bool:
  1274. if isinstance(other, PackData):
  1275. return self.get_stored_checksum() == other.get_stored_checksum()
  1276. return False
  1277. def _get_size(self) -> int:
  1278. if self._size is not None:
  1279. return self._size
  1280. self._size = os.path.getsize(self._filename)
  1281. if self._size < self._header_size:
  1282. errmsg = f"{self._filename} is too small for a packfile ({self._size} < {self._header_size})"
  1283. raise AssertionError(errmsg)
  1284. return self._size
  1285. def __len__(self) -> int:
  1286. """Returns the number of objects in this pack."""
  1287. return self._num_objects
  1288. def calculate_checksum(self) -> bytes:
  1289. """Calculate the checksum for this pack.
  1290. Returns: 20-byte binary SHA1 digest
  1291. """
  1292. return compute_file_sha(self._file, end_ofs=-20).digest()
  1293. def iter_unpacked(self, *, include_comp: bool = False) -> Any:
  1294. self._file.seek(self._header_size)
  1295. if self._num_objects is None:
  1296. return
  1297. for _ in range(self._num_objects):
  1298. offset = self._file.tell()
  1299. unpacked, unused = unpack_object(
  1300. self._file.read, compute_crc32=False, include_comp=include_comp
  1301. )
  1302. unpacked.offset = offset
  1303. yield unpacked
  1304. # Back up over unused data.
  1305. self._file.seek(-len(unused), SEEK_CUR)
  1306. def iterentries(
  1307. self, progress=None, resolve_ext_ref: Optional[ResolveExtRefFn] = None
  1308. ):
  1309. """Yield entries summarizing the contents of this pack.
  1310. Args:
  1311. progress: Progress function, called with current and total
  1312. object count.
  1313. resolve_ext_ref: Optional function to resolve external references
  1314. Returns: iterator of tuples with (sha, offset, crc32)
  1315. """
  1316. num_objects = self._num_objects
  1317. indexer = PackIndexer.for_pack_data(self, resolve_ext_ref=resolve_ext_ref)
  1318. for i, result in enumerate(indexer):
  1319. if progress is not None:
  1320. progress(i, num_objects)
  1321. yield result
  1322. def sorted_entries(
  1323. self,
  1324. progress: Optional[ProgressFn] = None,
  1325. resolve_ext_ref: Optional[ResolveExtRefFn] = None,
  1326. ) -> Any:
  1327. """Return entries in this pack, sorted by SHA.
  1328. Args:
  1329. progress: Progress function, called with current and total
  1330. object count
  1331. resolve_ext_ref: Optional function to resolve external references
  1332. Returns: Iterator of tuples with (sha, offset, crc32)
  1333. """
  1334. return sorted(
  1335. self.iterentries(progress=progress, resolve_ext_ref=resolve_ext_ref)
  1336. )
  1337. def create_index_v1(self, filename: str, progress: Optional[Callable] = None, resolve_ext_ref: Optional[Callable] = None) -> bytes:
  1338. """Create a version 1 file for this data file.
  1339. Args:
  1340. filename: Index filename.
  1341. progress: Progress report function
  1342. resolve_ext_ref: Optional function to resolve external references
  1343. Returns: Checksum of index file
  1344. """
  1345. entries = self.sorted_entries(
  1346. progress=progress, resolve_ext_ref=resolve_ext_ref
  1347. )
  1348. with GitFile(filename, "wb") as f:
  1349. return write_pack_index_v1(f, entries, self.calculate_checksum())
  1350. def create_index_v2(self, filename: str, progress: Optional[Callable] = None, resolve_ext_ref: Optional[Callable] = None) -> bytes:
  1351. """Create a version 2 index file for this data file.
  1352. Args:
  1353. filename: Index filename.
  1354. progress: Progress report function
  1355. resolve_ext_ref: Optional function to resolve external references
  1356. Returns: Checksum of index file
  1357. """
  1358. entries = self.sorted_entries(
  1359. progress=progress, resolve_ext_ref=resolve_ext_ref
  1360. )
  1361. with GitFile(filename, "wb") as f:
  1362. return write_pack_index_v2(f, entries, self.calculate_checksum())
  1363. def create_index_v3(
  1364. self, filename: str, progress: Optional[Callable] = None, resolve_ext_ref: Optional[Callable] = None, hash_algorithm: int = 1
  1365. ) -> bytes:
  1366. """Create a version 3 index file for this data file.
  1367. Args:
  1368. filename: Index filename.
  1369. progress: Progress report function
  1370. resolve_ext_ref: Function to resolve external references
  1371. hash_algorithm: Hash algorithm identifier (1 = SHA-1, 2 = SHA-256)
  1372. Returns: Checksum of index file
  1373. """
  1374. entries = self.sorted_entries(
  1375. progress=progress, resolve_ext_ref=resolve_ext_ref
  1376. )
  1377. with GitFile(filename, "wb") as f:
  1378. return write_pack_index_v3(
  1379. f, entries, self.calculate_checksum(), hash_algorithm
  1380. )
  1381. def create_index(
  1382. self, filename: str, progress: Optional[Callable] = None, version: int = 2, resolve_ext_ref: Optional[Callable] = None, hash_algorithm: int = 1
  1383. ) -> bytes:
  1384. """Create an index file for this data file.
  1385. Args:
  1386. filename: Index filename.
  1387. progress: Progress report function
  1388. version: Index version (1, 2, or 3)
  1389. resolve_ext_ref: Function to resolve external references
  1390. hash_algorithm: Hash algorithm identifier for v3 (1 = SHA-1, 2 = SHA-256)
  1391. Returns: Checksum of index file
  1392. """
  1393. if version == 1:
  1394. return self.create_index_v1(
  1395. filename, progress, resolve_ext_ref=resolve_ext_ref
  1396. )
  1397. elif version == 2:
  1398. return self.create_index_v2(
  1399. filename, progress, resolve_ext_ref=resolve_ext_ref
  1400. )
  1401. elif version == 3:
  1402. return self.create_index_v3(
  1403. filename,
  1404. progress,
  1405. resolve_ext_ref=resolve_ext_ref,
  1406. hash_algorithm=hash_algorithm,
  1407. )
  1408. else:
  1409. raise ValueError(f"unknown index format {version}")
  1410. def get_stored_checksum(self) -> bytes:
  1411. """Return the expected checksum stored in this pack."""
  1412. self._file.seek(-20, SEEK_END)
  1413. return self._file.read(20)
  1414. def check(self) -> None:
  1415. """Check the consistency of this pack."""
  1416. actual = self.calculate_checksum()
  1417. stored = self.get_stored_checksum()
  1418. if actual != stored:
  1419. raise ChecksumMismatch(stored, actual)
  1420. def get_unpacked_object_at(
  1421. self, offset: int, *, include_comp: bool = False
  1422. ) -> UnpackedObject:
  1423. """Given offset in the packfile return a UnpackedObject."""
  1424. assert offset >= self._header_size
  1425. self._file.seek(offset)
  1426. unpacked, _ = unpack_object(self._file.read, include_comp=include_comp)
  1427. unpacked.offset = offset
  1428. return unpacked
  1429. def get_object_at(self, offset: int) -> tuple[int, OldUnpackedObject]:
  1430. """Given an offset in to the packfile return the object that is there.
  1431. Using the associated index the location of an object can be looked up,
  1432. and then the packfile can be asked directly for that object using this
  1433. function.
  1434. """
  1435. try:
  1436. return self._offset_cache[offset]
  1437. except KeyError:
  1438. pass
  1439. unpacked = self.get_unpacked_object_at(offset, include_comp=False)
  1440. return (unpacked.pack_type_num, unpacked._obj())
  1441. T = TypeVar("T")
  1442. class DeltaChainIterator(Generic[T]):
  1443. """Abstract iterator over pack data based on delta chains.
  1444. Each object in the pack is guaranteed to be inflated exactly once,
  1445. regardless of how many objects reference it as a delta base. As a result,
  1446. memory usage is proportional to the length of the longest delta chain.
  1447. Subclasses can override _result to define the result type of the iterator.
  1448. By default, results are UnpackedObjects with the following members set:
  1449. * offset
  1450. * obj_type_num
  1451. * obj_chunks
  1452. * pack_type_num
  1453. * delta_base (for delta types)
  1454. * comp_chunks (if _include_comp is True)
  1455. * decomp_chunks
  1456. * decomp_len
  1457. * crc32 (if _compute_crc32 is True)
  1458. """
  1459. _compute_crc32 = False
  1460. _include_comp = False
  1461. def __init__(self, file_obj, *, resolve_ext_ref=None) -> None:
  1462. """Initialize DeltaChainIterator.
  1463. Args:
  1464. file_obj: File object to read pack data from
  1465. resolve_ext_ref: Optional function to resolve external references
  1466. """
  1467. def __init__(self, file_obj: Any, *, resolve_ext_ref: Optional[Callable] = None) -> None:
  1468. self._file = file_obj
  1469. self._resolve_ext_ref = resolve_ext_ref
  1470. self._pending_ofs: dict[int, list[int]] = defaultdict(list)
  1471. self._pending_ref: dict[bytes, list[int]] = defaultdict(list)
  1472. self._full_ofs: list[tuple[int, int]] = []
  1473. self._ext_refs: list[bytes] = []
  1474. @classmethod
  1475. def for_pack_data(cls, pack_data: PackData, resolve_ext_ref: Optional[Callable] = None) -> 'DeltaChainIterator':
  1476. """Create a DeltaChainIterator from pack data.
  1477. Args:
  1478. pack_data: PackData object to iterate
  1479. resolve_ext_ref: Optional function to resolve external refs
  1480. Returns:
  1481. DeltaChainIterator instance
  1482. """
  1483. walker = cls(None, resolve_ext_ref=resolve_ext_ref)
  1484. walker.set_pack_data(pack_data)
  1485. for unpacked in pack_data.iter_unpacked(include_comp=False):
  1486. walker.record(unpacked)
  1487. return walker
  1488. @classmethod
  1489. def for_pack_subset(
  1490. cls,
  1491. pack: "Pack",
  1492. shas: Iterable[bytes],
  1493. *,
  1494. allow_missing: bool = False,
  1495. resolve_ext_ref: Optional[Callable] = None,
  1496. ) -> 'DeltaChainIterator':
  1497. """Create a DeltaChainIterator for a subset of objects.
  1498. Args:
  1499. pack: Pack object containing the data
  1500. shas: Iterable of object SHAs to include
  1501. allow_missing: If True, skip missing objects
  1502. resolve_ext_ref: Optional function to resolve external refs
  1503. Returns:
  1504. DeltaChainIterator instance
  1505. """
  1506. walker = cls(None, resolve_ext_ref=resolve_ext_ref)
  1507. walker.set_pack_data(pack.data)
  1508. todo = set()
  1509. for sha in shas:
  1510. assert isinstance(sha, bytes)
  1511. try:
  1512. off = pack.index.object_offset(sha)
  1513. except KeyError:
  1514. if not allow_missing:
  1515. raise
  1516. else:
  1517. todo.add(off)
  1518. done = set()
  1519. while todo:
  1520. off = todo.pop()
  1521. unpacked = pack.data.get_unpacked_object_at(off)
  1522. walker.record(unpacked)
  1523. done.add(off)
  1524. base_ofs = None
  1525. if unpacked.pack_type_num == OFS_DELTA:
  1526. assert unpacked.offset is not None
  1527. assert unpacked.delta_base is not None
  1528. assert isinstance(unpacked.delta_base, int)
  1529. base_ofs = unpacked.offset - unpacked.delta_base
  1530. elif unpacked.pack_type_num == REF_DELTA:
  1531. with suppress(KeyError):
  1532. assert isinstance(unpacked.delta_base, bytes)
  1533. base_ofs = pack.index.object_index(unpacked.delta_base)
  1534. if base_ofs is not None and base_ofs not in done:
  1535. todo.add(base_ofs)
  1536. return walker
  1537. def record(self, unpacked: UnpackedObject) -> None:
  1538. """Record an unpacked object for later processing.
  1539. Args:
  1540. unpacked: UnpackedObject to record
  1541. """
  1542. type_num = unpacked.pack_type_num
  1543. offset = unpacked.offset
  1544. assert offset is not None
  1545. if type_num == OFS_DELTA:
  1546. assert unpacked.delta_base is not None
  1547. assert isinstance(unpacked.delta_base, int)
  1548. base_offset = offset - unpacked.delta_base
  1549. self._pending_ofs[base_offset].append(offset)
  1550. elif type_num == REF_DELTA:
  1551. assert isinstance(unpacked.delta_base, bytes)
  1552. self._pending_ref[unpacked.delta_base].append(offset)
  1553. else:
  1554. self._full_ofs.append((offset, type_num))
  1555. def set_pack_data(self, pack_data: PackData) -> None:
  1556. """Set the pack data for iteration.
  1557. Args:
  1558. pack_data: PackData object to use
  1559. """
  1560. self._file = pack_data._file
  1561. def _walk_all_chains(self) -> Any:
  1562. for offset, type_num in self._full_ofs:
  1563. yield from self._follow_chain(offset, type_num, None)
  1564. yield from self._walk_ref_chains()
  1565. assert not self._pending_ofs, repr(self._pending_ofs)
  1566. def _ensure_no_pending(self) -> None:
  1567. if self._pending_ref:
  1568. raise UnresolvedDeltas([sha_to_hex(s) for s in self._pending_ref])
  1569. def _walk_ref_chains(self) -> Any:
  1570. if not self._resolve_ext_ref:
  1571. self._ensure_no_pending()
  1572. return
  1573. for base_sha, pending in sorted(self._pending_ref.items()):
  1574. if base_sha not in self._pending_ref:
  1575. continue
  1576. try:
  1577. type_num, chunks = self._resolve_ext_ref(base_sha)
  1578. except KeyError:
  1579. # Not an external ref, but may depend on one. Either it will
  1580. # get popped via a _follow_chain call, or we will raise an
  1581. # error below.
  1582. continue
  1583. self._ext_refs.append(base_sha)
  1584. self._pending_ref.pop(base_sha)
  1585. for new_offset in pending:
  1586. yield from self._follow_chain(new_offset, type_num, chunks)
  1587. self._ensure_no_pending()
  1588. def _result(self, unpacked: UnpackedObject) -> Any:
  1589. raise NotImplementedError
  1590. def _resolve_object(
  1591. self, offset: int, obj_type_num: int, base_chunks: Optional[list[bytes]]
  1592. ) -> UnpackedObject:
  1593. self._file.seek(offset)
  1594. unpacked, _ = unpack_object(
  1595. self._file.read,
  1596. include_comp=self._include_comp,
  1597. compute_crc32=self._compute_crc32,
  1598. )
  1599. unpacked.offset = offset
  1600. if base_chunks is None:
  1601. assert unpacked.pack_type_num == obj_type_num
  1602. else:
  1603. assert unpacked.pack_type_num in DELTA_TYPES
  1604. unpacked.obj_type_num = obj_type_num
  1605. unpacked.obj_chunks = apply_delta(base_chunks, unpacked.decomp_chunks)
  1606. return unpacked
  1607. def _follow_chain(self, offset: int, obj_type_num: int, base_chunks: list[bytes]) -> Iterator[T]:
  1608. # Unlike PackData.get_object_at, there is no need to cache offsets as
  1609. # this approach by design inflates each object exactly once.
  1610. todo = [(offset, obj_type_num, base_chunks)]
  1611. while todo:
  1612. (offset, obj_type_num, base_chunks) = todo.pop()
  1613. unpacked = self._resolve_object(offset, obj_type_num, base_chunks)
  1614. yield self._result(unpacked)
  1615. assert unpacked.offset is not None
  1616. unblocked = chain(
  1617. self._pending_ofs.pop(unpacked.offset, []),
  1618. self._pending_ref.pop(unpacked.sha(), []),
  1619. )
  1620. todo.extend(
  1621. (new_offset, unpacked.obj_type_num, unpacked.obj_chunks) # type: ignore
  1622. for new_offset in unblocked
  1623. )
  1624. def __iter__(self) -> Iterator[T]:
  1625. """Iterate over objects in the pack."""
  1626. return self._walk_all_chains()
  1627. @property
  1628. def ext_refs(self) -> list[bytes]:
  1629. """Return external references."""
  1630. return self._ext_refs
  1631. class UnpackedObjectIterator(DeltaChainIterator[UnpackedObject]):
  1632. """Delta chain iterator that yield unpacked objects."""
  1633. def _result(self, unpacked: UnpackedObject) -> UnpackedObject:
  1634. """Return the unpacked object.
  1635. Args:
  1636. unpacked: The unpacked object
  1637. Returns:
  1638. The unpacked object unchanged
  1639. """
  1640. return unpacked
  1641. class PackIndexer(DeltaChainIterator[PackIndexEntry]):
  1642. """Delta chain iterator that yields index entries."""
  1643. _compute_crc32 = True
  1644. def _result(self, unpacked: UnpackedObject) -> tuple:
  1645. """Convert unpacked object to pack index entry.
  1646. Args:
  1647. unpacked: The unpacked object
  1648. Returns:
  1649. Tuple of (sha, offset, crc32) for index entry
  1650. """
  1651. return unpacked.sha(), unpacked.offset, unpacked.crc32
  1652. class PackInflater(DeltaChainIterator[ShaFile]):
  1653. """Delta chain iterator that yields ShaFile objects."""
  1654. def _result(self, unpacked: UnpackedObject) -> Any:
  1655. """Convert unpacked object to ShaFile.
  1656. Args:
  1657. unpacked: The unpacked object
  1658. Returns:
  1659. ShaFile object from the unpacked data
  1660. """
  1661. return unpacked.sha_file()
  1662. class SHA1Reader(BinaryIO):
  1663. """Wrapper for file-like object that remembers the SHA1 of its data."""
  1664. def __init__(self, f) -> None:
  1665. """Initialize SHA1Reader.
  1666. Args:
  1667. f: File-like object to wrap
  1668. """
  1669. def __init__(self, f: BinaryIO) -> None:
  1670. self.f = f
  1671. self.sha1 = sha1(b"")
  1672. def read(self, size: int = -1) -> bytes:
  1673. """Read bytes and update SHA1.
  1674. Args:
  1675. size: Number of bytes to read, -1 for all
  1676. Returns:
  1677. Bytes read from file
  1678. """
  1679. data = self.f.read(size)
  1680. self.sha1.update(data)
  1681. return data
  1682. def check_sha(self, allow_empty: bool = False) -> None:
  1683. """Check if the SHA1 matches the expected value.
  1684. Args:
  1685. allow_empty: Allow empty SHA1 hash
  1686. Raises:
  1687. ChecksumMismatch: If SHA1 doesn't match
  1688. """
  1689. stored = self.f.read(20)
  1690. # If git option index.skipHash is set the index will be empty
  1691. if stored != self.sha1.digest() and (
  1692. not allow_empty
  1693. or sha_to_hex(stored) != b"0000000000000000000000000000000000000000"
  1694. ):
  1695. raise ChecksumMismatch(self.sha1.hexdigest(), sha_to_hex(stored))
  1696. def close(self) -> None:
  1697. """Close the underlying file."""
  1698. return self.f.close()
  1699. def tell(self) -> int:
  1700. """Return current file position."""
  1701. return self.f.tell()
  1702. # BinaryIO abstract methods
  1703. def readable(self) -> bool:
  1704. """Check if file is readable."""
  1705. return True
  1706. def writable(self) -> bool:
  1707. """Check if file is writable."""
  1708. return False
  1709. def seekable(self) -> bool:
  1710. """Check if file is seekable."""
  1711. return getattr(self.f, "seekable", lambda: False)()
  1712. def seek(self, offset: int, whence: int = 0) -> int:
  1713. """Seek to position in file.
  1714. Args:
  1715. offset: Position offset
  1716. whence: Reference point (0=start, 1=current, 2=end)
  1717. Returns:
  1718. New file position
  1719. """
  1720. return self.f.seek(offset, whence)
  1721. def flush(self) -> None:
  1722. """Flush the file buffer."""
  1723. if hasattr(self.f, "flush"):
  1724. self.f.flush()
  1725. def readline(self, size: int = -1) -> bytes:
  1726. """Read a line from the file.
  1727. Args:
  1728. size: Maximum bytes to read
  1729. Returns:
  1730. Line read from file
  1731. """
  1732. return self.f.readline(size)
  1733. def readlines(self, hint: int = -1) -> list[bytes]:
  1734. """Read all lines from the file.
  1735. Args:
  1736. hint: Approximate number of bytes to read
  1737. Returns:
  1738. List of lines
  1739. """
  1740. return self.f.readlines(hint)
  1741. def writelines(self, lines) -> None:
  1742. """Not supported for read-only file.
  1743. Raises:
  1744. UnsupportedOperation: Always raised
  1745. """
  1746. raise UnsupportedOperation("writelines")
  1747. def write(self, data) -> int:
  1748. """Not supported for read-only file.
  1749. Raises:
  1750. UnsupportedOperation: Always raised
  1751. """
  1752. raise UnsupportedOperation("write")
  1753. def writelines(self, lines: Any) -> None:
  1754. raise UnsupportedOperation("writelines")
  1755. def write(self, data: bytes) -> int:
  1756. raise UnsupportedOperation("write")
  1757. def __enter__(self) -> 'SHA1Reader':
  1758. return self
  1759. def __exit__(self, type: Optional[type], value: Optional[BaseException], traceback: Optional[Any]) -> None:
  1760. self.close()
  1761. def __iter__(self) -> 'SHA1Reader':
  1762. return self
  1763. def __next__(self) -> bytes:
  1764. """Get next line from file.
  1765. Returns:
  1766. Next line
  1767. Raises:
  1768. StopIteration: When no more lines
  1769. """
  1770. line = self.readline()
  1771. if not line:
  1772. raise StopIteration
  1773. return line
  1774. def fileno(self) -> int:
  1775. """Return file descriptor number."""
  1776. return self.f.fileno()
  1777. def isatty(self) -> bool:
  1778. """Check if file is a terminal."""
  1779. return getattr(self.f, "isatty", lambda: False)()
  1780. def truncate(self, size: Optional[int] = None) -> int:
  1781. """Not supported for read-only file.
  1782. Raises:
  1783. UnsupportedOperation: Always raised
  1784. """
  1785. raise UnsupportedOperation("truncate")
  1786. class SHA1Writer(BinaryIO):
  1787. """Wrapper for file-like object that remembers the SHA1 of its data."""
  1788. def __init__(self, f) -> None:
  1789. """Initialize SHA1Writer.
  1790. Args:
  1791. f: File-like object to wrap
  1792. """
  1793. def __init__(self, f: BinaryIO) -> None:
  1794. self.f = f
  1795. self.length = 0
  1796. self.sha1 = sha1(b"")
  1797. def write(self, data) -> int:
  1798. """Write data and update SHA1.
  1799. Args:
  1800. data: Data to write
  1801. Returns:
  1802. Number of bytes written
  1803. """
  1804. def write(self, data: bytes) -> int:
  1805. self.sha1.update(data)
  1806. self.f.write(data)
  1807. self.length += len(data)
  1808. return len(data)
  1809. def write_sha(self) -> bytes:
  1810. """Write the SHA1 digest to the file.
  1811. Returns:
  1812. The SHA1 digest bytes
  1813. """
  1814. sha = self.sha1.digest()
  1815. assert len(sha) == 20
  1816. self.f.write(sha)
  1817. self.length += len(sha)
  1818. return sha
  1819. def close(self) -> bytes:
  1820. """Close the file after writing SHA1.
  1821. Returns:
  1822. The SHA1 digest bytes
  1823. """
  1824. sha = self.write_sha()
  1825. self.f.close()
  1826. return sha
  1827. def offset(self) -> int:
  1828. """Get the total number of bytes written.
  1829. Returns:
  1830. Total bytes written
  1831. """
  1832. return self.length
  1833. def tell(self) -> int:
  1834. """Return current file position."""
  1835. return self.f.tell()
  1836. # BinaryIO abstract methods
  1837. def readable(self) -> bool:
  1838. """Check if file is readable."""
  1839. return False
  1840. def writable(self) -> bool:
  1841. """Check if file is writable."""
  1842. return True
  1843. def seekable(self) -> bool:
  1844. """Check if file is seekable."""
  1845. return getattr(self.f, "seekable", lambda: False)()
  1846. def seek(self, offset: int, whence: int = 0) -> int:
  1847. """Seek to position in file.
  1848. Args:
  1849. offset: Position offset
  1850. whence: Reference point (0=start, 1=current, 2=end)
  1851. Returns:
  1852. New file position
  1853. """
  1854. return self.f.seek(offset, whence)
  1855. def flush(self) -> None:
  1856. """Flush the file buffer."""
  1857. if hasattr(self.f, "flush"):
  1858. self.f.flush()
  1859. def readline(self, size: int = -1) -> bytes:
  1860. """Not supported for write-only file.
  1861. Raises:
  1862. UnsupportedOperation: Always raised
  1863. """
  1864. raise UnsupportedOperation("readline")
  1865. def readlines(self, hint: int = -1) -> list[bytes]:
  1866. """Not supported for write-only file.
  1867. Raises:
  1868. UnsupportedOperation: Always raised
  1869. """
  1870. raise UnsupportedOperation("readlines")
  1871. def writelines(self, lines) -> None:
  1872. """Write multiple lines to the file.
  1873. Args:
  1874. lines: Iterable of lines to write
  1875. """
  1876. def writelines(self, lines: Any) -> None:
  1877. for line in lines:
  1878. self.write(line)
  1879. def read(self, size: int = -1) -> bytes:
  1880. """Not supported for write-only file.
  1881. Raises:
  1882. UnsupportedOperation: Always raised
  1883. """
  1884. raise UnsupportedOperation("read")
  1885. def __enter__(self) -> 'SHA1Writer':
  1886. """Enter context manager."""
  1887. return self
  1888. def __exit__(self, type: Optional[type], value: Optional[BaseException], traceback: Optional[Any]) -> None:
  1889. """Exit context manager and close file."""
  1890. self.close()
  1891. def __iter__(self) -> 'SHA1Writer':
  1892. """Return iterator."""
  1893. return self
  1894. def __next__(self) -> bytes:
  1895. """Not supported for write-only file.
  1896. Raises:
  1897. UnsupportedOperation: Always raised
  1898. """
  1899. raise UnsupportedOperation("__next__")
  1900. def fileno(self) -> int:
  1901. """Return file descriptor number."""
  1902. return self.f.fileno()
  1903. def isatty(self) -> bool:
  1904. """Check if file is a terminal."""
  1905. return getattr(self.f, "isatty", lambda: False)()
  1906. def truncate(self, size: Optional[int] = None) -> int:
  1907. """Not supported for write-only file.
  1908. Raises:
  1909. UnsupportedOperation: Always raised
  1910. """
  1911. raise UnsupportedOperation("truncate")
  1912. def pack_object_header(type_num: int, delta_base: Optional[Any], size: int) -> bytearray:
  1913. """Create a pack object header for the given object info.
  1914. Args:
  1915. type_num: Numeric type of the object.
  1916. delta_base: Delta base offset or ref, or None for whole objects.
  1917. size: Uncompressed object size.
  1918. Returns: A header for a packed object.
  1919. """
  1920. header = []
  1921. c = (type_num << 4) | (size & 15)
  1922. size >>= 4
  1923. while size:
  1924. header.append(c | 0x80)
  1925. c = size & 0x7F
  1926. size >>= 7
  1927. header.append(c)
  1928. if type_num == OFS_DELTA:
  1929. ret = [delta_base & 0x7F]
  1930. delta_base >>= 7
  1931. while delta_base:
  1932. delta_base -= 1
  1933. ret.insert(0, 0x80 | (delta_base & 0x7F))
  1934. delta_base >>= 7
  1935. header.extend(ret)
  1936. elif type_num == REF_DELTA:
  1937. assert len(delta_base) == 20
  1938. header += delta_base
  1939. return bytearray(header)
  1940. def pack_object_chunks(type: int, object: ShaFile, compression_level: int = -1) -> Iterator[bytes]:
  1941. """Generate chunks for a pack object.
  1942. Args:
  1943. type: Numeric type of the object
  1944. object: Object to write
  1945. compression_level: the zlib compression level
  1946. Returns: Chunks
  1947. """
  1948. if type in DELTA_TYPES:
  1949. delta_base, object = object
  1950. else:
  1951. delta_base = None
  1952. if isinstance(object, bytes):
  1953. object = [object]
  1954. yield bytes(pack_object_header(type, delta_base, sum(map(len, object))))
  1955. compressor = zlib.compressobj(level=compression_level)
  1956. for data in object:
  1957. yield compressor.compress(data)
  1958. yield compressor.flush()
  1959. def write_pack_object(write: Callable[[bytes], int], type: int, object: ShaFile, sha: Optional[bytes] = None, compression_level: int = -1) -> bytes:
  1960. """Write pack object to a file.
  1961. Args:
  1962. write: Write function to use
  1963. type: Numeric type of the object
  1964. object: Object to write
  1965. sha: Optional SHA-1 hasher to update
  1966. compression_level: the zlib compression level
  1967. Returns: Tuple with offset at which the object was written, and crc32
  1968. """
  1969. crc32 = 0
  1970. for chunk in pack_object_chunks(type, object, compression_level=compression_level):
  1971. write(chunk)
  1972. if sha is not None:
  1973. sha.update(chunk)
  1974. crc32 = binascii.crc32(chunk, crc32)
  1975. return crc32 & 0xFFFFFFFF
  1976. def write_pack(
  1977. filename,
  1978. objects: Union[Sequence[ShaFile], Sequence[tuple[ShaFile, Optional[bytes]]]],
  1979. *,
  1980. deltify: Optional[bool] = None,
  1981. delta_window_size: Optional[int] = None,
  1982. compression_level: int = -1,
  1983. ):
  1984. """Write a new pack data file.
  1985. Args:
  1986. filename: Path to the new pack file (without .pack extension)
  1987. objects: Objects to write to the pack
  1988. delta_window_size: Delta window size
  1989. deltify: Whether to deltify pack objects
  1990. compression_level: the zlib compression level
  1991. Returns: Tuple with checksum of pack file and index file
  1992. """
  1993. with GitFile(filename + ".pack", "wb") as f:
  1994. entries, data_sum = write_pack_objects(
  1995. f.write,
  1996. objects,
  1997. delta_window_size=delta_window_size,
  1998. deltify=deltify,
  1999. compression_level=compression_level,
  2000. )
  2001. entries = sorted([(k, v[0], v[1]) for (k, v) in entries.items()])
  2002. with GitFile(filename + ".idx", "wb") as f:
  2003. return data_sum, write_pack_index(f, entries, data_sum)
  2004. def pack_header_chunks(num_objects: int) -> Iterator[bytes]:
  2005. """Yield chunks for a pack header."""
  2006. yield b"PACK" # Pack header
  2007. yield struct.pack(b">L", 2) # Pack version
  2008. yield struct.pack(b">L", num_objects) # Number of objects in pack
  2009. def write_pack_header(write, num_objects) -> None:
  2010. """Write a pack header for the given number of objects."""
  2011. if hasattr(write, "write"):
  2012. write = write.write
  2013. warnings.warn(
  2014. "write_pack_header() now takes a write rather than file argument",
  2015. DeprecationWarning,
  2016. stacklevel=2,
  2017. )
  2018. for chunk in pack_header_chunks(num_objects):
  2019. write(chunk)
  2020. def find_reusable_deltas(
  2021. container: PackedObjectContainer,
  2022. object_ids: set[bytes],
  2023. *,
  2024. other_haves: Optional[set[bytes]] = None,
  2025. progress=None,
  2026. ) -> Iterator[UnpackedObject]:
  2027. """Find deltas in a pack that can be reused.
  2028. Args:
  2029. container: Pack container to search for deltas
  2030. object_ids: Set of object IDs to find deltas for
  2031. other_haves: Set of other object IDs we have
  2032. progress: Optional progress reporting callback
  2033. Returns:
  2034. Iterator of UnpackedObject entries that can be reused
  2035. """
  2036. if other_haves is None:
  2037. other_haves = set()
  2038. reused = 0
  2039. for i, unpacked in enumerate(
  2040. container.iter_unpacked_subset(
  2041. object_ids, allow_missing=True, convert_ofs_delta=True
  2042. )
  2043. ):
  2044. if progress is not None and i % 1000 == 0:
  2045. progress(f"checking for reusable deltas: {i}/{len(object_ids)}\r".encode())
  2046. if unpacked.pack_type_num == REF_DELTA:
  2047. hexsha = sha_to_hex(unpacked.delta_base) # type: ignore
  2048. if hexsha in object_ids or hexsha in other_haves:
  2049. yield unpacked
  2050. reused += 1
  2051. if progress is not None:
  2052. progress((f"found {reused} deltas to reuse\n").encode())
  2053. def deltify_pack_objects(
  2054. objects: Union[Iterator[bytes], Iterator[tuple[ShaFile, Optional[bytes]]]],
  2055. *,
  2056. window_size: Optional[int] = None,
  2057. progress=None,
  2058. ) -> Iterator[UnpackedObject]:
  2059. """Generate deltas for pack objects.
  2060. Args:
  2061. objects: An iterable of (object, path) tuples to deltify.
  2062. window_size: Window size; None for default
  2063. progress: Optional progress reporting callback
  2064. Returns: Iterator over type_num, object id, delta_base, content
  2065. delta_base is None for full text entries
  2066. """
  2067. def objects_with_hints() -> Iterator[tuple[ShaFile, tuple[int, None]]]:
  2068. for e in objects:
  2069. if isinstance(e, ShaFile):
  2070. yield (e, (e.type_num, None))
  2071. else:
  2072. yield (e[0], (e[0].type_num, e[1]))
  2073. yield from deltas_from_sorted_objects(
  2074. sort_objects_for_delta(objects_with_hints()),
  2075. window_size=window_size,
  2076. progress=progress,
  2077. )
  2078. def sort_objects_for_delta(
  2079. objects: Union[Iterator[ShaFile], Iterator[tuple[ShaFile, Optional[PackHint]]]],
  2080. ) -> Iterator[ShaFile]:
  2081. """Sort objects for optimal delta compression.
  2082. Args:
  2083. objects: Iterator of objects or (object, hint) tuples
  2084. Returns:
  2085. Iterator of sorted ShaFile objects
  2086. """
  2087. magic = []
  2088. for entry in objects:
  2089. if isinstance(entry, tuple):
  2090. obj, hint = entry
  2091. if hint is None:
  2092. type_num = None
  2093. path = None
  2094. else:
  2095. (type_num, path) = hint
  2096. else:
  2097. obj = entry
  2098. magic.append((type_num, path, -obj.raw_length(), obj))
  2099. # Build a list of objects ordered by the magic Linus heuristic
  2100. # This helps us find good objects to diff against us
  2101. magic.sort()
  2102. return (x[3] for x in magic)
  2103. def deltas_from_sorted_objects(
  2104. objects, window_size: Optional[int] = None, progress=None
  2105. ):
  2106. """Create deltas from sorted objects.
  2107. Args:
  2108. objects: Iterator of sorted objects to deltify
  2109. window_size: Delta window size; None for default
  2110. progress: Optional progress reporting callback
  2111. Returns:
  2112. Iterator of UnpackedObject entries
  2113. """
  2114. # TODO(jelmer): Use threads
  2115. if window_size is None:
  2116. window_size = DEFAULT_PACK_DELTA_WINDOW_SIZE
  2117. possible_bases: deque[tuple[bytes, int, list[bytes]]] = deque()
  2118. for i, o in enumerate(objects):
  2119. if progress is not None and i % 1000 == 0:
  2120. progress((f"generating deltas: {i}\r").encode())
  2121. raw = o.as_raw_chunks()
  2122. winner = raw
  2123. winner_len = sum(map(len, winner))
  2124. winner_base = None
  2125. for base_id, base_type_num, base in possible_bases:
  2126. if base_type_num != o.type_num:
  2127. continue
  2128. delta_len = 0
  2129. delta = []
  2130. for chunk in create_delta(base, raw):
  2131. delta_len += len(chunk)
  2132. if delta_len >= winner_len:
  2133. break
  2134. delta.append(chunk)
  2135. else:
  2136. winner_base = base_id
  2137. winner = delta
  2138. winner_len = sum(map(len, winner))
  2139. yield UnpackedObject(
  2140. o.type_num,
  2141. sha=o.sha().digest(),
  2142. delta_base=winner_base,
  2143. decomp_len=winner_len,
  2144. decomp_chunks=winner,
  2145. )
  2146. possible_bases.appendleft((o.sha().digest(), o.type_num, raw))
  2147. while len(possible_bases) > window_size:
  2148. possible_bases.pop()
  2149. def pack_objects_to_data(
  2150. objects: Union[Sequence[ShaFile], Sequence[tuple[ShaFile, Optional[bytes]]]],
  2151. *,
  2152. deltify: Optional[bool] = None,
  2153. delta_window_size: Optional[int] = None,
  2154. ofs_delta: bool = True,
  2155. progress=None,
  2156. ) -> tuple[int, Iterator[UnpackedObject]]:
  2157. """Create pack data from objects.
  2158. Args:
  2159. objects: Pack objects
  2160. deltify: Whether to deltify pack objects
  2161. delta_window_size: Delta window size
  2162. ofs_delta: Whether to use offset deltas
  2163. progress: Optional progress reporting callback
  2164. Returns: Tuples with (type_num, hexdigest, delta base, object chunks)
  2165. """
  2166. # TODO(jelmer): support deltaifying
  2167. count = len(objects)
  2168. if deltify is None:
  2169. # PERFORMANCE/TODO(jelmer): This should be enabled but is *much* too
  2170. # slow at the moment.
  2171. deltify = False
  2172. if deltify:
  2173. return (
  2174. count,
  2175. deltify_pack_objects(
  2176. iter(objects), # type: ignore
  2177. window_size=delta_window_size,
  2178. progress=progress,
  2179. ),
  2180. )
  2181. else:
  2182. def iter_without_path() -> Iterator[tuple[ShaFile, tuple[int, None]]]:
  2183. for o in objects:
  2184. if isinstance(o, tuple):
  2185. yield full_unpacked_object(o[0])
  2186. else:
  2187. yield full_unpacked_object(o)
  2188. return (count, iter_without_path())
  2189. def generate_unpacked_objects(
  2190. container: PackedObjectContainer,
  2191. object_ids: Sequence[tuple[ObjectID, Optional[PackHint]]],
  2192. delta_window_size: Optional[int] = None,
  2193. deltify: Optional[bool] = None,
  2194. reuse_deltas: bool = True,
  2195. ofs_delta: bool = True,
  2196. other_haves: Optional[set[bytes]] = None,
  2197. progress=None,
  2198. ) -> Iterator[UnpackedObject]:
  2199. """Create pack data from objects.
  2200. Returns: Tuples with (type_num, hexdigest, delta base, object chunks)
  2201. """
  2202. todo = dict(object_ids)
  2203. if reuse_deltas:
  2204. for unpack in find_reusable_deltas(
  2205. container, set(todo), other_haves=other_haves, progress=progress
  2206. ):
  2207. del todo[sha_to_hex(unpack.sha())]
  2208. yield unpack
  2209. if deltify is None:
  2210. # PERFORMANCE/TODO(jelmer): This should be enabled but is *much* too
  2211. # slow at the moment.
  2212. deltify = False
  2213. if deltify:
  2214. objects_to_delta = container.iterobjects_subset(
  2215. todo.keys(), allow_missing=False
  2216. )
  2217. yield from deltas_from_sorted_objects(
  2218. sort_objects_for_delta((o, todo[o.id]) for o in objects_to_delta),
  2219. window_size=delta_window_size,
  2220. progress=progress,
  2221. )
  2222. else:
  2223. for oid in todo:
  2224. yield full_unpacked_object(container[oid])
  2225. def full_unpacked_object(o: ShaFile) -> UnpackedObject:
  2226. """Create an UnpackedObject from a ShaFile.
  2227. Args:
  2228. o: ShaFile object to convert
  2229. Returns:
  2230. UnpackedObject with full object data
  2231. """
  2232. return UnpackedObject(
  2233. o.type_num,
  2234. delta_base=None,
  2235. crc32=None,
  2236. decomp_chunks=o.as_raw_chunks(),
  2237. sha=o.sha().digest(),
  2238. )
  2239. def write_pack_from_container(
  2240. write,
  2241. container: PackedObjectContainer,
  2242. object_ids: Sequence[tuple[ObjectID, Optional[PackHint]]],
  2243. delta_window_size: Optional[int] = None,
  2244. deltify: Optional[bool] = None,
  2245. reuse_deltas: bool = True,
  2246. compression_level: int = -1,
  2247. other_haves: Optional[set[bytes]] = None,
  2248. ):
  2249. """Write a new pack data file.
  2250. Args:
  2251. write: write function to use
  2252. container: PackedObjectContainer
  2253. object_ids: Sequence of (object_id, hint) tuples to write
  2254. delta_window_size: Sliding window size for searching for deltas;
  2255. Set to None for default window size.
  2256. deltify: Whether to deltify objects
  2257. reuse_deltas: Whether to reuse existing deltas
  2258. compression_level: the zlib compression level to use
  2259. other_haves: Set of additional object IDs the receiver has
  2260. Returns: Dict mapping id -> (offset, crc32 checksum), pack checksum
  2261. """
  2262. pack_contents_count = len(object_ids)
  2263. pack_contents = generate_unpacked_objects(
  2264. container,
  2265. object_ids,
  2266. delta_window_size=delta_window_size,
  2267. deltify=deltify,
  2268. reuse_deltas=reuse_deltas,
  2269. other_haves=other_haves,
  2270. )
  2271. return write_pack_data(
  2272. write,
  2273. pack_contents,
  2274. num_records=pack_contents_count,
  2275. compression_level=compression_level,
  2276. )
  2277. def write_pack_objects(
  2278. write,
  2279. objects: Union[Sequence[ShaFile], Sequence[tuple[ShaFile, Optional[bytes]]]],
  2280. *,
  2281. delta_window_size: Optional[int] = None,
  2282. deltify: Optional[bool] = None,
  2283. compression_level: int = -1,
  2284. ):
  2285. """Write a new pack data file.
  2286. Args:
  2287. write: write function to use
  2288. objects: Sequence of (object, path) tuples to write
  2289. delta_window_size: Sliding window size for searching for deltas;
  2290. Set to None for default window size.
  2291. deltify: Whether to deltify objects
  2292. compression_level: the zlib compression level to use
  2293. Returns: Dict mapping id -> (offset, crc32 checksum), pack checksum
  2294. """
  2295. pack_contents_count, pack_contents = pack_objects_to_data(objects, deltify=deltify)
  2296. return write_pack_data(
  2297. write,
  2298. pack_contents,
  2299. num_records=pack_contents_count,
  2300. compression_level=compression_level,
  2301. )
  2302. class PackChunkGenerator:
  2303. """Generator for pack data chunks."""
  2304. def __init__(
  2305. self,
  2306. num_records=None,
  2307. records=None,
  2308. progress=None,
  2309. compression_level=-1,
  2310. reuse_compressed=True,
  2311. ) -> None:
  2312. """Initialize PackChunkGenerator.
  2313. Args:
  2314. num_records: Expected number of records
  2315. records: Iterator of pack records
  2316. progress: Optional progress callback
  2317. compression_level: Compression level (-1 for default)
  2318. reuse_compressed: Whether to reuse compressed chunks
  2319. """
  2320. self.cs = sha1(b"")
  2321. self.entries: dict[Union[int, bytes], tuple[int, int]] = {}
  2322. self._it = self._pack_data_chunks(
  2323. num_records=num_records,
  2324. records=records,
  2325. progress=progress,
  2326. compression_level=compression_level,
  2327. reuse_compressed=reuse_compressed,
  2328. )
  2329. def sha1digest(self) -> bytes:
  2330. """Return the SHA1 digest of the pack data."""
  2331. return self.cs.digest()
  2332. def __iter__(self) -> Iterator[bytes]:
  2333. """Iterate over pack data chunks."""
  2334. return self._it
  2335. def _pack_data_chunks(
  2336. self,
  2337. records: Iterator[UnpackedObject],
  2338. *,
  2339. num_records=None,
  2340. progress=None,
  2341. compression_level: int = -1,
  2342. reuse_compressed: bool = True,
  2343. ) -> Iterator[bytes]:
  2344. """Iterate pack data file chunks.
  2345. Args:
  2346. records: Iterator over UnpackedObject
  2347. num_records: Number of records (defaults to len(records) if not specified)
  2348. progress: Function to report progress to
  2349. compression_level: the zlib compression level
  2350. reuse_compressed: Whether to reuse compressed chunks
  2351. Returns: Dict mapping id -> (offset, crc32 checksum), pack checksum
  2352. """
  2353. # Write the pack
  2354. if num_records is None:
  2355. num_records = len(records) # type: ignore
  2356. offset = 0
  2357. for chunk in pack_header_chunks(num_records):
  2358. yield chunk
  2359. self.cs.update(chunk)
  2360. offset += len(chunk)
  2361. actual_num_records = 0
  2362. for i, unpacked in enumerate(records):
  2363. type_num = unpacked.pack_type_num
  2364. if progress is not None and i % 1000 == 0:
  2365. progress((f"writing pack data: {i}/{num_records}\r").encode("ascii"))
  2366. raw: Union[list[bytes], tuple[int, list[bytes]], tuple[bytes, list[bytes]]]
  2367. if unpacked.delta_base is not None:
  2368. try:
  2369. base_offset, base_crc32 = self.entries[unpacked.delta_base]
  2370. except KeyError:
  2371. type_num = REF_DELTA
  2372. assert isinstance(unpacked.delta_base, bytes)
  2373. raw = (unpacked.delta_base, unpacked.decomp_chunks)
  2374. else:
  2375. type_num = OFS_DELTA
  2376. raw = (offset - base_offset, unpacked.decomp_chunks)
  2377. else:
  2378. raw = unpacked.decomp_chunks
  2379. if unpacked.comp_chunks is not None and reuse_compressed:
  2380. chunks = unpacked.comp_chunks
  2381. else:
  2382. chunks = pack_object_chunks(
  2383. type_num, raw, compression_level=compression_level
  2384. )
  2385. crc32 = 0
  2386. object_size = 0
  2387. for chunk in chunks:
  2388. yield chunk
  2389. crc32 = binascii.crc32(chunk, crc32)
  2390. self.cs.update(chunk)
  2391. object_size += len(chunk)
  2392. actual_num_records += 1
  2393. self.entries[unpacked.sha()] = (offset, crc32)
  2394. offset += object_size
  2395. if actual_num_records != num_records:
  2396. raise AssertionError(
  2397. f"actual records written differs: {actual_num_records} != {num_records}"
  2398. )
  2399. yield self.cs.digest()
  2400. def write_pack_data(
  2401. write,
  2402. records: Iterator[UnpackedObject],
  2403. *,
  2404. num_records=None,
  2405. progress=None,
  2406. compression_level=-1,
  2407. ):
  2408. """Write a new pack data file.
  2409. Args:
  2410. write: Write function to use
  2411. num_records: Number of records (defaults to len(records) if None)
  2412. records: Iterator over type_num, object_id, delta_base, raw
  2413. progress: Function to report progress to
  2414. compression_level: the zlib compression level
  2415. Returns: Dict mapping id -> (offset, crc32 checksum), pack checksum
  2416. """
  2417. chunk_generator = PackChunkGenerator(
  2418. num_records=num_records,
  2419. records=records,
  2420. progress=progress,
  2421. compression_level=compression_level,
  2422. )
  2423. for chunk in chunk_generator:
  2424. write(chunk)
  2425. return chunk_generator.entries, chunk_generator.sha1digest()
  2426. def write_pack_index_v1(f: BinaryIO, entries: list[tuple[bytes, int, Optional[int]]], pack_checksum: bytes) -> None:
  2427. """Write a new pack index file.
  2428. Args:
  2429. f: A file-like object to write to
  2430. entries: List of tuples with object name (sha), offset_in_pack,
  2431. and crc32_checksum.
  2432. pack_checksum: Checksum of the pack file.
  2433. Returns: The SHA of the written index file
  2434. """
  2435. f = SHA1Writer(f)
  2436. fan_out_table = defaultdict(lambda: 0)
  2437. for name, _offset, _entry_checksum in entries:
  2438. fan_out_table[ord(name[:1])] += 1
  2439. # Fan-out table
  2440. for i in range(0x100):
  2441. f.write(struct.pack(">L", fan_out_table[i]))
  2442. fan_out_table[i + 1] += fan_out_table[i]
  2443. for name, offset, _entry_checksum in entries:
  2444. if not (offset <= 0xFFFFFFFF):
  2445. raise TypeError("pack format 1 only supports offsets < 2Gb")
  2446. f.write(struct.pack(">L20s", offset, name))
  2447. assert len(pack_checksum) == 20
  2448. f.write(pack_checksum)
  2449. return f.write_sha()
  2450. def _delta_encode_size(size) -> bytes:
  2451. ret = bytearray()
  2452. c = size & 0x7F
  2453. size >>= 7
  2454. while size:
  2455. ret.append(c | 0x80)
  2456. c = size & 0x7F
  2457. size >>= 7
  2458. ret.append(c)
  2459. return bytes(ret)
  2460. # The length of delta compression copy operations in version 2 packs is limited
  2461. # to 64K. To copy more, we use several copy operations. Version 3 packs allow
  2462. # 24-bit lengths in copy operations, but we always make version 2 packs.
  2463. _MAX_COPY_LEN = 0xFFFF
  2464. def _encode_copy_operation(start: int, length: int) -> bytes:
  2465. scratch = bytearray([0x80])
  2466. for i in range(4):
  2467. if start & 0xFF << i * 8:
  2468. scratch.append((start >> i * 8) & 0xFF)
  2469. scratch[0] |= 1 << i
  2470. for i in range(2):
  2471. if length & 0xFF << i * 8:
  2472. scratch.append((length >> i * 8) & 0xFF)
  2473. scratch[0] |= 1 << (4 + i)
  2474. return bytes(scratch)
  2475. def create_delta(base_buf: bytes, target_buf: bytes) -> bytes:
  2476. """Use python difflib to work out how to transform base_buf to target_buf.
  2477. Args:
  2478. base_buf: Base buffer
  2479. target_buf: Target buffer
  2480. """
  2481. if isinstance(base_buf, list):
  2482. base_buf = b"".join(base_buf)
  2483. if isinstance(target_buf, list):
  2484. target_buf = b"".join(target_buf)
  2485. assert isinstance(base_buf, bytes)
  2486. assert isinstance(target_buf, bytes)
  2487. # write delta header
  2488. yield _delta_encode_size(len(base_buf))
  2489. yield _delta_encode_size(len(target_buf))
  2490. # write out delta opcodes
  2491. seq = SequenceMatcher(isjunk=None, a=base_buf, b=target_buf)
  2492. for opcode, i1, i2, j1, j2 in seq.get_opcodes():
  2493. # Git patch opcodes don't care about deletes!
  2494. # if opcode == 'replace' or opcode == 'delete':
  2495. # pass
  2496. if opcode == "equal":
  2497. # If they are equal, unpacker will use data from base_buf
  2498. # Write out an opcode that says what range to use
  2499. copy_start = i1
  2500. copy_len = i2 - i1
  2501. while copy_len > 0:
  2502. to_copy = min(copy_len, _MAX_COPY_LEN)
  2503. yield _encode_copy_operation(copy_start, to_copy)
  2504. copy_start += to_copy
  2505. copy_len -= to_copy
  2506. if opcode == "replace" or opcode == "insert":
  2507. # If we are replacing a range or adding one, then we just
  2508. # output it to the stream (prefixed by its size)
  2509. s = j2 - j1
  2510. o = j1
  2511. while s > 127:
  2512. yield bytes([127])
  2513. yield memoryview(target_buf)[o : o + 127]
  2514. s -= 127
  2515. o += 127
  2516. yield bytes([s])
  2517. yield memoryview(target_buf)[o : o + s]
  2518. def apply_delta(src_buf: bytes, delta: bytes) -> bytes:
  2519. """Based on the similar function in git's patch-delta.c.
  2520. Args:
  2521. src_buf: Source buffer
  2522. delta: Delta instructions
  2523. """
  2524. if not isinstance(src_buf, bytes):
  2525. src_buf = b"".join(src_buf)
  2526. if not isinstance(delta, bytes):
  2527. delta = b"".join(delta)
  2528. out = []
  2529. index = 0
  2530. delta_length = len(delta)
  2531. def get_delta_header_size(delta: bytes, index: list[int]) -> tuple[int, int]:
  2532. size = 0
  2533. i = 0
  2534. while delta:
  2535. cmd = ord(delta[index : index + 1])
  2536. index += 1
  2537. size |= (cmd & ~0x80) << i
  2538. i += 7
  2539. if not cmd & 0x80:
  2540. break
  2541. return size, index
  2542. src_size, index = get_delta_header_size(delta, index)
  2543. dest_size, index = get_delta_header_size(delta, index)
  2544. if src_size != len(src_buf):
  2545. raise ApplyDeltaError(
  2546. f"Unexpected source buffer size: {src_size} vs {len(src_buf)}"
  2547. )
  2548. while index < delta_length:
  2549. cmd = ord(delta[index : index + 1])
  2550. index += 1
  2551. if cmd & 0x80:
  2552. cp_off = 0
  2553. for i in range(4):
  2554. if cmd & (1 << i):
  2555. x = ord(delta[index : index + 1])
  2556. index += 1
  2557. cp_off |= x << (i * 8)
  2558. cp_size = 0
  2559. # Version 3 packs can contain copy sizes larger than 64K.
  2560. for i in range(3):
  2561. if cmd & (1 << (4 + i)):
  2562. x = ord(delta[index : index + 1])
  2563. index += 1
  2564. cp_size |= x << (i * 8)
  2565. if cp_size == 0:
  2566. cp_size = 0x10000
  2567. if (
  2568. cp_off + cp_size < cp_size
  2569. or cp_off + cp_size > src_size
  2570. or cp_size > dest_size
  2571. ):
  2572. break
  2573. out.append(src_buf[cp_off : cp_off + cp_size])
  2574. elif cmd != 0:
  2575. out.append(delta[index : index + cmd])
  2576. index += cmd
  2577. else:
  2578. raise ApplyDeltaError("Invalid opcode 0")
  2579. if index != delta_length:
  2580. raise ApplyDeltaError(f"delta not empty: {delta[index:]!r}")
  2581. if dest_size != chunks_length(out):
  2582. raise ApplyDeltaError("dest size incorrect")
  2583. return out
  2584. def write_pack_index_v2(
  2585. f, entries: Iterable[PackIndexEntry], pack_checksum: bytes
  2586. ) -> bytes:
  2587. """Write a new pack index file.
  2588. Args:
  2589. f: File-like object to write to
  2590. entries: List of tuples with object name (sha), offset_in_pack, and
  2591. crc32_checksum.
  2592. pack_checksum: Checksum of the pack file.
  2593. Returns: The SHA of the index file written
  2594. """
  2595. f = SHA1Writer(f)
  2596. f.write(b"\377tOc") # Magic!
  2597. f.write(struct.pack(">L", 2))
  2598. fan_out_table: dict[int, int] = defaultdict(lambda: 0)
  2599. for name, offset, entry_checksum in entries:
  2600. fan_out_table[ord(name[:1])] += 1
  2601. # Fan-out table
  2602. largetable: list[int] = []
  2603. for i in range(0x100):
  2604. f.write(struct.pack(b">L", fan_out_table[i]))
  2605. fan_out_table[i + 1] += fan_out_table[i]
  2606. for name, offset, entry_checksum in entries:
  2607. f.write(name)
  2608. for name, offset, entry_checksum in entries:
  2609. f.write(struct.pack(b">L", entry_checksum))
  2610. for name, offset, entry_checksum in entries:
  2611. if offset < 2**31:
  2612. f.write(struct.pack(b">L", offset))
  2613. else:
  2614. f.write(struct.pack(b">L", 2**31 + len(largetable)))
  2615. largetable.append(offset)
  2616. for offset in largetable:
  2617. f.write(struct.pack(b">Q", offset))
  2618. assert len(pack_checksum) == 20
  2619. f.write(pack_checksum)
  2620. return f.write_sha()
  2621. def write_pack_index_v3(
  2622. f, entries: Iterable[PackIndexEntry], pack_checksum: bytes, hash_algorithm: int = 1
  2623. ) -> bytes:
  2624. """Write a new pack index file in v3 format.
  2625. Args:
  2626. f: File-like object to write to
  2627. entries: List of tuples with object name (sha), offset_in_pack, and
  2628. crc32_checksum.
  2629. pack_checksum: Checksum of the pack file.
  2630. hash_algorithm: Hash algorithm identifier (1 = SHA-1, 2 = SHA-256)
  2631. Returns: The SHA of the index file written
  2632. """
  2633. if hash_algorithm == 1:
  2634. hash_size = 20 # SHA-1
  2635. writer_cls = SHA1Writer
  2636. elif hash_algorithm == 2:
  2637. hash_size = 32 # SHA-256
  2638. # TODO: Add SHA256Writer when SHA-256 support is implemented
  2639. raise NotImplementedError("SHA-256 support not yet implemented")
  2640. else:
  2641. raise ValueError(f"Unknown hash algorithm {hash_algorithm}")
  2642. # Convert entries to list to allow multiple iterations
  2643. entries_list = list(entries)
  2644. # Calculate shortest unambiguous prefix length for object names
  2645. # For now, use full hash size (this could be optimized)
  2646. shortened_oid_len = hash_size
  2647. f = writer_cls(f)
  2648. f.write(b"\377tOc") # Magic!
  2649. f.write(struct.pack(">L", 3)) # Version 3
  2650. f.write(struct.pack(">L", hash_algorithm)) # Hash algorithm
  2651. f.write(struct.pack(">L", shortened_oid_len)) # Shortened OID length
  2652. fan_out_table: dict[int, int] = defaultdict(lambda: 0)
  2653. for name, offset, entry_checksum in entries_list:
  2654. if len(name) != hash_size:
  2655. raise ValueError(
  2656. f"Object name has wrong length: expected {hash_size}, got {len(name)}"
  2657. )
  2658. fan_out_table[ord(name[:1])] += 1
  2659. # Fan-out table
  2660. largetable: list[int] = []
  2661. for i in range(0x100):
  2662. f.write(struct.pack(b">L", fan_out_table[i]))
  2663. fan_out_table[i + 1] += fan_out_table[i]
  2664. # Object names table
  2665. for name, offset, entry_checksum in entries_list:
  2666. f.write(name)
  2667. # CRC32 checksums table
  2668. for name, offset, entry_checksum in entries_list:
  2669. f.write(struct.pack(b">L", entry_checksum))
  2670. # Offset table
  2671. for name, offset, entry_checksum in entries_list:
  2672. if offset < 2**31:
  2673. f.write(struct.pack(b">L", offset))
  2674. else:
  2675. f.write(struct.pack(b">L", 2**31 + len(largetable)))
  2676. largetable.append(offset)
  2677. # Large offset table
  2678. for offset in largetable:
  2679. f.write(struct.pack(b">Q", offset))
  2680. assert len(pack_checksum) == hash_size, (
  2681. f"Pack checksum has wrong length: expected {hash_size}, got {len(pack_checksum)}"
  2682. )
  2683. f.write(pack_checksum)
  2684. return f.write_sha()
  2685. def write_pack_index(
  2686. index_filename, entries, pack_checksum, progress=None, version=None
  2687. ):
  2688. """Write a pack index file.
  2689. Args:
  2690. index_filename: Index filename.
  2691. entries: List of (checksum, offset, crc32) tuples
  2692. pack_checksum: Checksum of the pack file.
  2693. progress: Progress function (not currently used)
  2694. version: Pack index version to use (1, 2, or 3). If None, defaults to DEFAULT_PACK_INDEX_VERSION.
  2695. Returns:
  2696. SHA of the written index file
  2697. """
  2698. if version is None:
  2699. version = DEFAULT_PACK_INDEX_VERSION
  2700. if version == 1:
  2701. return write_pack_index_v1(index_filename, entries, pack_checksum)
  2702. elif version == 2:
  2703. return write_pack_index_v2(index_filename, entries, pack_checksum)
  2704. elif version == 3:
  2705. return write_pack_index_v3(index_filename, entries, pack_checksum)
  2706. else:
  2707. raise ValueError(f"Unsupported pack index version: {version}")
  2708. class Pack:
  2709. """A Git pack object."""
  2710. _data_load: Optional[Callable[[], PackData]]
  2711. _idx_load: Optional[Callable[[], PackIndex]]
  2712. _data: Optional[PackData]
  2713. _idx: Optional[PackIndex]
  2714. def __init__(
  2715. self,
  2716. basename,
  2717. resolve_ext_ref: Optional[ResolveExtRefFn] = None,
  2718. *,
  2719. delta_window_size=None,
  2720. window_memory=None,
  2721. delta_cache_size=None,
  2722. depth=None,
  2723. threads=None,
  2724. big_file_threshold=None,
  2725. ) -> None:
  2726. """Initialize a Pack object.
  2727. Args:
  2728. basename: Base path for pack files (without .pack/.idx extension)
  2729. resolve_ext_ref: Optional function to resolve external references
  2730. delta_window_size: Size of the delta compression window
  2731. window_memory: Memory limit for delta compression window
  2732. delta_cache_size: Size of the delta cache
  2733. depth: Maximum depth for delta chains
  2734. threads: Number of threads to use for operations
  2735. big_file_threshold: Size threshold for big file handling
  2736. """
  2737. self._basename = basename
  2738. self._data = None
  2739. self._idx = None
  2740. self._idx_path = self._basename + ".idx"
  2741. self._data_path = self._basename + ".pack"
  2742. self.delta_window_size = delta_window_size
  2743. self.window_memory = window_memory
  2744. self.delta_cache_size = delta_cache_size
  2745. self.depth = depth
  2746. self.threads = threads
  2747. self.big_file_threshold = big_file_threshold
  2748. self._data_load = lambda: PackData(
  2749. self._data_path,
  2750. delta_window_size=delta_window_size,
  2751. window_memory=window_memory,
  2752. delta_cache_size=delta_cache_size,
  2753. depth=depth,
  2754. threads=threads,
  2755. big_file_threshold=big_file_threshold,
  2756. )
  2757. self._idx_load = lambda: load_pack_index(self._idx_path)
  2758. self.resolve_ext_ref = resolve_ext_ref
  2759. @classmethod
  2760. def from_lazy_objects(cls, data_fn: Callable, idx_fn: Callable) -> 'Pack':
  2761. """Create a new pack object from callables to load pack data and index objects."""
  2762. ret = cls("")
  2763. ret._data_load = data_fn
  2764. ret._idx_load = idx_fn
  2765. return ret
  2766. @classmethod
  2767. def from_objects(cls, data: PackData, idx: PackIndex) -> 'Pack':
  2768. """Create a new pack object from pack data and index objects."""
  2769. ret = cls("")
  2770. ret._data = data
  2771. ret._data_load = None
  2772. ret._idx = idx
  2773. ret._idx_load = None
  2774. ret.check_length_and_checksum()
  2775. return ret
  2776. def name(self) -> bytes:
  2777. """The SHA over the SHAs of the objects in this pack."""
  2778. return self.index.objects_sha1()
  2779. @property
  2780. def data(self) -> PackData:
  2781. """The pack data object being used."""
  2782. if self._data is None:
  2783. assert self._data_load
  2784. self._data = self._data_load()
  2785. self.check_length_and_checksum()
  2786. return self._data
  2787. @property
  2788. def index(self) -> PackIndex:
  2789. """The index being used.
  2790. Note: This may be an in-memory index
  2791. """
  2792. if self._idx is None:
  2793. assert self._idx_load
  2794. self._idx = self._idx_load()
  2795. return self._idx
  2796. def close(self) -> None:
  2797. """Close the pack file and index."""
  2798. if self._data is not None:
  2799. self._data.close()
  2800. if self._idx is not None:
  2801. self._idx.close()
  2802. def __enter__(self) -> 'Pack':
  2803. """Enter context manager."""
  2804. return self
  2805. def __exit__(self, exc_type: Optional[type], exc_val: Optional[BaseException], exc_tb: Optional[Any]) -> None:
  2806. """Exit context manager."""
  2807. self.close()
  2808. def __eq__(self, other: Any) -> bool:
  2809. """Check equality with another pack."""
  2810. return isinstance(self, type(other)) and self.index == other.index
  2811. def __len__(self) -> int:
  2812. """Number of entries in this pack."""
  2813. return len(self.index)
  2814. def __repr__(self) -> str:
  2815. """Return string representation of this pack."""
  2816. return f"{self.__class__.__name__}({self._basename!r})"
  2817. def __iter__(self) -> Iterator[bytes]:
  2818. """Iterate over all the sha1s of the objects in this pack."""
  2819. return iter(self.index)
  2820. def check_length_and_checksum(self) -> None:
  2821. """Sanity check the length and checksum of the pack index and data."""
  2822. assert len(self.index) == len(self.data), (
  2823. f"Length mismatch: {len(self.index)} (index) != {len(self.data)} (data)"
  2824. )
  2825. idx_stored_checksum = self.index.get_pack_checksum()
  2826. data_stored_checksum = self.data.get_stored_checksum()
  2827. if (
  2828. idx_stored_checksum is not None
  2829. and idx_stored_checksum != data_stored_checksum
  2830. ):
  2831. raise ChecksumMismatch(
  2832. sha_to_hex(idx_stored_checksum),
  2833. sha_to_hex(data_stored_checksum),
  2834. )
  2835. def check(self) -> None:
  2836. """Check the integrity of this pack.
  2837. Raises:
  2838. ChecksumMismatch: if a checksum for the index or data is wrong
  2839. """
  2840. self.index.check()
  2841. self.data.check()
  2842. for obj in self.iterobjects():
  2843. obj.check()
  2844. # TODO: object connectivity checks
  2845. def get_stored_checksum(self) -> bytes:
  2846. """Return the stored checksum of the pack data."""
  2847. return self.data.get_stored_checksum()
  2848. def pack_tuples(self) -> list[tuple[ShaFile, None]]:
  2849. """Return pack tuples for all objects in pack."""
  2850. return [(o, None) for o in self.iterobjects()]
  2851. def __contains__(self, sha1: bytes) -> bool:
  2852. """Check whether this pack contains a particular SHA1."""
  2853. try:
  2854. self.index.object_offset(sha1)
  2855. return True
  2856. except KeyError:
  2857. return False
  2858. def get_raw(self, sha1: bytes) -> tuple[int, bytes]:
  2859. """Get raw object data by SHA1."""
  2860. offset = self.index.object_offset(sha1)
  2861. obj_type, obj = self.data.get_object_at(offset)
  2862. type_num, chunks = self.resolve_object(offset, obj_type, obj)
  2863. return type_num, b"".join(chunks)
  2864. def __getitem__(self, sha1: bytes) -> ShaFile:
  2865. """Retrieve the specified SHA1."""
  2866. type, uncomp = self.get_raw(sha1)
  2867. return ShaFile.from_raw_string(type, uncomp, sha=sha1)
  2868. def iterobjects(self) -> Iterator[ShaFile]:
  2869. """Iterate over the objects in this pack."""
  2870. return iter(
  2871. PackInflater.for_pack_data(self.data, resolve_ext_ref=self.resolve_ext_ref)
  2872. )
  2873. def iterobjects_subset(
  2874. self, shas: Iterable[ObjectID], *, allow_missing: bool = False
  2875. ) -> Iterator[ShaFile]:
  2876. """Iterate over a subset of objects in this pack."""
  2877. return (
  2878. uo
  2879. for uo in PackInflater.for_pack_subset(
  2880. self,
  2881. shas,
  2882. allow_missing=allow_missing,
  2883. resolve_ext_ref=self.resolve_ext_ref,
  2884. )
  2885. if uo.id in shas
  2886. )
  2887. def iter_unpacked_subset(
  2888. self,
  2889. shas: Iterable[ObjectID],
  2890. *,
  2891. include_comp: bool = False,
  2892. allow_missing: bool = False,
  2893. convert_ofs_delta: bool = False,
  2894. ) -> Iterator[UnpackedObject]:
  2895. """Iterate over unpacked objects in subset."""
  2896. ofs_pending: dict[int, list[UnpackedObject]] = defaultdict(list)
  2897. ofs: dict[bytes, int] = {}
  2898. todo = set(shas)
  2899. for unpacked in self.iter_unpacked(include_comp=include_comp):
  2900. sha = unpacked.sha()
  2901. ofs[unpacked.offset] = sha
  2902. hexsha = sha_to_hex(sha)
  2903. if hexsha in todo:
  2904. if unpacked.pack_type_num == OFS_DELTA:
  2905. assert isinstance(unpacked.delta_base, int)
  2906. base_offset = unpacked.offset - unpacked.delta_base
  2907. try:
  2908. unpacked.delta_base = ofs[base_offset]
  2909. except KeyError:
  2910. ofs_pending[base_offset].append(unpacked)
  2911. continue
  2912. else:
  2913. unpacked.pack_type_num = REF_DELTA
  2914. yield unpacked
  2915. todo.remove(hexsha)
  2916. for child in ofs_pending.pop(unpacked.offset, []):
  2917. child.pack_type_num = REF_DELTA
  2918. child.delta_base = sha
  2919. yield child
  2920. assert not ofs_pending
  2921. if not allow_missing and todo:
  2922. raise UnresolvedDeltas(list(todo))
  2923. def iter_unpacked(self, include_comp: bool = False) -> Iterator[UnpackedObject]:
  2924. """Iterate over all unpacked objects in this pack."""
  2925. ofs_to_entries = {
  2926. ofs: (sha, crc32) for (sha, ofs, crc32) in self.index.iterentries()
  2927. }
  2928. for unpacked in self.data.iter_unpacked(include_comp=include_comp):
  2929. (sha, crc32) = ofs_to_entries[unpacked.offset]
  2930. unpacked._sha = sha
  2931. unpacked.crc32 = crc32
  2932. yield unpacked
  2933. def keep(self, msg: Optional[bytes] = None) -> str:
  2934. """Add a .keep file for the pack, preventing git from garbage collecting it.
  2935. Args:
  2936. msg: A message written inside the .keep file; can be used later
  2937. to determine whether or not a .keep file is obsolete.
  2938. Returns: The path of the .keep file, as a string.
  2939. """
  2940. keepfile_name = f"{self._basename}.keep"
  2941. with GitFile(keepfile_name, "wb") as keepfile:
  2942. if msg:
  2943. keepfile.write(msg)
  2944. keepfile.write(b"\n")
  2945. return keepfile_name
  2946. def get_ref(self, sha: bytes) -> tuple[Optional[int], int, OldUnpackedObject]:
  2947. """Get the object for a ref SHA, only looking in this pack."""
  2948. # TODO: cache these results
  2949. try:
  2950. offset = self.index.object_offset(sha)
  2951. except KeyError:
  2952. offset = None
  2953. if offset:
  2954. type, obj = self.data.get_object_at(offset)
  2955. elif self.resolve_ext_ref:
  2956. type, obj = self.resolve_ext_ref(sha)
  2957. else:
  2958. raise KeyError(sha)
  2959. return offset, type, obj
  2960. def resolve_object(
  2961. self, offset: int, type: int, obj, get_ref=None
  2962. ) -> tuple[int, Iterable[bytes]]:
  2963. """Resolve an object, possibly resolving deltas when necessary.
  2964. Returns: Tuple with object type and contents.
  2965. """
  2966. # Walk down the delta chain, building a stack of deltas to reach
  2967. # the requested object.
  2968. base_offset = offset
  2969. base_type = type
  2970. base_obj = obj
  2971. delta_stack = []
  2972. while base_type in DELTA_TYPES:
  2973. prev_offset = base_offset
  2974. if get_ref is None:
  2975. get_ref = self.get_ref
  2976. if base_type == OFS_DELTA:
  2977. (delta_offset, delta) = base_obj
  2978. # TODO: clean up asserts and replace with nicer error messages
  2979. base_offset = base_offset - delta_offset
  2980. base_type, base_obj = self.data.get_object_at(base_offset)
  2981. assert isinstance(base_type, int)
  2982. elif base_type == REF_DELTA:
  2983. (basename, delta) = base_obj
  2984. assert isinstance(basename, bytes) and len(basename) == 20
  2985. base_offset, base_type, base_obj = get_ref(basename)
  2986. assert isinstance(base_type, int)
  2987. if base_offset == prev_offset: # object is based on itself
  2988. raise UnresolvedDeltas([basename])
  2989. delta_stack.append((prev_offset, base_type, delta))
  2990. # Now grab the base object (mustn't be a delta) and apply the
  2991. # deltas all the way up the stack.
  2992. chunks = base_obj
  2993. for prev_offset, _delta_type, delta in reversed(delta_stack):
  2994. chunks = apply_delta(chunks, delta)
  2995. if prev_offset is not None:
  2996. self.data._offset_cache[prev_offset] = base_type, chunks
  2997. return base_type, chunks
  2998. def entries(
  2999. self, progress: Optional[ProgressFn] = None
  3000. ) -> Iterator[PackIndexEntry]:
  3001. """Yield entries summarizing the contents of this pack.
  3002. Args:
  3003. progress: Progress function, called with current and total
  3004. object count.
  3005. Returns: iterator of tuples with (sha, offset, crc32)
  3006. """
  3007. return self.data.iterentries(
  3008. progress=progress, resolve_ext_ref=self.resolve_ext_ref
  3009. )
  3010. def sorted_entries(
  3011. self, progress: Optional[ProgressFn] = None
  3012. ) -> Iterator[PackIndexEntry]:
  3013. """Return entries in this pack, sorted by SHA.
  3014. Args:
  3015. progress: Progress function, called with current and total
  3016. object count
  3017. Returns: Iterator of tuples with (sha, offset, crc32)
  3018. """
  3019. return self.data.sorted_entries(
  3020. progress=progress, resolve_ext_ref=self.resolve_ext_ref
  3021. )
  3022. def get_unpacked_object(
  3023. self, sha: bytes, *, include_comp: bool = False, convert_ofs_delta: bool = True
  3024. ) -> UnpackedObject:
  3025. """Get the unpacked object for a sha.
  3026. Args:
  3027. sha: SHA of object to fetch
  3028. include_comp: Whether to include compression data in UnpackedObject
  3029. convert_ofs_delta: Whether to convert offset deltas to ref deltas
  3030. """
  3031. offset = self.index.object_offset(sha)
  3032. unpacked = self.data.get_unpacked_object_at(offset, include_comp=include_comp)
  3033. if unpacked.pack_type_num == OFS_DELTA and convert_ofs_delta:
  3034. assert isinstance(unpacked.delta_base, int)
  3035. unpacked.delta_base = self.index.object_sha1(offset - unpacked.delta_base)
  3036. unpacked.pack_type_num = REF_DELTA
  3037. return unpacked
  3038. def extend_pack(
  3039. f: BinaryIO,
  3040. object_ids: set[ObjectID],
  3041. get_raw,
  3042. *,
  3043. compression_level=-1,
  3044. progress=None,
  3045. ) -> tuple[bytes, list]:
  3046. """Extend a pack file with more objects.
  3047. The caller should make sure that object_ids does not contain any objects
  3048. that are already in the pack
  3049. """
  3050. # Update the header with the new number of objects.
  3051. f.seek(0)
  3052. _version, num_objects = read_pack_header(f.read)
  3053. if object_ids:
  3054. f.seek(0)
  3055. write_pack_header(f.write, num_objects + len(object_ids))
  3056. # Must flush before reading (http://bugs.python.org/issue3207)
  3057. f.flush()
  3058. # Rescan the rest of the pack, computing the SHA with the new header.
  3059. new_sha = compute_file_sha(f, end_ofs=-20)
  3060. # Must reposition before writing (http://bugs.python.org/issue3207)
  3061. f.seek(0, os.SEEK_CUR)
  3062. extra_entries = []
  3063. # Complete the pack.
  3064. for i, object_id in enumerate(object_ids):
  3065. if progress is not None:
  3066. progress(
  3067. (f"writing extra base objects: {i}/{len(object_ids)}\r").encode("ascii")
  3068. )
  3069. assert len(object_id) == 20
  3070. type_num, data = get_raw(object_id)
  3071. offset = f.tell()
  3072. crc32 = write_pack_object(
  3073. f.write,
  3074. type_num,
  3075. data,
  3076. sha=new_sha,
  3077. compression_level=compression_level,
  3078. )
  3079. extra_entries.append((object_id, offset, crc32))
  3080. pack_sha = new_sha.digest()
  3081. f.write(pack_sha)
  3082. return pack_sha, extra_entries
  3083. try:
  3084. from dulwich._pack import ( # type: ignore
  3085. apply_delta, # type: ignore
  3086. bisect_find_sha, # type: ignore
  3087. )
  3088. except ImportError:
  3089. pass