2
0

pack.py 77 KB

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