pack.py 88 KB

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