pack.py 41 KB

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