pack.py 100 KB

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