pack.py 146 KB

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