pack.py 90 KB

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