pack.py 70 KB

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