pack.py 50 KB

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