pack.py 147 KB

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