pack.py 90 KB

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