pack.py 34 KB

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