pack.py 88 KB

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