pack.py 47 KB

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