pack.py 68 KB

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