pack.py 100 KB

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