pack.py 88 KB

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