pack.py 36 KB

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