pack.py 90 KB

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