pack.py 38 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031
  1. # Copyright (C) 2010, 2011 Sebastian Thiel (byronimo@gmail.com) and contributors
  2. #
  3. # This module is part of GitDB and is released under
  4. # the New BSD License: https://opensource.org/license/bsd-3-clause/
  5. """Contains PackIndexFile and PackFile implementations"""
  6. import zlib
  7. from gitdb.exc import (
  8. BadObject,
  9. AmbiguousObjectName,
  10. UnsupportedOperation,
  11. ParseError
  12. )
  13. from gitdb.util import (
  14. mman,
  15. LazyMixin,
  16. unpack_from,
  17. bin_to_hex,
  18. byte_ord,
  19. )
  20. from gitdb.fun import (
  21. create_pack_object_header,
  22. pack_object_header_info,
  23. is_equal_canonical_sha,
  24. type_id_to_type_map,
  25. write_object,
  26. stream_copy,
  27. chunk_size,
  28. delta_types,
  29. OFS_DELTA,
  30. REF_DELTA,
  31. msb_size
  32. )
  33. try:
  34. from gitdb_speedups._perf import PackIndexFile_sha_to_index
  35. except ImportError:
  36. pass
  37. # END try c module
  38. from gitdb.base import ( # Amazing !
  39. OInfo,
  40. OStream,
  41. OPackInfo,
  42. OPackStream,
  43. ODeltaStream,
  44. ODeltaPackInfo,
  45. ODeltaPackStream,
  46. )
  47. from gitdb.stream import (
  48. DecompressMemMapReader,
  49. DeltaApplyReader,
  50. Sha1Writer,
  51. NullStream,
  52. FlexibleSha1Writer
  53. )
  54. from struct import pack
  55. from binascii import crc32
  56. from gitdb.const import NULL_BYTE
  57. import tempfile
  58. import array
  59. import os
  60. import sys
  61. __all__ = ('PackIndexFile', 'PackFile', 'PackEntity')
  62. #{ Utilities
  63. def pack_object_at(cursor, offset, as_stream):
  64. """
  65. :return: Tuple(abs_data_offset, PackInfo|PackStream)
  66. an object of the correct type according to the type_id of the object.
  67. If as_stream is True, the object will contain a stream, allowing the
  68. data to be read decompressed.
  69. :param data: random accessible data containing all required information
  70. :parma offset: offset in to the data at which the object information is located
  71. :param as_stream: if True, a stream object will be returned that can read
  72. the data, otherwise you receive an info object only"""
  73. data = cursor.use_region(offset).buffer()
  74. type_id, uncomp_size, data_rela_offset = pack_object_header_info(data)
  75. total_rela_offset = None # set later, actual offset until data stream begins
  76. delta_info = None
  77. # OFFSET DELTA
  78. if type_id == OFS_DELTA:
  79. i = data_rela_offset
  80. c = byte_ord(data[i])
  81. i += 1
  82. delta_offset = c & 0x7f
  83. while c & 0x80:
  84. c = byte_ord(data[i])
  85. i += 1
  86. delta_offset += 1
  87. delta_offset = (delta_offset << 7) + (c & 0x7f)
  88. # END character loop
  89. delta_info = delta_offset
  90. total_rela_offset = i
  91. # REF DELTA
  92. elif type_id == REF_DELTA:
  93. total_rela_offset = data_rela_offset + 20
  94. delta_info = data[data_rela_offset:total_rela_offset]
  95. # BASE OBJECT
  96. else:
  97. # assume its a base object
  98. total_rela_offset = data_rela_offset
  99. # END handle type id
  100. abs_data_offset = offset + total_rela_offset
  101. if as_stream:
  102. stream = DecompressMemMapReader(data[total_rela_offset:], False, uncomp_size)
  103. if delta_info is None:
  104. return abs_data_offset, OPackStream(offset, type_id, uncomp_size, stream)
  105. else:
  106. return abs_data_offset, ODeltaPackStream(offset, type_id, uncomp_size, delta_info, stream)
  107. else:
  108. if delta_info is None:
  109. return abs_data_offset, OPackInfo(offset, type_id, uncomp_size)
  110. else:
  111. return abs_data_offset, ODeltaPackInfo(offset, type_id, uncomp_size, delta_info)
  112. # END handle info
  113. # END handle stream
  114. def write_stream_to_pack(read, write, zstream, base_crc=None):
  115. """Copy a stream as read from read function, zip it, and write the result.
  116. Count the number of written bytes and return it
  117. :param base_crc: if not None, the crc will be the base for all compressed data
  118. we consecutively write and generate a crc32 from. If None, no crc will be generated
  119. :return: tuple(no bytes read, no bytes written, crc32) crc might be 0 if base_crc
  120. was false"""
  121. br = 0 # bytes read
  122. bw = 0 # bytes written
  123. want_crc = base_crc is not None
  124. crc = 0
  125. if want_crc:
  126. crc = base_crc
  127. # END initialize crc
  128. while True:
  129. chunk = read(chunk_size)
  130. br += len(chunk)
  131. compressed = zstream.compress(chunk)
  132. bw += len(compressed)
  133. write(compressed) # cannot assume return value
  134. if want_crc:
  135. crc = crc32(compressed, crc)
  136. # END handle crc
  137. if len(chunk) != chunk_size:
  138. break
  139. # END copy loop
  140. compressed = zstream.flush()
  141. bw += len(compressed)
  142. write(compressed)
  143. if want_crc:
  144. crc = crc32(compressed, crc)
  145. # END handle crc
  146. return (br, bw, crc)
  147. #} END utilities
  148. class IndexWriter:
  149. """Utility to cache index information, allowing to write all information later
  150. in one go to the given stream
  151. **Note:** currently only writes v2 indices"""
  152. __slots__ = '_objs'
  153. def __init__(self):
  154. self._objs = list()
  155. def append(self, binsha, crc, offset):
  156. """Append one piece of object information"""
  157. self._objs.append((binsha, crc, offset))
  158. def write(self, pack_sha, write):
  159. """Write the index file using the given write method
  160. :param pack_sha: binary sha over the whole pack that we index
  161. :return: sha1 binary sha over all index file contents"""
  162. # sort for sha1 hash
  163. self._objs.sort(key=lambda o: o[0])
  164. sha_writer = FlexibleSha1Writer(write)
  165. sha_write = sha_writer.write
  166. sha_write(PackIndexFile.index_v2_signature)
  167. sha_write(pack(">L", PackIndexFile.index_version_default))
  168. # fanout
  169. tmplist = list((0,) * 256) # fanout or list with 64 bit offsets
  170. for t in self._objs:
  171. tmplist[byte_ord(t[0][0])] += 1
  172. # END prepare fanout
  173. for i in range(255):
  174. v = tmplist[i]
  175. sha_write(pack('>L', v))
  176. tmplist[i + 1] += v
  177. # END write each fanout entry
  178. sha_write(pack('>L', tmplist[255]))
  179. # sha1 ordered
  180. # save calls, that is push them into c
  181. sha_write(b''.join(t[0] for t in self._objs))
  182. # crc32
  183. for t in self._objs:
  184. sha_write(pack('>L', t[1] & 0xffffffff))
  185. # END for each crc
  186. tmplist = list()
  187. # offset 32
  188. for t in self._objs:
  189. ofs = t[2]
  190. if ofs > 0x7fffffff:
  191. tmplist.append(ofs)
  192. ofs = 0x80000000 + len(tmplist) - 1
  193. # END handle 64 bit offsets
  194. sha_write(pack('>L', ofs & 0xffffffff))
  195. # END for each offset
  196. # offset 64
  197. for ofs in tmplist:
  198. sha_write(pack(">Q", ofs))
  199. # END for each offset
  200. # trailer
  201. assert(len(pack_sha) == 20)
  202. sha_write(pack_sha)
  203. sha = sha_writer.sha(as_hex=False)
  204. write(sha)
  205. return sha
  206. class PackIndexFile(LazyMixin):
  207. """A pack index provides offsets into the corresponding pack, allowing to find
  208. locations for offsets faster."""
  209. # Dont use slots as we dynamically bind functions for each version, need a dict for this
  210. # The slots you see here are just to keep track of our instance variables
  211. # __slots__ = ('_indexpath', '_fanout_table', '_cursor', '_version',
  212. # '_sha_list_offset', '_crc_list_offset', '_pack_offset', '_pack_64_offset')
  213. # used in v2 indices
  214. _sha_list_offset = 8 + 1024
  215. index_v2_signature = b'\xfftOc'
  216. index_version_default = 2
  217. def __init__(self, indexpath):
  218. super().__init__()
  219. self._indexpath = indexpath
  220. def close(self):
  221. mman.force_map_handle_removal_win(self._indexpath)
  222. self._cursor = None
  223. def _set_cache_(self, attr):
  224. if attr == "_packfile_checksum":
  225. self._packfile_checksum = self._cursor.map()[-40:-20]
  226. elif attr == "_packfile_checksum":
  227. self._packfile_checksum = self._cursor.map()[-20:]
  228. elif attr == "_cursor":
  229. # Note: We don't lock the file when reading as we cannot be sure
  230. # that we can actually write to the location - it could be a read-only
  231. # alternate for instance
  232. self._cursor = mman.make_cursor(self._indexpath).use_region()
  233. # We will assume that the index will always fully fit into memory !
  234. if mman.window_size() > 0 and self._cursor.file_size() > mman.window_size():
  235. raise AssertionError("The index file at %s is too large to fit into a mapped window (%i > %i). This is a limitation of the implementation" % (
  236. self._indexpath, self._cursor.file_size(), mman.window_size()))
  237. # END assert window size
  238. else:
  239. # now its time to initialize everything - if we are here, someone wants
  240. # to access the fanout table or related properties
  241. # CHECK VERSION
  242. mmap = self._cursor.map()
  243. self._version = (mmap[:4] == self.index_v2_signature and 2) or 1
  244. if self._version == 2:
  245. version_id = unpack_from(">L", mmap, 4)[0]
  246. assert version_id == self._version, "Unsupported index version: %i" % version_id
  247. # END assert version
  248. # SETUP FUNCTIONS
  249. # setup our functions according to the actual version
  250. for fname in ('entry', 'offset', 'sha', 'crc'):
  251. setattr(self, fname, getattr(self, "_%s_v%i" % (fname, self._version)))
  252. # END for each function to initialize
  253. # INITIALIZE DATA
  254. # byte offset is 8 if version is 2, 0 otherwise
  255. self._initialize()
  256. # END handle attributes
  257. #{ Access V1
  258. def _entry_v1(self, i):
  259. """:return: tuple(offset, binsha, 0)"""
  260. return unpack_from(">L20s", self._cursor.map(), 1024 + i * 24) + (0, )
  261. def _offset_v1(self, i):
  262. """see ``_offset_v2``"""
  263. return unpack_from(">L", self._cursor.map(), 1024 + i * 24)[0]
  264. def _sha_v1(self, i):
  265. """see ``_sha_v2``"""
  266. base = 1024 + (i * 24) + 4
  267. return self._cursor.map()[base:base + 20]
  268. def _crc_v1(self, i):
  269. """unsupported"""
  270. return 0
  271. #} END access V1
  272. #{ Access V2
  273. def _entry_v2(self, i):
  274. """:return: tuple(offset, binsha, crc)"""
  275. return (self._offset_v2(i), self._sha_v2(i), self._crc_v2(i))
  276. def _offset_v2(self, i):
  277. """:return: 32 or 64 byte offset into pack files. 64 byte offsets will only
  278. be returned if the pack is larger than 4 GiB, or 2^32"""
  279. offset = unpack_from(">L", self._cursor.map(), self._pack_offset + i * 4)[0]
  280. # if the high-bit is set, this indicates that we have to lookup the offset
  281. # in the 64 bit region of the file. The current offset ( lower 31 bits )
  282. # are the index into it
  283. if offset & 0x80000000:
  284. offset = unpack_from(">Q", self._cursor.map(), self._pack_64_offset + (offset & ~0x80000000) * 8)[0]
  285. # END handle 64 bit offset
  286. return offset
  287. def _sha_v2(self, i):
  288. """:return: sha at the given index of this file index instance"""
  289. base = self._sha_list_offset + i * 20
  290. return self._cursor.map()[base:base + 20]
  291. def _crc_v2(self, i):
  292. """:return: 4 bytes crc for the object at index i"""
  293. return unpack_from(">L", self._cursor.map(), self._crc_list_offset + i * 4)[0]
  294. #} END access V2
  295. #{ Initialization
  296. def _initialize(self):
  297. """initialize base data"""
  298. self._fanout_table = self._read_fanout((self._version == 2) * 8)
  299. if self._version == 2:
  300. self._crc_list_offset = self._sha_list_offset + self.size() * 20
  301. self._pack_offset = self._crc_list_offset + self.size() * 4
  302. self._pack_64_offset = self._pack_offset + self.size() * 4
  303. # END setup base
  304. def _read_fanout(self, byte_offset):
  305. """Generate a fanout table from our data"""
  306. d = self._cursor.map()
  307. out = list()
  308. append = out.append
  309. for i in range(256):
  310. append(unpack_from('>L', d, byte_offset + i * 4)[0])
  311. # END for each entry
  312. return out
  313. #} END initialization
  314. #{ Properties
  315. def version(self):
  316. return self._version
  317. def size(self):
  318. """:return: amount of objects referred to by this index"""
  319. return self._fanout_table[255]
  320. def path(self):
  321. """:return: path to the packindexfile"""
  322. return self._indexpath
  323. def packfile_checksum(self):
  324. """:return: 20 byte sha representing the sha1 hash of the pack file"""
  325. return self._cursor.map()[-40:-20]
  326. def indexfile_checksum(self):
  327. """:return: 20 byte sha representing the sha1 hash of this index file"""
  328. return self._cursor.map()[-20:]
  329. def offsets(self):
  330. """:return: sequence of all offsets in the order in which they were written
  331. **Note:** return value can be random accessed, but may be immmutable"""
  332. if self._version == 2:
  333. # read stream to array, convert to tuple
  334. a = array.array('I') # 4 byte unsigned int, long are 8 byte on 64 bit it appears
  335. a.frombytes(self._cursor.map()[self._pack_offset:self._pack_64_offset])
  336. # networkbyteorder to something array likes more
  337. if sys.byteorder == 'little':
  338. a.byteswap()
  339. return a
  340. else:
  341. return tuple(self.offset(index) for index in range(self.size()))
  342. # END handle version
  343. def sha_to_index(self, sha):
  344. """
  345. :return: index usable with the ``offset`` or ``entry`` method, or None
  346. if the sha was not found in this pack index
  347. :param sha: 20 byte sha to lookup"""
  348. first_byte = byte_ord(sha[0])
  349. get_sha = self.sha
  350. lo = 0 # lower index, the left bound of the bisection
  351. if first_byte != 0:
  352. lo = self._fanout_table[first_byte - 1]
  353. hi = self._fanout_table[first_byte] # the upper, right bound of the bisection
  354. # bisect until we have the sha
  355. while lo < hi:
  356. mid = (lo + hi) // 2
  357. mid_sha = get_sha(mid)
  358. if sha < mid_sha:
  359. hi = mid
  360. elif sha == mid_sha:
  361. return mid
  362. else:
  363. lo = mid + 1
  364. # END handle midpoint
  365. # END bisect
  366. return None
  367. def partial_sha_to_index(self, partial_bin_sha, canonical_length):
  368. """
  369. :return: index as in `sha_to_index` or None if the sha was not found in this
  370. index file
  371. :param partial_bin_sha: an at least two bytes of a partial binary sha as bytes
  372. :param canonical_length: length of the original hexadecimal representation of the
  373. given partial binary sha
  374. :raise AmbiguousObjectName:"""
  375. if len(partial_bin_sha) < 2:
  376. raise ValueError("Require at least 2 bytes of partial sha")
  377. assert isinstance(partial_bin_sha, bytes), "partial_bin_sha must be bytes"
  378. first_byte = byte_ord(partial_bin_sha[0])
  379. get_sha = self.sha
  380. lo = 0 # lower index, the left bound of the bisection
  381. if first_byte != 0:
  382. lo = self._fanout_table[first_byte - 1]
  383. hi = self._fanout_table[first_byte] # the upper, right bound of the bisection
  384. # fill the partial to full 20 bytes
  385. filled_sha = partial_bin_sha + NULL_BYTE * (20 - len(partial_bin_sha))
  386. # find lowest
  387. while lo < hi:
  388. mid = (lo + hi) // 2
  389. mid_sha = get_sha(mid)
  390. if filled_sha < mid_sha:
  391. hi = mid
  392. elif filled_sha == mid_sha:
  393. # perfect match
  394. lo = mid
  395. break
  396. else:
  397. lo = mid + 1
  398. # END handle midpoint
  399. # END bisect
  400. if lo < self.size():
  401. cur_sha = get_sha(lo)
  402. if is_equal_canonical_sha(canonical_length, partial_bin_sha, cur_sha):
  403. next_sha = None
  404. if lo + 1 < self.size():
  405. next_sha = get_sha(lo + 1)
  406. if next_sha and next_sha == cur_sha:
  407. raise AmbiguousObjectName(partial_bin_sha)
  408. return lo
  409. # END if we have a match
  410. # END if we found something
  411. return None
  412. if 'PackIndexFile_sha_to_index' in globals():
  413. # NOTE: Its just about 25% faster, the major bottleneck might be the attr
  414. # accesses
  415. def sha_to_index(self, sha):
  416. return PackIndexFile_sha_to_index(self, sha)
  417. # END redefine heavy-hitter with c version
  418. #} END properties
  419. class PackFile(LazyMixin):
  420. """A pack is a file written according to the Version 2 for git packs
  421. As we currently use memory maps, it could be assumed that the maximum size of
  422. packs therefore is 32 bit on 32 bit systems. On 64 bit systems, this should be
  423. fine though.
  424. **Note:** at some point, this might be implemented using streams as well, or
  425. streams are an alternate path in the case memory maps cannot be created
  426. for some reason - one clearly doesn't want to read 10GB at once in that
  427. case"""
  428. __slots__ = ('_packpath', '_cursor', '_size', '_version')
  429. pack_signature = 0x5041434b # 'PACK'
  430. pack_version_default = 2
  431. # offset into our data at which the first object starts
  432. first_object_offset = 3 * 4 # header bytes
  433. footer_size = 20 # final sha
  434. def __init__(self, packpath):
  435. self._packpath = packpath
  436. def close(self):
  437. mman.force_map_handle_removal_win(self._packpath)
  438. self._cursor = None
  439. def _set_cache_(self, attr):
  440. # we fill the whole cache, whichever attribute gets queried first
  441. self._cursor = mman.make_cursor(self._packpath).use_region()
  442. # read the header information
  443. type_id, self._version, self._size = unpack_from(">LLL", self._cursor.map(), 0)
  444. # TODO: figure out whether we should better keep the lock, or maybe
  445. # add a .keep file instead ?
  446. if type_id != self.pack_signature:
  447. raise ParseError("Invalid pack signature: %i" % type_id)
  448. def _iter_objects(self, start_offset, as_stream=True):
  449. """Handle the actual iteration of objects within this pack"""
  450. c = self._cursor
  451. content_size = c.file_size() - self.footer_size
  452. cur_offset = start_offset or self.first_object_offset
  453. null = NullStream()
  454. while cur_offset < content_size:
  455. data_offset, ostream = pack_object_at(c, cur_offset, True)
  456. # scrub the stream to the end - this decompresses the object, but yields
  457. # the amount of compressed bytes we need to get to the next offset
  458. stream_copy(ostream.read, null.write, ostream.size, chunk_size)
  459. assert ostream.stream._br == ostream.size
  460. cur_offset += (data_offset - ostream.pack_offset) + ostream.stream.compressed_bytes_read()
  461. # if a stream is requested, reset it beforehand
  462. # Otherwise return the Stream object directly, its derived from the
  463. # info object
  464. if as_stream:
  465. ostream.stream.seek(0)
  466. yield ostream
  467. # END until we have read everything
  468. #{ Pack Information
  469. def size(self):
  470. """:return: The amount of objects stored in this pack"""
  471. return self._size
  472. def version(self):
  473. """:return: the version of this pack"""
  474. return self._version
  475. def data(self):
  476. """
  477. :return: read-only data of this pack. It provides random access and usually
  478. is a memory map.
  479. :note: This method is unsafe as it returns a window into a file which might be larger than than the actual window size"""
  480. # can use map as we are starting at offset 0. Otherwise we would have to use buffer()
  481. return self._cursor.use_region().map()
  482. def checksum(self):
  483. """:return: 20 byte sha1 hash on all object sha's contained in this file"""
  484. return self._cursor.use_region(self._cursor.file_size() - 20).buffer()[:]
  485. def path(self):
  486. """:return: path to the packfile"""
  487. return self._packpath
  488. #} END pack information
  489. #{ Pack Specific
  490. def collect_streams(self, offset):
  491. """
  492. :return: list of pack streams which are required to build the object
  493. at the given offset. The first entry of the list is the object at offset,
  494. the last one is either a full object, or a REF_Delta stream. The latter
  495. type needs its reference object to be locked up in an ODB to form a valid
  496. delta chain.
  497. If the object at offset is no delta, the size of the list is 1.
  498. :param offset: specifies the first byte of the object within this pack"""
  499. out = list()
  500. c = self._cursor
  501. while True:
  502. ostream = pack_object_at(c, offset, True)[1]
  503. out.append(ostream)
  504. if ostream.type_id == OFS_DELTA:
  505. offset = ostream.pack_offset - ostream.delta_info
  506. else:
  507. # the only thing we can lookup are OFFSET deltas. Everything
  508. # else is either an object, or a ref delta, in the latter
  509. # case someone else has to find it
  510. break
  511. # END handle type
  512. # END while chaining streams
  513. return out
  514. #} END pack specific
  515. #{ Read-Database like Interface
  516. def info(self, offset):
  517. """Retrieve information about the object at the given file-absolute offset
  518. :param offset: byte offset
  519. :return: OPackInfo instance, the actual type differs depending on the type_id attribute"""
  520. return pack_object_at(self._cursor, offset or self.first_object_offset, False)[1]
  521. def stream(self, offset):
  522. """Retrieve an object at the given file-relative offset as stream along with its information
  523. :param offset: byte offset
  524. :return: OPackStream instance, the actual type differs depending on the type_id attribute"""
  525. return pack_object_at(self._cursor, offset or self.first_object_offset, True)[1]
  526. def stream_iter(self, start_offset=0):
  527. """
  528. :return: iterator yielding OPackStream compatible instances, allowing
  529. to access the data in the pack directly.
  530. :param start_offset: offset to the first object to iterate. If 0, iteration
  531. starts at the very first object in the pack.
  532. **Note:** Iterating a pack directly is costly as the datastream has to be decompressed
  533. to determine the bounds between the objects"""
  534. return self._iter_objects(start_offset, as_stream=True)
  535. #} END Read-Database like Interface
  536. class PackEntity(LazyMixin):
  537. """Combines the PackIndexFile and the PackFile into one, allowing the
  538. actual objects to be resolved and iterated"""
  539. __slots__ = ('_index', # our index file
  540. '_pack', # our pack file
  541. '_offset_map' # on demand dict mapping one offset to the next consecutive one
  542. )
  543. IndexFileCls = PackIndexFile
  544. PackFileCls = PackFile
  545. def __init__(self, pack_or_index_path):
  546. """Initialize ourselves with the path to the respective pack or index file"""
  547. basename, ext = os.path.splitext(pack_or_index_path)
  548. self._index = self.IndexFileCls("%s.idx" % basename) # PackIndexFile instance
  549. self._pack = self.PackFileCls("%s.pack" % basename) # corresponding PackFile instance
  550. def close(self):
  551. self._index.close()
  552. self._pack.close()
  553. def _set_cache_(self, attr):
  554. # currently this can only be _offset_map
  555. # TODO: make this a simple sorted offset array which can be bisected
  556. # to find the respective entry, from which we can take a +1 easily
  557. # This might be slower, but should also be much lighter in memory !
  558. offsets_sorted = sorted(self._index.offsets())
  559. last_offset = len(self._pack.data()) - self._pack.footer_size
  560. assert offsets_sorted, "Cannot handle empty indices"
  561. offset_map = None
  562. if len(offsets_sorted) == 1:
  563. offset_map = {offsets_sorted[0]: last_offset}
  564. else:
  565. iter_offsets = iter(offsets_sorted)
  566. iter_offsets_plus_one = iter(offsets_sorted)
  567. next(iter_offsets_plus_one)
  568. consecutive = zip(iter_offsets, iter_offsets_plus_one)
  569. offset_map = dict(consecutive)
  570. # the last offset is not yet set
  571. offset_map[offsets_sorted[-1]] = last_offset
  572. # END handle offset amount
  573. self._offset_map = offset_map
  574. def _sha_to_index(self, sha):
  575. """:return: index for the given sha, or raise"""
  576. index = self._index.sha_to_index(sha)
  577. if index is None:
  578. raise BadObject(sha)
  579. return index
  580. def _iter_objects(self, as_stream):
  581. """Iterate over all objects in our index and yield their OInfo or OStream instences"""
  582. _sha = self._index.sha
  583. _object = self._object
  584. for index in range(self._index.size()):
  585. yield _object(_sha(index), as_stream, index)
  586. # END for each index
  587. def _object(self, sha, as_stream, index=-1):
  588. """:return: OInfo or OStream object providing information about the given sha
  589. :param index: if not -1, its assumed to be the sha's index in the IndexFile"""
  590. # its a little bit redundant here, but it needs to be efficient
  591. if index < 0:
  592. index = self._sha_to_index(sha)
  593. if sha is None:
  594. sha = self._index.sha(index)
  595. # END assure sha is present ( in output )
  596. offset = self._index.offset(index)
  597. type_id, uncomp_size, data_rela_offset = pack_object_header_info(self._pack._cursor.use_region(offset).buffer())
  598. if as_stream:
  599. if type_id not in delta_types:
  600. packstream = self._pack.stream(offset)
  601. return OStream(sha, packstream.type, packstream.size, packstream.stream)
  602. # END handle non-deltas
  603. # produce a delta stream containing all info
  604. # To prevent it from applying the deltas when querying the size,
  605. # we extract it from the delta stream ourselves
  606. streams = self.collect_streams_at_offset(offset)
  607. dstream = DeltaApplyReader.new(streams)
  608. return ODeltaStream(sha, dstream.type, None, dstream)
  609. else:
  610. if type_id not in delta_types:
  611. return OInfo(sha, type_id_to_type_map[type_id], uncomp_size)
  612. # END handle non-deltas
  613. # deltas are a little tougher - unpack the first bytes to obtain
  614. # the actual target size, as opposed to the size of the delta data
  615. streams = self.collect_streams_at_offset(offset)
  616. buf = streams[0].read(512)
  617. offset, src_size = msb_size(buf)
  618. offset, target_size = msb_size(buf, offset)
  619. # collect the streams to obtain the actual object type
  620. if streams[-1].type_id in delta_types:
  621. raise BadObject(sha, "Could not resolve delta object")
  622. return OInfo(sha, streams[-1].type, target_size)
  623. # END handle stream
  624. #{ Read-Database like Interface
  625. def info(self, sha):
  626. """Retrieve information about the object identified by the given sha
  627. :param sha: 20 byte sha1
  628. :raise BadObject:
  629. :return: OInfo instance, with 20 byte sha"""
  630. return self._object(sha, False)
  631. def stream(self, sha):
  632. """Retrieve an object stream along with its information as identified by the given sha
  633. :param sha: 20 byte sha1
  634. :raise BadObject:
  635. :return: OStream instance, with 20 byte sha"""
  636. return self._object(sha, True)
  637. def info_at_index(self, index):
  638. """As ``info``, but uses a PackIndexFile compatible index to refer to the object"""
  639. return self._object(None, False, index)
  640. def stream_at_index(self, index):
  641. """As ``stream``, but uses a PackIndexFile compatible index to refer to the
  642. object"""
  643. return self._object(None, True, index)
  644. #} END Read-Database like Interface
  645. #{ Interface
  646. def pack(self):
  647. """:return: the underlying pack file instance"""
  648. return self._pack
  649. def index(self):
  650. """:return: the underlying pack index file instance"""
  651. return self._index
  652. def is_valid_stream(self, sha, use_crc=False):
  653. """
  654. Verify that the stream at the given sha is valid.
  655. :param use_crc: if True, the index' crc is run over the compressed stream of
  656. the object, which is much faster than checking the sha1. It is also
  657. more prone to unnoticed corruption or manipulation.
  658. :param sha: 20 byte sha1 of the object whose stream to verify
  659. whether the compressed stream of the object is valid. If it is
  660. a delta, this only verifies that the delta's data is valid, not the
  661. data of the actual undeltified object, as it depends on more than
  662. just this stream.
  663. If False, the object will be decompressed and the sha generated. It must
  664. match the given sha
  665. :return: True if the stream is valid
  666. :raise UnsupportedOperation: If the index is version 1 only
  667. :raise BadObject: sha was not found"""
  668. if use_crc:
  669. if self._index.version() < 2:
  670. raise UnsupportedOperation("Version 1 indices do not contain crc's, verify by sha instead")
  671. # END handle index version
  672. index = self._sha_to_index(sha)
  673. offset = self._index.offset(index)
  674. next_offset = self._offset_map[offset]
  675. crc_value = self._index.crc(index)
  676. # create the current crc value, on the compressed object data
  677. # Read it in chunks, without copying the data
  678. crc_update = zlib.crc32
  679. pack_data = self._pack.data()
  680. cur_pos = offset
  681. this_crc_value = 0
  682. while cur_pos < next_offset:
  683. rbound = min(cur_pos + chunk_size, next_offset)
  684. size = rbound - cur_pos
  685. this_crc_value = crc_update(pack_data[cur_pos:cur_pos + size], this_crc_value)
  686. cur_pos += size
  687. # END window size loop
  688. # crc returns signed 32 bit numbers, the AND op forces it into unsigned
  689. # mode ... wow, sneaky, from dulwich.
  690. return (this_crc_value & 0xffffffff) == crc_value
  691. else:
  692. shawriter = Sha1Writer()
  693. stream = self._object(sha, as_stream=True)
  694. # write a loose object, which is the basis for the sha
  695. write_object(stream.type, stream.size, stream.read, shawriter.write)
  696. assert shawriter.sha(as_hex=False) == sha
  697. return shawriter.sha(as_hex=False) == sha
  698. # END handle crc/sha verification
  699. return True
  700. def info_iter(self):
  701. """
  702. :return: Iterator over all objects in this pack. The iterator yields
  703. OInfo instances"""
  704. return self._iter_objects(as_stream=False)
  705. def stream_iter(self):
  706. """
  707. :return: iterator over all objects in this pack. The iterator yields
  708. OStream instances"""
  709. return self._iter_objects(as_stream=True)
  710. def collect_streams_at_offset(self, offset):
  711. """
  712. As the version in the PackFile, but can resolve REF deltas within this pack
  713. For more info, see ``collect_streams``
  714. :param offset: offset into the pack file at which the object can be found"""
  715. streams = self._pack.collect_streams(offset)
  716. # try to resolve the last one if needed. It is assumed to be either
  717. # a REF delta, or a base object, as OFFSET deltas are resolved by the pack
  718. if streams[-1].type_id == REF_DELTA:
  719. stream = streams[-1]
  720. while stream.type_id in delta_types:
  721. if stream.type_id == REF_DELTA:
  722. # smmap can return memory view objects, which can't be compared as buffers/bytes can ...
  723. if isinstance(stream.delta_info, memoryview):
  724. sindex = self._index.sha_to_index(stream.delta_info.tobytes())
  725. else:
  726. sindex = self._index.sha_to_index(stream.delta_info)
  727. if sindex is None:
  728. break
  729. stream = self._pack.stream(self._index.offset(sindex))
  730. streams.append(stream)
  731. else:
  732. # must be another OFS DELTA - this could happen if a REF
  733. # delta we resolve previously points to an OFS delta. Who
  734. # would do that ;) ? We can handle it though
  735. stream = self._pack.stream(stream.delta_info)
  736. streams.append(stream)
  737. # END handle ref delta
  738. # END resolve ref streams
  739. # END resolve streams
  740. return streams
  741. def collect_streams(self, sha):
  742. """
  743. As ``PackFile.collect_streams``, but takes a sha instead of an offset.
  744. Additionally, ref_delta streams will be resolved within this pack.
  745. If this is not possible, the stream will be left alone, hence it is adivsed
  746. to check for unresolved ref-deltas and resolve them before attempting to
  747. construct a delta stream.
  748. :param sha: 20 byte sha1 specifying the object whose related streams you want to collect
  749. :return: list of streams, first being the actual object delta, the last being
  750. a possibly unresolved base object.
  751. :raise BadObject:"""
  752. return self.collect_streams_at_offset(self._index.offset(self._sha_to_index(sha)))
  753. @classmethod
  754. def write_pack(cls, object_iter, pack_write, index_write=None,
  755. object_count=None, zlib_compression=zlib.Z_BEST_SPEED):
  756. """
  757. Create a new pack by putting all objects obtained by the object_iterator
  758. into a pack which is written using the pack_write method.
  759. The respective index is produced as well if index_write is not Non.
  760. :param object_iter: iterator yielding odb output objects
  761. :param pack_write: function to receive strings to write into the pack stream
  762. :param indx_write: if not None, the function writes the index file corresponding
  763. to the pack.
  764. :param object_count: if you can provide the amount of objects in your iteration,
  765. this would be the place to put it. Otherwise we have to pre-iterate and store
  766. all items into a list to get the number, which uses more memory than necessary.
  767. :param zlib_compression: the zlib compression level to use
  768. :return: tuple(pack_sha, index_binsha) binary sha over all the contents of the pack
  769. and over all contents of the index. If index_write was None, index_binsha will be None
  770. **Note:** The destination of the write functions is up to the user. It could
  771. be a socket, or a file for instance
  772. **Note:** writes only undeltified objects"""
  773. objs = object_iter
  774. if not object_count:
  775. if not isinstance(object_iter, (tuple, list)):
  776. objs = list(object_iter)
  777. # END handle list type
  778. object_count = len(objs)
  779. # END handle object
  780. pack_writer = FlexibleSha1Writer(pack_write)
  781. pwrite = pack_writer.write
  782. ofs = 0 # current offset into the pack file
  783. index = None
  784. wants_index = index_write is not None
  785. # write header
  786. pwrite(pack('>LLL', PackFile.pack_signature, PackFile.pack_version_default, object_count))
  787. ofs += 12
  788. if wants_index:
  789. index = IndexWriter()
  790. # END handle index header
  791. actual_count = 0
  792. for obj in objs:
  793. actual_count += 1
  794. crc = 0
  795. # object header
  796. hdr = create_pack_object_header(obj.type_id, obj.size)
  797. if index_write:
  798. crc = crc32(hdr)
  799. else:
  800. crc = None
  801. # END handle crc
  802. pwrite(hdr)
  803. # data stream
  804. zstream = zlib.compressobj(zlib_compression)
  805. ostream = obj.stream
  806. br, bw, crc = write_stream_to_pack(ostream.read, pwrite, zstream, base_crc=crc)
  807. assert(br == obj.size)
  808. if wants_index:
  809. index.append(obj.binsha, crc, ofs)
  810. # END handle index
  811. ofs += len(hdr) + bw
  812. if actual_count == object_count:
  813. break
  814. # END abort once we are done
  815. # END for each object
  816. if actual_count != object_count:
  817. raise ValueError(
  818. "Expected to write %i objects into pack, but received only %i from iterators" % (object_count, actual_count))
  819. # END count assertion
  820. # write footer
  821. pack_sha = pack_writer.sha(as_hex=False)
  822. assert len(pack_sha) == 20
  823. pack_write(pack_sha)
  824. ofs += len(pack_sha) # just for completeness ;)
  825. index_sha = None
  826. if wants_index:
  827. index_sha = index.write(pack_sha, index_write)
  828. # END handle index
  829. return pack_sha, index_sha
  830. @classmethod
  831. def create(cls, object_iter, base_dir, object_count=None, zlib_compression=zlib.Z_BEST_SPEED):
  832. """Create a new on-disk entity comprised of a properly named pack file and a properly named
  833. and corresponding index file. The pack contains all OStream objects contained in object iter.
  834. :param base_dir: directory which is to contain the files
  835. :return: PackEntity instance initialized with the new pack
  836. **Note:** for more information on the other parameters see the write_pack method"""
  837. pack_fd, pack_path = tempfile.mkstemp('', 'pack', base_dir)
  838. index_fd, index_path = tempfile.mkstemp('', 'index', base_dir)
  839. pack_write = lambda d: os.write(pack_fd, d)
  840. index_write = lambda d: os.write(index_fd, d)
  841. pack_binsha, index_binsha = cls.write_pack(object_iter, pack_write, index_write, object_count, zlib_compression)
  842. os.close(pack_fd)
  843. os.close(index_fd)
  844. fmt = "pack-%s.%s"
  845. new_pack_path = os.path.join(base_dir, fmt % (bin_to_hex(pack_binsha), 'pack'))
  846. new_index_path = os.path.join(base_dir, fmt % (bin_to_hex(pack_binsha), 'idx'))
  847. os.rename(pack_path, new_pack_path)
  848. os.rename(index_path, new_index_path)
  849. return cls(new_pack_path)
  850. #} END interface