pack.py 38 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163
  1. # pack.py -- For dealing wih packed git objects.
  2. # Copyright (C) 2007 James Westby <jw+debian@jameswestby.net>
  3. # Copryight (C) 2008-2009 Jelmer Vernooij <jelmer@samba.org>
  4. #
  5. # This program is free software; you can redistribute it and/or
  6. # modify it under the terms of the GNU General Public License
  7. # as published by the Free Software Foundation; version 2
  8. # of the License or (at your option) a later version.
  9. #
  10. # This program is distributed in the hope that it will be useful,
  11. # but WITHOUT ANY WARRANTY; without even the implied warranty of
  12. # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  13. # GNU General Public License for more details.
  14. #
  15. # You should have received a copy of the GNU General Public License
  16. # along with this program; if not, write to the Free Software
  17. # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
  18. # MA 02110-1301, USA.
  19. """Classes for dealing with packed git objects.
  20. A pack is a compact representation of a bunch of objects, stored
  21. using deltas where possible.
  22. They have two parts, the pack file, which stores the data, and an index
  23. that tells you where the data is.
  24. To find an object you look in all of the index files 'til you find a
  25. match for the object name. You then use the pointer got from this as
  26. a pointer in to the corresponding packfile.
  27. """
  28. try:
  29. from collections import defaultdict
  30. except ImportError:
  31. from misc import defaultdict
  32. import difflib
  33. from itertools import (
  34. chain,
  35. imap,
  36. izip,
  37. )
  38. import mmap
  39. import os
  40. import struct
  41. try:
  42. from struct import unpack_from
  43. except ImportError:
  44. from dulwich.misc import unpack_from
  45. import sys
  46. import zlib
  47. from dulwich.errors import (
  48. ApplyDeltaError,
  49. ChecksumMismatch,
  50. )
  51. from dulwich.file import GitFile
  52. from dulwich.lru_cache import (
  53. LRUSizeCache,
  54. )
  55. from dulwich.objects import (
  56. ShaFile,
  57. hex_to_sha,
  58. sha_to_hex,
  59. )
  60. from dulwich.misc import (
  61. make_sha,
  62. )
  63. supports_mmap_offset = (sys.version_info[0] >= 3 or
  64. (sys.version_info[0] == 2 and sys.version_info[1] >= 6))
  65. def take_msb_bytes(read):
  66. """Read bytes marked with most significant bit.
  67. :param read: Read function
  68. """
  69. ret = []
  70. while len(ret) == 0 or ret[-1] & 0x80:
  71. ret.append(ord(read(1)))
  72. return ret
  73. def read_zlib_chunks(read, buffer_size=4096):
  74. """Read chunks of zlib data from a buffer.
  75. :param read: Read function
  76. :return: Tuple with list of chunks, length of
  77. compressed data length and unused read data
  78. """
  79. obj = zlib.decompressobj()
  80. ret = []
  81. fed = 0
  82. while obj.unused_data == "":
  83. add = read(buffer_size)
  84. if len(add) < buffer_size:
  85. add += "Z"
  86. fed += len(add)
  87. ret.append(obj.decompress(add))
  88. comp_len = fed-len(obj.unused_data)
  89. return ret, comp_len, obj.unused_data
  90. def iter_sha1(iter):
  91. """Return the hexdigest of the SHA1 over a set of names.
  92. :param iter: Iterator over string objects
  93. :return: 40-byte hex sha1 digest
  94. """
  95. sha1 = make_sha()
  96. for name in iter:
  97. sha1.update(name)
  98. return sha1.hexdigest()
  99. def load_pack_index(path):
  100. """Load an index file by path.
  101. :param filename: Path to the index file
  102. """
  103. f = GitFile(path, 'rb')
  104. return load_pack_index_file(path, f)
  105. def load_pack_index_file(path, f):
  106. """Load an index file from a file-like object.
  107. :param path: Path for the index file
  108. :param f: File-like object
  109. """
  110. if f.read(4) == '\377tOc':
  111. version = struct.unpack(">L", f.read(4))[0]
  112. if version == 2:
  113. f.seek(0)
  114. return PackIndex2(path, file=f)
  115. else:
  116. raise KeyError("Unknown pack index format %d" % version)
  117. else:
  118. f.seek(0)
  119. return PackIndex1(path, file=f)
  120. def bisect_find_sha(start, end, sha, unpack_name):
  121. """Find a SHA in a data blob with sorted SHAs.
  122. :param start: Start index of range to search
  123. :param end: End index of range to search
  124. :param sha: Sha to find
  125. :param unpack_name: Callback to retrieve SHA by index
  126. :return: Index of the SHA, or None if it wasn't found
  127. """
  128. assert start <= end
  129. while start <= end:
  130. i = (start + end)/2
  131. file_sha = unpack_name(i)
  132. x = cmp(file_sha, sha)
  133. if x < 0:
  134. start = i + 1
  135. elif x > 0:
  136. end = i - 1
  137. else:
  138. return i
  139. return None
  140. class PackIndex(object):
  141. """An index in to a packfile.
  142. Given a sha id of an object a pack index can tell you the location in the
  143. packfile of that object if it has it.
  144. To do the loop it opens the file, and indexes first 256 4 byte groups
  145. with the first byte of the sha id. The value in the four byte group indexed
  146. is the end of the group that shares the same starting byte. Subtract one
  147. from the starting byte and index again to find the start of the group.
  148. The values are sorted by sha id within the group, so do the math to find
  149. the start and end offset and then bisect in to find if the value is present.
  150. """
  151. def __init__(self, filename, file=None, size=None):
  152. """Create a pack index object.
  153. Provide it with the name of the index file to consider, and it will map
  154. it whenever required.
  155. """
  156. self._filename = filename
  157. # Take the size now, so it can be checked each time we map the file to
  158. # ensure that it hasn't changed.
  159. if file is None:
  160. self._file = GitFile(filename, 'rb')
  161. else:
  162. self._file = file
  163. fileno = getattr(self._file, 'fileno', None)
  164. if fileno is not None:
  165. fd = self._file.fileno()
  166. if size is None:
  167. self._size = os.fstat(fd).st_size
  168. else:
  169. self._size = size
  170. self._contents = mmap.mmap(fd, self._size,
  171. access=mmap.ACCESS_READ)
  172. else:
  173. self._file.seek(0)
  174. self._contents = self._file.read()
  175. self._size = len(self._contents)
  176. def __eq__(self, other):
  177. if not isinstance(other, PackIndex):
  178. return False
  179. if self._fan_out_table != other._fan_out_table:
  180. return False
  181. for (name1, _, _), (name2, _, _) in izip(self.iterentries(), other.iterentries()):
  182. if name1 != name2:
  183. return False
  184. return True
  185. def __ne__(self, other):
  186. return not self.__eq__(other)
  187. def close(self):
  188. self._file.close()
  189. def __len__(self):
  190. """Return the number of entries in this pack index."""
  191. return self._fan_out_table[-1]
  192. def _unpack_entry(self, i):
  193. """Unpack the i-th entry in the index file.
  194. :return: Tuple with object name (SHA), offset in pack file and
  195. CRC32 checksum (if known)."""
  196. raise NotImplementedError(self._unpack_entry)
  197. def _unpack_name(self, i):
  198. """Unpack the i-th name from the index file."""
  199. raise NotImplementedError(self._unpack_name)
  200. def _unpack_offset(self, i):
  201. """Unpack the i-th object offset from the index file."""
  202. raise NotImplementedError(self._unpack_offset)
  203. def _unpack_crc32_checksum(self, i):
  204. """Unpack the crc32 checksum for the i-th object from the index file."""
  205. raise NotImplementedError(self._unpack_crc32_checksum)
  206. def __iter__(self):
  207. """Iterate over the SHAs in this pack."""
  208. return imap(sha_to_hex, self._itersha())
  209. def _itersha(self):
  210. for i in range(len(self)):
  211. yield self._unpack_name(i)
  212. def objects_sha1(self):
  213. """Return the hex SHA1 over all the shas of all objects in this pack.
  214. :note: This is used for the filename of the pack.
  215. """
  216. return iter_sha1(self._itersha())
  217. def iterentries(self):
  218. """Iterate over the entries in this pack index.
  219. Will yield tuples with object name, offset in packfile and crc32 checksum.
  220. """
  221. for i in range(len(self)):
  222. yield self._unpack_entry(i)
  223. def _read_fan_out_table(self, start_offset):
  224. ret = []
  225. for i in range(0x100):
  226. ret.append(struct.unpack(">L", self._contents[start_offset+i*4:start_offset+(i+1)*4])[0])
  227. return ret
  228. def check(self):
  229. """Check that the stored checksum matches the actual checksum."""
  230. # TODO: Check pack contents, too
  231. return self.calculate_checksum() == self.get_stored_checksum()
  232. def calculate_checksum(self):
  233. """Calculate the SHA1 checksum over this pack index.
  234. :return: This is a 20-byte binary digest
  235. """
  236. return make_sha(self._contents[:-20]).digest()
  237. def get_pack_checksum(self):
  238. """Return the SHA1 checksum stored for the corresponding packfile.
  239. :return: 20-byte binary digest
  240. """
  241. return str(self._contents[-40:-20])
  242. def get_stored_checksum(self):
  243. """Return the SHA1 checksum stored for this index.
  244. :return: 20-byte binary digest
  245. """
  246. return str(self._contents[-20:])
  247. def object_index(self, sha):
  248. """Return the index in to the corresponding packfile for the object.
  249. Given the name of an object it will return the offset that object lives
  250. at within the corresponding pack file. If the pack file doesn't have the
  251. object then None will be returned.
  252. """
  253. if len(sha) == 40:
  254. sha = hex_to_sha(sha)
  255. return self._object_index(sha)
  256. def _object_index(self, sha):
  257. """See object_index.
  258. :param sha: A *binary* SHA string. (20 characters long)_
  259. """
  260. assert len(sha) == 20
  261. idx = ord(sha[0])
  262. if idx == 0:
  263. start = 0
  264. else:
  265. start = self._fan_out_table[idx-1]
  266. end = self._fan_out_table[idx]
  267. i = bisect_find_sha(start, end, sha, self._unpack_name)
  268. if i is None:
  269. raise KeyError(sha)
  270. return self._unpack_offset(i)
  271. class PackIndex1(PackIndex):
  272. """Version 1 Pack Index."""
  273. def __init__(self, filename, file=None, size=None):
  274. PackIndex.__init__(self, filename, file, size)
  275. self.version = 1
  276. self._fan_out_table = self._read_fan_out_table(0)
  277. def _unpack_entry(self, i):
  278. (offset, name) = unpack_from(">L20s", self._contents,
  279. (0x100 * 4) + (i * 24))
  280. return (name, offset, None)
  281. def _unpack_name(self, i):
  282. offset = (0x100 * 4) + (i * 24) + 4
  283. return self._contents[offset:offset+20]
  284. def _unpack_offset(self, i):
  285. offset = (0x100 * 4) + (i * 24)
  286. return unpack_from(">L", self._contents, offset)[0]
  287. def _unpack_crc32_checksum(self, i):
  288. # Not stored in v1 index files
  289. return None
  290. class PackIndex2(PackIndex):
  291. """Version 2 Pack Index."""
  292. def __init__(self, filename, file=None, size=None):
  293. PackIndex.__init__(self, filename, file, size)
  294. assert self._contents[:4] == '\377tOc', "Not a v2 pack index file"
  295. (self.version, ) = unpack_from(">L", self._contents, 4)
  296. assert self.version == 2, "Version was %d" % self.version
  297. self._fan_out_table = self._read_fan_out_table(8)
  298. self._name_table_offset = 8 + 0x100 * 4
  299. self._crc32_table_offset = self._name_table_offset + 20 * len(self)
  300. self._pack_offset_table_offset = self._crc32_table_offset + 4 * len(self)
  301. def _unpack_entry(self, i):
  302. return (self._unpack_name(i), self._unpack_offset(i),
  303. self._unpack_crc32_checksum(i))
  304. def _unpack_name(self, i):
  305. offset = self._name_table_offset + i * 20
  306. return self._contents[offset:offset+20]
  307. def _unpack_offset(self, i):
  308. offset = self._pack_offset_table_offset + i * 4
  309. return unpack_from(">L", self._contents, offset)[0]
  310. def _unpack_crc32_checksum(self, i):
  311. return unpack_from(">L", self._contents,
  312. self._crc32_table_offset + i * 4)[0]
  313. def read_pack_header(f):
  314. """Read the header of a pack file.
  315. :param f: File-like object to read from
  316. """
  317. header = f.read(12)
  318. assert header[:4] == "PACK"
  319. (version,) = unpack_from(">L", header, 4)
  320. assert version in (2, 3), "Version was %d" % version
  321. (num_objects,) = unpack_from(">L", header, 8)
  322. return (version, num_objects)
  323. def chunks_length(chunks):
  324. return sum(imap(len, chunks))
  325. def unpack_object(read):
  326. """Unpack a Git object.
  327. :return: tuple with type, uncompressed data as chunks, compressed size and
  328. tail data
  329. """
  330. bytes = take_msb_bytes(read)
  331. type = (bytes[0] >> 4) & 0x07
  332. size = bytes[0] & 0x0f
  333. for i, byte in enumerate(bytes[1:]):
  334. size += (byte & 0x7f) << ((i * 7) + 4)
  335. raw_base = len(bytes)
  336. if type == 6: # offset delta
  337. bytes = take_msb_bytes(read)
  338. raw_base += len(bytes)
  339. assert not (bytes[-1] & 0x80)
  340. delta_base_offset = bytes[0] & 0x7f
  341. for byte in bytes[1:]:
  342. delta_base_offset += 1
  343. delta_base_offset <<= 7
  344. delta_base_offset += (byte & 0x7f)
  345. uncomp, comp_len, unused = read_zlib_chunks(read, size)
  346. assert size == chunks_length(uncomp)
  347. return type, (delta_base_offset, uncomp), comp_len+raw_base, unused
  348. elif type == 7: # ref delta
  349. basename = read(20)
  350. raw_base += 20
  351. uncomp, comp_len, unused = read_zlib_chunks(read, size)
  352. assert size == chunks_length(uncomp)
  353. return type, (basename, uncomp), comp_len+raw_base, unused
  354. else:
  355. uncomp, comp_len, unused = read_zlib_chunks(read, size)
  356. assert chunks_length(uncomp) == size
  357. return type, uncomp, comp_len+raw_base, unused
  358. def _compute_object_size((num, obj)):
  359. """Compute the size of a unresolved object for use with LRUSizeCache.
  360. """
  361. if num in (6, 7):
  362. return chunks_length(obj[1])
  363. return chunks_length(obj)
  364. class PackData(object):
  365. """The data contained in a packfile.
  366. Pack files can be accessed both sequentially for exploding a pack, and
  367. directly with the help of an index to retrieve a specific object.
  368. The objects within are either complete or a delta aginst another.
  369. The header is variable length. If the MSB of each byte is set then it
  370. indicates that the subsequent byte is still part of the header.
  371. For the first byte the next MS bits are the type, which tells you the type
  372. of object, and whether it is a delta. The LS byte is the lowest bits of the
  373. size. For each subsequent byte the LS 7 bits are the next MS bits of the
  374. size, i.e. the last byte of the header contains the MS bits of the size.
  375. For the complete objects the data is stored as zlib deflated data.
  376. The size in the header is the uncompressed object size, so to uncompress
  377. you need to just keep feeding data to zlib until you get an object back,
  378. or it errors on bad data. This is done here by just giving the complete
  379. buffer from the start of the deflated object on. This is bad, but until I
  380. get mmap sorted out it will have to do.
  381. Currently there are no integrity checks done. Also no attempt is made to try
  382. and detect the delta case, or a request for an object at the wrong position.
  383. It will all just throw a zlib or KeyError.
  384. """
  385. def __init__(self, filename, file=None, size=None):
  386. """Create a PackData object that represents the pack in the given filename.
  387. The file must exist and stay readable until the object is disposed of. It
  388. must also stay the same size. It will be mapped whenever needed.
  389. Currently there is a restriction on the size of the pack as the python
  390. mmap implementation is flawed.
  391. """
  392. self._filename = filename
  393. self._size = size
  394. self._header_size = 12
  395. if file is None:
  396. self._file = GitFile(self._filename, 'rb')
  397. else:
  398. self._file = file
  399. (version, self._num_objects) = read_pack_header(self._file)
  400. self._offset_cache = LRUSizeCache(1024*1024*20,
  401. compute_size=_compute_object_size)
  402. @classmethod
  403. def from_file(cls, file, size):
  404. return cls(str(file), file=file, size=size)
  405. @classmethod
  406. def from_path(cls, path):
  407. return cls(filename=path)
  408. def close(self):
  409. self._file.close()
  410. def _get_size(self):
  411. if self._size is not None:
  412. return self._size
  413. self._size = os.path.getsize(self._filename)
  414. assert self._size >= self._header_size, "%s is too small for a packfile (%d < %d)" % (self._filename, self._size, self._header_size)
  415. return self._size
  416. def __len__(self):
  417. """Returns the number of objects in this pack."""
  418. return self._num_objects
  419. def calculate_checksum(self):
  420. """Calculate the checksum for this pack.
  421. :return: 20-byte binary SHA1 digest
  422. """
  423. s = make_sha()
  424. self._file.seek(0)
  425. todo = self._get_size() - 20
  426. while todo > 0:
  427. x = self._file.read(min(todo, 1<<16))
  428. s.update(x)
  429. todo -= len(x)
  430. return s.digest()
  431. def resolve_object(self, offset, type, obj, get_ref, get_offset=None):
  432. """Resolve an object, possibly resolving deltas when necessary.
  433. :return: Tuple with object type and contents.
  434. """
  435. if type not in (6, 7): # Not a delta
  436. return type, obj
  437. if get_offset is None:
  438. get_offset = self.get_object_at
  439. if type == 6: # offset delta
  440. (delta_offset, delta) = obj
  441. assert isinstance(delta_offset, int)
  442. base_offset = offset-delta_offset
  443. type, base_obj = get_offset(base_offset)
  444. assert isinstance(type, int)
  445. elif type == 7: # ref delta
  446. (basename, delta) = obj
  447. assert isinstance(basename, str) and len(basename) == 20
  448. type, base_obj = get_ref(basename)
  449. assert isinstance(type, int)
  450. # Can't be a ofs delta, as we wouldn't know the base offset
  451. assert type != 6
  452. base_offset = None
  453. type, base_chunks = self.resolve_object(base_offset, type, base_obj,
  454. get_ref)
  455. if base_offset is not None:
  456. self._offset_cache[base_offset] = type, base_chunks
  457. return (type, apply_delta(base_chunks, delta))
  458. def iterobjects(self, progress=None):
  459. class ObjectIterator(object):
  460. def __init__(self, pack):
  461. self.i = 0
  462. self.offset = pack._header_size
  463. self.num = len(pack)
  464. self.map = pack._file
  465. def __iter__(self):
  466. return self
  467. def __len__(self):
  468. return self.num
  469. def next(self):
  470. if self.i == self.num:
  471. raise StopIteration
  472. self.map.seek(self.offset)
  473. (type, obj, total_size, unused) = unpack_object(self.map.read)
  474. self.map.seek(self.offset)
  475. crc32 = zlib.crc32(self.map.read(total_size)) & 0xffffffff
  476. ret = (self.offset, type, obj, crc32)
  477. self.offset += total_size
  478. if progress:
  479. progress(self.i, self.num)
  480. self.i+=1
  481. return ret
  482. return ObjectIterator(self)
  483. def iterentries(self, ext_resolve_ref=None, progress=None):
  484. """Yield entries summarizing the contents of this pack.
  485. :param ext_resolve_ref: Optional function to resolve base
  486. objects (in case this is a thin pack)
  487. :param progress: Progress function, called with current and
  488. total object count.
  489. This will yield tuples with (sha, offset, crc32)
  490. """
  491. found = {}
  492. postponed = defaultdict(list)
  493. class Postpone(Exception):
  494. """Raised to postpone delta resolving."""
  495. def get_ref_text(sha):
  496. assert len(sha) == 20
  497. if sha in found:
  498. return self.get_object_at(found[sha])
  499. if ext_resolve_ref:
  500. try:
  501. return ext_resolve_ref(sha)
  502. except KeyError:
  503. pass
  504. raise Postpone, (sha, )
  505. extra = []
  506. todo = chain(self.iterobjects(progress=progress), extra)
  507. for (offset, type, obj, crc32) in todo:
  508. assert isinstance(offset, int)
  509. assert isinstance(type, int)
  510. assert isinstance(obj, list) or isinstance(obj, str)
  511. try:
  512. type, obj = self.resolve_object(offset, type, obj, get_ref_text)
  513. except Postpone, (sha, ):
  514. postponed[sha].append((offset, type, obj))
  515. else:
  516. shafile = ShaFile.from_raw_chunks(type, obj)
  517. sha = shafile.sha().digest()
  518. found[sha] = offset
  519. yield sha, offset, crc32
  520. extra.extend(postponed.get(sha, []))
  521. if postponed:
  522. raise KeyError([sha_to_hex(h) for h in postponed.keys()])
  523. def sorted_entries(self, resolve_ext_ref=None, progress=None):
  524. """Return entries in this pack, sorted by SHA.
  525. :param ext_resolve_ref: Optional function to resolve base
  526. objects (in case this is a thin pack)
  527. :param progress: Progress function, called with current and
  528. total object count.
  529. :return: List of tuples with (sha, offset, crc32)
  530. """
  531. ret = list(self.iterentries(resolve_ext_ref, progress=progress))
  532. ret.sort()
  533. return ret
  534. def create_index_v1(self, filename, resolve_ext_ref=None, progress=None):
  535. """Create a version 1 file for this data file.
  536. :param filename: Index filename.
  537. :param resolve_ext_ref: Function to use for resolving externally referenced
  538. SHA1s (for thin packs)
  539. :param progress: Progress report function
  540. """
  541. entries = self.sorted_entries(resolve_ext_ref, progress=progress)
  542. write_pack_index_v1(filename, entries, self.calculate_checksum())
  543. def create_index_v2(self, filename, resolve_ext_ref=None, progress=None):
  544. """Create a version 2 index file for this data file.
  545. :param filename: Index filename.
  546. :param resolve_ext_ref: Function to use for resolving externally referenced
  547. SHA1s (for thin packs)
  548. :param progress: Progress report function
  549. """
  550. entries = self.sorted_entries(resolve_ext_ref, progress=progress)
  551. write_pack_index_v2(filename, entries, self.calculate_checksum())
  552. def create_index(self, filename, resolve_ext_ref=None, progress=None,
  553. version=2):
  554. """Create an index file for this data file.
  555. :param filename: Index filename.
  556. :param resolve_ext_ref: Function to use for resolving externally referenced
  557. SHA1s (for thin packs)
  558. :param progress: Progress report function
  559. """
  560. if version == 1:
  561. self.create_index_v1(filename, resolve_ext_ref, progress)
  562. elif version == 2:
  563. self.create_index_v2(filename, resolve_ext_ref, progress)
  564. else:
  565. raise ValueError("unknown index format %d" % version)
  566. def get_stored_checksum(self):
  567. """Return the expected checksum stored in this pack."""
  568. self._file.seek(self._get_size()-20)
  569. return self._file.read(20)
  570. def check(self):
  571. """Check the consistency of this pack."""
  572. return (self.calculate_checksum() == self.get_stored_checksum())
  573. def get_object_at(self, offset):
  574. """Given an offset in to the packfile return the object that is there.
  575. Using the associated index the location of an object can be looked up, and
  576. then the packfile can be asked directly for that object using this
  577. function.
  578. """
  579. if offset in self._offset_cache:
  580. return self._offset_cache[offset]
  581. assert isinstance(offset, long) or isinstance(offset, int),\
  582. "offset was %r" % offset
  583. assert offset >= self._header_size
  584. self._file.seek(offset)
  585. return unpack_object(self._file.read)[:2]
  586. class SHA1Reader(object):
  587. """Wrapper around a file-like object that remembers the SHA1 of
  588. the data read from it."""
  589. def __init__(self, f):
  590. self.f = f
  591. self.sha1 = make_sha("")
  592. def read(self, num=None):
  593. data = self.f.read(num)
  594. self.sha1.update(data)
  595. return data
  596. def check_sha(self):
  597. stored = self.f.read(20)
  598. if stored != self.sha1.digest():
  599. raise ChecksumMismatch(self.sha1.hexdigest(), sha_to_hex(stored))
  600. def close(self):
  601. return self.f.close()
  602. def tell(self):
  603. return self.f.tell()
  604. class SHA1Writer(object):
  605. """Wrapper around a file-like object that remembers the SHA1 of
  606. the data written to it."""
  607. def __init__(self, f):
  608. self.f = f
  609. self.sha1 = make_sha("")
  610. def write(self, data):
  611. self.sha1.update(data)
  612. self.f.write(data)
  613. def write_sha(self):
  614. sha = self.sha1.digest()
  615. assert len(sha) == 20
  616. self.f.write(sha)
  617. return sha
  618. def close(self):
  619. sha = self.write_sha()
  620. self.f.close()
  621. return sha
  622. def tell(self):
  623. return self.f.tell()
  624. def write_pack_object(f, type, object):
  625. """Write pack object to a file.
  626. :param f: File to write to
  627. :param o: Object to write
  628. :return: Tuple with offset at which the object was written, and crc32
  629. """
  630. offset = f.tell()
  631. packed_data_hdr = ""
  632. if type == 6: # offset delta
  633. (delta_base_offset, object) = object
  634. elif type == 7: # ref delta
  635. (basename, object) = object
  636. size = len(object)
  637. c = (type << 4) | (size & 15)
  638. size >>= 4
  639. while size:
  640. packed_data_hdr += (chr(c | 0x80))
  641. c = size & 0x7f
  642. size >>= 7
  643. packed_data_hdr += chr(c)
  644. if type == 6: # offset delta
  645. ret = [delta_base_offset & 0x7f]
  646. delta_base_offset >>= 7
  647. while delta_base_offset:
  648. delta_base_offset -= 1
  649. ret.insert(0, 0x80 | (delta_base_offset & 0x7f))
  650. delta_base_offset >>= 7
  651. packed_data_hdr += "".join([chr(x) for x in ret])
  652. elif type == 7: # ref delta
  653. assert len(basename) == 20
  654. packed_data_hdr += basename
  655. packed_data = packed_data_hdr + zlib.compress(object)
  656. f.write(packed_data)
  657. return (offset, (zlib.crc32(packed_data) & 0xffffffff))
  658. def write_pack(filename, objects, num_objects):
  659. """Write a new pack data file.
  660. :param filename: Path to the new pack file (without .pack extension)
  661. :param objects: Iterable over (object, path) tuples to write
  662. :param num_objects: Number of objects to write
  663. """
  664. f = GitFile(filename + ".pack", 'wb')
  665. try:
  666. entries, data_sum = write_pack_data(f, objects, num_objects)
  667. finally:
  668. f.close()
  669. entries.sort()
  670. write_pack_index_v2(filename + ".idx", entries, data_sum)
  671. def write_pack_data(f, objects, num_objects, window=10):
  672. """Write a new pack file.
  673. :param filename: The filename of the new pack file.
  674. :param objects: List of objects to write (tuples with object and path)
  675. :return: List with (name, offset, crc32 checksum) entries, pack checksum
  676. """
  677. recency = list(objects)
  678. # FIXME: Somehow limit delta depth
  679. # FIXME: Make thin-pack optional (its not used when cloning a pack)
  680. # Build a list of objects ordered by the magic Linus heuristic
  681. # This helps us find good objects to diff against us
  682. magic = []
  683. for obj, path in recency:
  684. magic.append( (obj.type, path, 1, -obj.raw_length(), obj) )
  685. magic.sort()
  686. # Build a map of objects and their index in magic - so we can find preceeding objects
  687. # to diff against
  688. offs = {}
  689. for i in range(len(magic)):
  690. offs[magic[i][4]] = i
  691. # Write the pack
  692. entries = []
  693. f = SHA1Writer(f)
  694. f.write("PACK") # Pack header
  695. f.write(struct.pack(">L", 2)) # Pack version
  696. f.write(struct.pack(">L", num_objects)) # Number of objects in pack
  697. for o, path in recency:
  698. sha1 = o.sha().digest()
  699. orig_t = o.type
  700. raw = o.as_raw_string()
  701. winner = raw
  702. t = orig_t
  703. #for i in range(offs[o]-window, window):
  704. # if i < 0 or i >= len(offs): continue
  705. # b = magic[i][4]
  706. # if b.type != orig_t: continue
  707. # base = b.as_raw_string()
  708. # delta = create_delta(base, raw)
  709. # if len(delta) < len(winner):
  710. # winner = delta
  711. # t = 6 if magic[i][2] == 1 else 7
  712. offset, crc32 = write_pack_object(f, t, winner)
  713. entries.append((sha1, offset, crc32))
  714. return entries, f.write_sha()
  715. def write_pack_index_v1(filename, entries, pack_checksum):
  716. """Write a new pack index file.
  717. :param filename: The filename of the new pack index file.
  718. :param entries: List of tuples with object name (sha), offset_in_pack, and
  719. crc32_checksum.
  720. :param pack_checksum: Checksum of the pack file.
  721. """
  722. f = GitFile(filename, 'wb')
  723. f = SHA1Writer(f)
  724. fan_out_table = defaultdict(lambda: 0)
  725. for (name, offset, entry_checksum) in entries:
  726. fan_out_table[ord(name[0])] += 1
  727. # Fan-out table
  728. for i in range(0x100):
  729. f.write(struct.pack(">L", fan_out_table[i]))
  730. fan_out_table[i+1] += fan_out_table[i]
  731. for (name, offset, entry_checksum) in entries:
  732. f.write(struct.pack(">L20s", offset, name))
  733. assert len(pack_checksum) == 20
  734. f.write(pack_checksum)
  735. f.close()
  736. def create_delta(base_buf, target_buf):
  737. """Use python difflib to work out how to transform base_buf to target_buf.
  738. :param base_buf: Base buffer
  739. :param target_buf: Target buffer
  740. """
  741. assert isinstance(base_buf, str)
  742. assert isinstance(target_buf, str)
  743. out_buf = ""
  744. # write delta header
  745. def encode_size(size):
  746. ret = ""
  747. c = size & 0x7f
  748. size >>= 7
  749. while size:
  750. ret += chr(c | 0x80)
  751. c = size & 0x7f
  752. size >>= 7
  753. ret += chr(c)
  754. return ret
  755. out_buf += encode_size(len(base_buf))
  756. out_buf += encode_size(len(target_buf))
  757. # write out delta opcodes
  758. seq = difflib.SequenceMatcher(a=base_buf, b=target_buf)
  759. for opcode, i1, i2, j1, j2 in seq.get_opcodes():
  760. # Git patch opcodes don't care about deletes!
  761. #if opcode == "replace" or opcode == "delete":
  762. # pass
  763. if opcode == "equal":
  764. # If they are equal, unpacker will use data from base_buf
  765. # Write out an opcode that says what range to use
  766. scratch = ""
  767. op = 0x80
  768. o = i1
  769. for i in range(4):
  770. if o & 0xff << i*8:
  771. scratch += chr((o >> i*8) & 0xff)
  772. op |= 1 << i
  773. s = i2 - i1
  774. for i in range(2):
  775. if s & 0xff << i*8:
  776. scratch += chr((s >> i*8) & 0xff)
  777. op |= 1 << (4+i)
  778. out_buf += chr(op)
  779. out_buf += scratch
  780. if opcode == "replace" or opcode == "insert":
  781. # If we are replacing a range or adding one, then we just
  782. # output it to the stream (prefixed by its size)
  783. s = j2 - j1
  784. o = j1
  785. while s > 127:
  786. out_buf += chr(127)
  787. out_buf += target_buf[o:o+127]
  788. s -= 127
  789. o += 127
  790. out_buf += chr(s)
  791. out_buf += target_buf[o:o+s]
  792. return out_buf
  793. def apply_delta(src_buf, delta):
  794. """Based on the similar function in git's patch-delta.c.
  795. :param src_buf: Source buffer
  796. :param delta: Delta instructions
  797. """
  798. if type(src_buf) != str:
  799. src_buf = "".join(src_buf)
  800. if type(delta) != str:
  801. delta = "".join(delta)
  802. out = []
  803. index = 0
  804. delta_length = len(delta)
  805. def get_delta_header_size(delta, index):
  806. size = 0
  807. i = 0
  808. while delta:
  809. cmd = ord(delta[index])
  810. index += 1
  811. size |= (cmd & ~0x80) << i
  812. i += 7
  813. if not cmd & 0x80:
  814. break
  815. return size, index
  816. src_size, index = get_delta_header_size(delta, index)
  817. dest_size, index = get_delta_header_size(delta, index)
  818. assert src_size == len(src_buf), "%d vs %d" % (src_size, len(src_buf))
  819. while index < delta_length:
  820. cmd = ord(delta[index])
  821. index += 1
  822. if cmd & 0x80:
  823. cp_off = 0
  824. for i in range(4):
  825. if cmd & (1 << i):
  826. x = ord(delta[index])
  827. index += 1
  828. cp_off |= x << (i * 8)
  829. cp_size = 0
  830. for i in range(3):
  831. if cmd & (1 << (4+i)):
  832. x = ord(delta[index])
  833. index += 1
  834. cp_size |= x << (i * 8)
  835. if cp_size == 0:
  836. cp_size = 0x10000
  837. if (cp_off + cp_size < cp_size or
  838. cp_off + cp_size > src_size or
  839. cp_size > dest_size):
  840. break
  841. out.append(src_buf[cp_off:cp_off+cp_size])
  842. elif cmd != 0:
  843. out.append(delta[index:index+cmd])
  844. index += cmd
  845. else:
  846. raise ApplyDeltaError("Invalid opcode 0")
  847. if index != delta_length:
  848. raise ApplyDeltaError("delta not empty: %r" % delta[index:])
  849. if dest_size != chunks_length(out):
  850. raise ApplyDeltaError("dest size incorrect")
  851. return out
  852. def write_pack_index_v2(filename, entries, pack_checksum):
  853. """Write a new pack index file.
  854. :param filename: The filename of the new pack index file.
  855. :param entries: List of tuples with object name (sha), offset_in_pack, and
  856. crc32_checksum.
  857. :param pack_checksum: Checksum of the pack file.
  858. """
  859. f = GitFile(filename, 'wb')
  860. f = SHA1Writer(f)
  861. f.write('\377tOc') # Magic!
  862. f.write(struct.pack(">L", 2))
  863. fan_out_table = defaultdict(lambda: 0)
  864. for (name, offset, entry_checksum) in entries:
  865. fan_out_table[ord(name[0])] += 1
  866. # Fan-out table
  867. for i in range(0x100):
  868. f.write(struct.pack(">L", fan_out_table[i]))
  869. fan_out_table[i+1] += fan_out_table[i]
  870. for (name, offset, entry_checksum) in entries:
  871. f.write(name)
  872. for (name, offset, entry_checksum) in entries:
  873. f.write(struct.pack(">L", entry_checksum))
  874. for (name, offset, entry_checksum) in entries:
  875. # FIXME: handle if MSBit is set in offset
  876. f.write(struct.pack(">L", offset))
  877. # FIXME: handle table for pack files > 8 Gb
  878. assert len(pack_checksum) == 20
  879. f.write(pack_checksum)
  880. f.close()
  881. class Pack(object):
  882. """A Git pack object."""
  883. def __init__(self, basename):
  884. self._basename = basename
  885. self._data_path = self._basename + ".pack"
  886. self._idx_path = self._basename + ".idx"
  887. self._data = None
  888. self._idx = None
  889. @classmethod
  890. def from_objects(self, data, idx):
  891. """Create a new pack object from pack data and index objects."""
  892. ret = Pack("")
  893. ret._data = data
  894. ret._idx = idx
  895. return ret
  896. def name(self):
  897. """The SHA over the SHAs of the objects in this pack."""
  898. return self.index.objects_sha1()
  899. @property
  900. def data(self):
  901. """The pack data object being used."""
  902. if self._data is None:
  903. self._data = PackData(self._data_path)
  904. assert len(self.index) == len(self._data)
  905. idx_stored_checksum = self.index.get_pack_checksum()
  906. data_stored_checksum = self._data.get_stored_checksum()
  907. if idx_stored_checksum != data_stored_checksum:
  908. raise ChecksumMismatch(sha_to_hex(idx_stored_checksum),
  909. sha_to_hex(data_stored_checksum))
  910. return self._data
  911. @property
  912. def index(self):
  913. """The index being used.
  914. :note: This may be an in-memory index
  915. """
  916. if self._idx is None:
  917. self._idx = load_pack_index(self._idx_path)
  918. return self._idx
  919. def close(self):
  920. if self._data is not None:
  921. self._data.close()
  922. self.index.close()
  923. def __eq__(self, other):
  924. return type(self) == type(other) and self.index == other.index
  925. def __len__(self):
  926. """Number of entries in this pack."""
  927. return len(self.index)
  928. def __repr__(self):
  929. return "%s(%r)" % (self.__class__.__name__, self._basename)
  930. def __iter__(self):
  931. """Iterate over all the sha1s of the objects in this pack."""
  932. return iter(self.index)
  933. def check(self):
  934. """Check the integrity of this pack."""
  935. if not self.index.check():
  936. return False
  937. if not self.data.check():
  938. return False
  939. return True
  940. def get_stored_checksum(self):
  941. return self.data.get_stored_checksum()
  942. def __contains__(self, sha1):
  943. """Check whether this pack contains a particular SHA1."""
  944. try:
  945. self.index.object_index(sha1)
  946. return True
  947. except KeyError:
  948. return False
  949. def get_raw(self, sha1, resolve_ref=None):
  950. offset = self.index.object_index(sha1)
  951. obj_type, obj = self.data.get_object_at(offset)
  952. if type(offset) is long:
  953. offset = int(offset)
  954. if resolve_ref is None:
  955. resolve_ref = self.get_raw
  956. kind, chunks = self.data.resolve_object(offset, obj_type, obj,
  957. resolve_ref)
  958. return kind, "".join(chunks)
  959. def __getitem__(self, sha1):
  960. """Retrieve the specified SHA1."""
  961. type, uncomp = self.get_raw(sha1)
  962. return ShaFile.from_raw_string(type, uncomp)
  963. def iterobjects(self, get_raw=None):
  964. """Iterate over the objects in this pack."""
  965. if get_raw is None:
  966. get_raw = self.get_raw
  967. for offset, type, obj, crc32 in self.data.iterobjects():
  968. assert isinstance(offset, int)
  969. type, obj = self.data.resolve_object(offset, type, obj, get_raw)
  970. yield ShaFile.from_raw_chunks(type, obj)
  971. try:
  972. from dulwich._pack import apply_delta, bisect_find_sha
  973. except ImportError:
  974. pass