pack.py 82 KB

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