pack.py 43 KB

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