pack.py 139 KB

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