pack.py 71 KB

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