pack.py 74 KB

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