pack.py 127 KB

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