pack.py 88 KB

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