pack.py 49 KB

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