pack.py 79 KB

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