pack.py 38 KB

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