pack.py 88 KB

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