pack.py 48 KB

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