pack.py 38 KB

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