pack.py 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741
  1. # pack.py -- For dealing wih packed git objects.
  2. # Copyright (C) 2007 James Westby <jw+debian@jameswestby.net>
  3. # Copryight (C) 2008 Jelmer Vernooij <jelmer@samba.org>
  4. # The code is loosely based on that in the sha1_file.c file from git itself,
  5. # which is Copyright (C) Linus Torvalds, 2005 and distributed under the
  6. # GPL version 2.
  7. #
  8. # This program is free software; you can redistribute it and/or
  9. # modify it under the terms of the GNU General Public License
  10. # as published by the Free Software Foundation; version 2
  11. # of the License.
  12. #
  13. # This program is distributed in the hope that it will be useful,
  14. # but WITHOUT ANY WARRANTY; without even the implied warranty of
  15. # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  16. # GNU General Public License for more details.
  17. #
  18. # You should have received a copy of the GNU General Public License
  19. # along with this program; if not, write to the Free Software
  20. # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
  21. # MA 02110-1301, USA.
  22. """Classes for dealing with packed git objects.
  23. A pack is a compact representation of a bunch of objects, stored
  24. using deltas where possible.
  25. They have two parts, the pack file, which stores the data, and an index
  26. that tells you where the data is.
  27. To find an object you look in all of the index files 'til you find a
  28. match for the object name. You then use the pointer got from this as
  29. a pointer in to the corresponding packfile.
  30. """
  31. from collections import defaultdict
  32. import hashlib
  33. from itertools import izip
  34. import mmap
  35. import os
  36. import struct
  37. import sys
  38. import zlib
  39. from objects import (
  40. ShaFile,
  41. )
  42. from errors import ApplyDeltaError
  43. supports_mmap_offset = (sys.version_info[0] >= 3 or
  44. (sys.version_info[0] == 2 and sys.version_info[1] >= 6))
  45. def take_msb_bytes(map, offset):
  46. ret = []
  47. while len(ret) == 0 or ret[-1] & 0x80:
  48. ret.append(ord(map[offset]))
  49. offset += 1
  50. return ret
  51. def read_zlib(data, offset, dec_size):
  52. obj = zlib.decompressobj()
  53. x = ""
  54. fed = 0
  55. while obj.unused_data == "":
  56. base = offset+fed
  57. add = data[base:base+1024]
  58. fed += len(add)
  59. x += obj.decompress(add)
  60. assert len(x) == dec_size
  61. comp_len = fed-len(obj.unused_data)
  62. return x, comp_len
  63. def hex_to_sha(hex):
  64. """Convert a hex string to a binary sha string."""
  65. ret = ""
  66. for i in range(0, len(hex), 2):
  67. ret += chr(int(hex[i:i+2], 16))
  68. return ret
  69. def sha_to_hex(sha):
  70. """Convert a binary sha string to a hex sha string."""
  71. ret = ""
  72. for i in sha:
  73. ret += "%02x" % ord(i)
  74. return ret
  75. MAX_MMAP_SIZE = 256 * 1024 * 1024
  76. def simple_mmap(f, offset, size, access=mmap.ACCESS_READ):
  77. """Simple wrapper for mmap() which always supports the offset parameter.
  78. :param f: File object.
  79. :param offset: Offset in the file, from the beginning of the file.
  80. :param size: Size of the mmap'ed area
  81. :param access: Access mechanism.
  82. :return: MMAP'd area.
  83. """
  84. if offset+size > MAX_MMAP_SIZE and not supports_mmap_offset:
  85. raise AssertionError("%s is larger than 256 meg, and this version "
  86. "of Python does not support the offset argument to mmap().")
  87. if supports_mmap_offset:
  88. return mmap.mmap(f.fileno(), size, access=access, offset=offset)
  89. else:
  90. class ArraySkipper(object):
  91. def __init__(self, array, offset):
  92. self.array = array
  93. self.offset = offset
  94. def __getslice__(self, i, j):
  95. return self.array[i+self.offset:j+self.offset]
  96. def __getitem__(self, i):
  97. return self.array[i+self.offset]
  98. def __len__(self):
  99. return len(self.array) - self.offset
  100. def __str__(self):
  101. return str(self.array[self.offset:])
  102. mem = mmap.mmap(f.fileno(), size+offset, access=access)
  103. if offset == 0:
  104. return mem
  105. return ArraySkipper(mem, offset)
  106. def resolve_object(offset, type, obj, get_ref, get_offset):
  107. """Resolve an object, possibly resolving deltas when necessary."""
  108. if not type in (6, 7): # Not a delta
  109. return type, obj
  110. if type == 6: # offset delta
  111. (delta_offset, delta) = obj
  112. assert isinstance(delta_offset, int)
  113. assert isinstance(delta, str)
  114. offset = offset-delta_offset
  115. type, base_obj = get_offset(offset)
  116. assert isinstance(type, int)
  117. elif type == 7: # ref delta
  118. (basename, delta) = obj
  119. assert isinstance(basename, str) and len(basename) == 20
  120. assert isinstance(delta, str)
  121. type, base_obj= get_ref(basename)
  122. assert isinstance(type, int)
  123. type, base_text = resolve_object(offset, type, base_obj, get_ref, get_offset)
  124. return type, apply_delta(base_text, delta)
  125. class PackIndex(object):
  126. """An index in to a packfile.
  127. Given a sha id of an object a pack index can tell you the location in the
  128. packfile of that object if it has it.
  129. To do the loop it opens the file, and indexes first 256 4 byte groups
  130. with the first byte of the sha id. The value in the four byte group indexed
  131. is the end of the group that shares the same starting byte. Subtract one
  132. from the starting byte and index again to find the start of the group.
  133. The values are sorted by sha id within the group, so do the math to find
  134. the start and end offset and then bisect in to find if the value is present.
  135. """
  136. def __init__(self, filename):
  137. """Create a pack index object.
  138. Provide it with the name of the index file to consider, and it will map
  139. it whenever required.
  140. """
  141. self._filename = filename
  142. assert os.path.exists(filename), "%s is not a pack index" % filename
  143. # Take the size now, so it can be checked each time we map the file to
  144. # ensure that it hasn't changed.
  145. self._size = os.path.getsize(filename)
  146. self._file = open(filename, 'r')
  147. self._contents = simple_mmap(self._file, 0, self._size)
  148. if self._contents[:4] != '\377tOc':
  149. self.version = 1
  150. self._fan_out_table = self._read_fan_out_table(0)
  151. else:
  152. (self.version, ) = struct.unpack_from(">L", self._contents, 4)
  153. assert self.version in (2,), "Version was %d" % self.version
  154. self._fan_out_table = self._read_fan_out_table(8)
  155. self._name_table_offset = 8 + 0x100 * 4
  156. self._crc32_table_offset = self._name_table_offset + 20 * len(self)
  157. self._pack_offset_table_offset = self._crc32_table_offset + 4 * len(self)
  158. def __eq__(self, other):
  159. if type(self) != type(other):
  160. return False
  161. if self._fan_out_table != other._fan_out_table:
  162. return False
  163. for (name1, _, _), (name2, _, _) in izip(self.iterentries(), other.iterentries()):
  164. if name1 != name2:
  165. return False
  166. return True
  167. def close(self):
  168. self._file.close()
  169. def __len__(self):
  170. """Return the number of entries in this pack index."""
  171. return self._fan_out_table[-1]
  172. def _unpack_entry(self, i):
  173. """Unpack the i-th entry in the index file.
  174. :return: Tuple with object name (SHA), offset in pack file and
  175. CRC32 checksum (if known)."""
  176. if self.version == 1:
  177. (offset, name) = struct.unpack_from(">L20s", self._contents,
  178. (0x100 * 4) + (i * 24))
  179. return (name, offset, None)
  180. else:
  181. return (self._unpack_name(i), self._unpack_offset(i),
  182. self._unpack_crc32_checksum(i))
  183. def _unpack_name(self, i):
  184. if self.version == 1:
  185. return self._unpack_entry(i)[0]
  186. else:
  187. return struct.unpack_from("20s", self._contents,
  188. self._name_table_offset + i * 20)[0]
  189. def _unpack_offset(self, i):
  190. if self.version == 1:
  191. return self._unpack_entry(i)[1]
  192. else:
  193. return struct.unpack_from(">L", self._contents,
  194. self._pack_offset_table_offset + i * 4)[0]
  195. def _unpack_crc32_checksum(self, i):
  196. if self.version == 1:
  197. return None
  198. else:
  199. return struct.unpack_from(">L", self._contents,
  200. self._crc32_table_offset + i * 4)[0]
  201. def __iter__(self):
  202. for i in range(len(self)):
  203. yield sha_to_hex(self._unpack_name(i))
  204. def iterentries(self):
  205. """Iterate over the entries in this pack index.
  206. Will yield tuples with object name, offset in packfile and crc32 checksum.
  207. """
  208. for i in range(len(self)):
  209. yield self._unpack_entry(i)
  210. def _read_fan_out_table(self, start_offset):
  211. ret = []
  212. for i in range(0x100):
  213. ret.append(struct.unpack(">L", self._contents[start_offset+i*4:start_offset+(i+1)*4])[0])
  214. return ret
  215. def check(self):
  216. """Check that the stored checksum matches the actual checksum."""
  217. return self.calculate_checksum() == self.get_stored_checksums()[1]
  218. def calculate_checksum(self):
  219. f = open(self._filename, 'r')
  220. try:
  221. return hashlib.sha1(self._contents[:-20]).digest()
  222. finally:
  223. f.close()
  224. def get_stored_checksums(self):
  225. """Return the SHA1 checksums stored for the corresponding packfile and
  226. this header file itself."""
  227. return str(self._contents[-40:-20]), str(self._contents[-20:])
  228. def object_index(self, sha):
  229. """Return the index in to the corresponding packfile for the object.
  230. Given the name of an object it will return the offset that object lives
  231. at within the corresponding pack file. If the pack file doesn't have the
  232. object then None will be returned.
  233. """
  234. size = os.path.getsize(self._filename)
  235. assert size == self._size, "Pack index %s has changed size, I don't " \
  236. "like that" % self._filename
  237. if len(sha) == 40:
  238. sha = hex_to_sha(sha)
  239. return self._object_index(sha)
  240. def _object_index(self, sha):
  241. """See object_index"""
  242. idx = ord(sha[0])
  243. if idx == 0:
  244. start = 0
  245. else:
  246. start = self._fan_out_table[idx-1]
  247. end = self._fan_out_table[idx]
  248. assert start <= end
  249. while start <= end:
  250. i = (start + end)/2
  251. file_sha = self._unpack_name(i)
  252. if file_sha < sha:
  253. start = i + 1
  254. elif file_sha > sha:
  255. end = i - 1
  256. else:
  257. return self._unpack_offset(i)
  258. return None
  259. class PackData(object):
  260. """The data contained in a packfile.
  261. Pack files can be accessed both sequentially for exploding a pack, and
  262. directly with the help of an index to retrieve a specific object.
  263. The objects within are either complete or a delta aginst another.
  264. The header is variable length. If the MSB of each byte is set then it
  265. indicates that the subsequent byte is still part of the header.
  266. For the first byte the next MS bits are the type, which tells you the type
  267. of object, and whether it is a delta. The LS byte is the lowest bits of the
  268. size. For each subsequent byte the LS 7 bits are the next MS bits of the
  269. size, i.e. the last byte of the header contains the MS bits of the size.
  270. For the complete objects the data is stored as zlib deflated data.
  271. The size in the header is the uncompressed object size, so to uncompress
  272. you need to just keep feeding data to zlib until you get an object back,
  273. or it errors on bad data. This is done here by just giving the complete
  274. buffer from the start of the deflated object on. This is bad, but until I
  275. get mmap sorted out it will have to do.
  276. Currently there are no integrity checks done. Also no attempt is made to try
  277. and detect the delta case, or a request for an object at the wrong position.
  278. It will all just throw a zlib or KeyError.
  279. """
  280. def __init__(self, filename):
  281. """Create a PackData object that represents the pack in the given filename.
  282. The file must exist and stay readable until the object is disposed of. It
  283. must also stay the same size. It will be mapped whenever needed.
  284. Currently there is a restriction on the size of the pack as the python
  285. mmap implementation is flawed.
  286. """
  287. self._filename = filename
  288. assert os.path.exists(filename), "%s is not a packfile" % filename
  289. self._size = os.path.getsize(filename)
  290. self._header_size = self._read_header()
  291. def _read_header(self):
  292. f = open(self._filename, 'rb')
  293. try:
  294. header = f.read(12)
  295. f.seek(self._size-20)
  296. self._stored_checksum = f.read(20)
  297. finally:
  298. f.close()
  299. assert header[:4] == "PACK"
  300. (version,) = struct.unpack_from(">L", header, 4)
  301. assert version in (2, 3), "Version was %d" % version
  302. (self._num_objects,) = struct.unpack_from(">L", header, 8)
  303. return 12 # Header size
  304. def __len__(self):
  305. """Returns the number of objects in this pack."""
  306. return self._num_objects
  307. def calculate_checksum(self):
  308. f = open(self._filename, 'rb')
  309. try:
  310. map = simple_mmap(f, 0, self._size)
  311. return hashlib.sha1(map[:-20]).digest()
  312. finally:
  313. f.close()
  314. def iterobjects(self):
  315. offset = self._header_size
  316. f = open(self._filename, 'rb')
  317. for i in range(len(self)):
  318. map = simple_mmap(f, offset, self._size-offset)
  319. (type, obj, total_size) = self._unpack_object(map)
  320. yield offset, type, obj
  321. offset += total_size
  322. f.close()
  323. def iterentries(self):
  324. found = {}
  325. postponed = list(self.iterobjects())
  326. while postponed:
  327. (offset, type, obj) = postponed.pop(0)
  328. assert isinstance(offset, int)
  329. assert isinstance(type, int)
  330. assert isinstance(obj, tuple) or isinstance(obj, str)
  331. try:
  332. type, obj = resolve_object(offset, type, obj, found.__getitem__,
  333. self.get_object_at)
  334. except KeyError:
  335. postponed.append((offset, type, obj))
  336. else:
  337. shafile = ShaFile.from_raw_string(type, obj)
  338. sha = shafile.sha().digest()
  339. found[sha] = (type, obj)
  340. yield sha, offset, shafile.crc32()
  341. def create_index_v1(self, filename):
  342. entries = list(self.iterentries())
  343. write_pack_index_v1(filename, entries, self.calculate_checksum())
  344. def create_index_v2(self, filename):
  345. entries = list(self.iterentries())
  346. write_pack_index_v1(filename, entries, self.calculate_checksum())
  347. def get_stored_checksum(self):
  348. return self._stored_checksum
  349. def check(self):
  350. return (self.calculate_checksum() == self.get_stored_checksum())
  351. def get_object_at(self, offset):
  352. """Given an offset in to the packfile return the object that is there.
  353. Using the associated index the location of an object can be looked up, and
  354. then the packfile can be asked directly for that object using this
  355. function.
  356. """
  357. assert isinstance(offset, long) or isinstance(offset, int),\
  358. "offset was %r" % offset
  359. assert offset >= self._header_size
  360. size = os.path.getsize(self._filename)
  361. assert size == self._size, "Pack data %s has changed size, I don't " \
  362. "like that" % self._filename
  363. f = open(self._filename, 'rb')
  364. try:
  365. map = simple_mmap(f, offset, size-offset)
  366. return self._unpack_object(map)[:2]
  367. finally:
  368. f.close()
  369. def _unpack_object(self, map):
  370. bytes = take_msb_bytes(map, 0)
  371. type = (bytes[0] >> 4) & 0x07
  372. size = bytes[0] & 0x0f
  373. for i, byte in enumerate(bytes[1:]):
  374. size += (byte & 0x7f) << ((i * 7) + 4)
  375. raw_base = len(bytes)
  376. if type == 6: # offset delta
  377. bytes = take_msb_bytes(map, raw_base)
  378. assert not (bytes[-1] & 0x80)
  379. delta_base_offset = bytes[0] & 0x7f
  380. for byte in bytes[1:]:
  381. delta_base_offset += 1
  382. delta_base_offset <<= 7
  383. delta_base_offset += (byte & 0x7f)
  384. raw_base+=len(bytes)
  385. uncomp, comp_len = read_zlib(map, raw_base, size)
  386. assert size == len(uncomp)
  387. return type, (delta_base_offset, uncomp), comp_len+raw_base
  388. elif type == 7: # ref delta
  389. basename = map[raw_base:raw_base+20]
  390. uncomp, comp_len = read_zlib(map, raw_base+20, size)
  391. assert size == len(uncomp)
  392. return type, (basename, uncomp), comp_len+raw_base+20
  393. else:
  394. uncomp, comp_len = read_zlib(map, raw_base, size)
  395. assert len(uncomp) == size
  396. return type, uncomp, comp_len+raw_base
  397. class SHA1Writer(object):
  398. def __init__(self, f):
  399. self.f = f
  400. self.sha1 = hashlib.sha1("")
  401. def write(self, data):
  402. self.sha1.update(data)
  403. self.f.write(data)
  404. def close(self):
  405. sha = self.sha1.digest()
  406. assert len(sha) == 20
  407. self.f.write(sha)
  408. self.f.close()
  409. return sha
  410. def tell(self):
  411. return self.f.tell()
  412. def write_pack_object(f, type, object):
  413. """Write pack object to a file.
  414. :param f: File to write to
  415. :param o: Object to write
  416. """
  417. ret = f.tell()
  418. if type == 6: # ref delta
  419. (delta_base_offset, object) = object
  420. elif type == 7: # offset delta
  421. (basename, object) = object
  422. size = len(object)
  423. c = (type << 4) | (size & 15)
  424. size >>= 4
  425. while size:
  426. f.write(chr(c | 0x80))
  427. c = size & 0x7f
  428. size >>= 7
  429. f.write(chr(c))
  430. if type == 6: # offset delta
  431. ret = [delta_base_offset & 0x7f]
  432. delta_base_offset >>= 7
  433. while delta_base_offset:
  434. delta_base_offset -= 1
  435. ret.insert(0, 0x80 | (delta_base_offset & 0x7f))
  436. delta_base_offset >>= 7
  437. f.write("".join([chr(x) for x in ret]))
  438. elif type == 7: # ref delta
  439. assert len(basename) == 20
  440. f.write(basename)
  441. f.write(zlib.compress(object))
  442. return f.tell()
  443. def write_pack(filename, objects):
  444. entries, data_sum = write_pack_data(filename + ".pack", objects)
  445. write_pack_index_v2(filename + ".idx", entries, data_sum)
  446. def write_pack_data(filename, objects):
  447. """Write a new pack file.
  448. :param filename: The filename of the new pack file.
  449. :param objects: List of objects to write.
  450. :return: List with (name, offset, crc32 checksum) entries, pack checksum
  451. """
  452. f = open(filename, 'w')
  453. entries = []
  454. f = SHA1Writer(f)
  455. f.write("PACK") # Pack header
  456. f.write(struct.pack(">L", 2)) # Pack version
  457. f.write(struct.pack(">L", len(objects))) # Number of objects in pack
  458. for o in objects:
  459. sha1 = o.sha().digest()
  460. crc32 = o.crc32()
  461. # FIXME: Delta !
  462. t, o = o.as_raw_string()
  463. offset = write_pack_object(f, t, o)
  464. entries.append((sha1, offset, crc32))
  465. return entries, f.close()
  466. def write_pack_index_v1(filename, entries, pack_checksum):
  467. """Write a new pack index file.
  468. :param filename: The filename of the new pack index file.
  469. :param entries: List of tuples with object name (sha), offset_in_pack, and
  470. crc32_checksum.
  471. :param pack_checksum: Checksum of the pack file.
  472. """
  473. # Sort entries first
  474. entries = sorted(entries)
  475. f = open(filename, 'w')
  476. f = SHA1Writer(f)
  477. fan_out_table = defaultdict(lambda: 0)
  478. for (name, offset, entry_checksum) in entries:
  479. fan_out_table[ord(name[0])] += 1
  480. # Fan-out table
  481. for i in range(0x100):
  482. f.write(struct.pack(">L", fan_out_table[i]))
  483. fan_out_table[i+1] += fan_out_table[i]
  484. for (name, offset, entry_checksum) in entries:
  485. f.write(struct.pack(">L20s", offset, name))
  486. assert len(pack_checksum) == 20
  487. f.write(pack_checksum)
  488. f.close()
  489. def apply_delta(src_buf, delta):
  490. """Based on the similar function in git's patch-delta.c."""
  491. assert isinstance(src_buf, str), "was %r" % (src_buf,)
  492. assert isinstance(delta, str)
  493. out = ""
  494. def pop(delta):
  495. ret = delta[0]
  496. delta = delta[1:]
  497. return ord(ret), delta
  498. def get_delta_header_size(delta):
  499. size = 0
  500. i = 0
  501. while delta:
  502. cmd, delta = pop(delta)
  503. size |= (cmd & ~0x80) << i
  504. i += 7
  505. if not cmd & 0x80:
  506. break
  507. return size, delta
  508. src_size, delta = get_delta_header_size(delta)
  509. dest_size, delta = get_delta_header_size(delta)
  510. assert src_size == len(src_buf)
  511. while delta:
  512. cmd, delta = pop(delta)
  513. if cmd & 0x80:
  514. cp_off = 0
  515. for i in range(4):
  516. if cmd & (1 << i):
  517. x, delta = pop(delta)
  518. cp_off |= x << (i * 8)
  519. cp_size = 0
  520. for i in range(3):
  521. if cmd & (1 << (4+i)):
  522. x, delta = pop(delta)
  523. cp_size |= x << (i * 8)
  524. if cp_size == 0:
  525. cp_size = 0x10000
  526. if (cp_off + cp_size < cp_size or
  527. cp_off + cp_size > src_size or
  528. cp_size > dest_size):
  529. break
  530. out += src_buf[cp_off:cp_off+cp_size]
  531. elif cmd != 0:
  532. out += delta[:cmd]
  533. delta = delta[cmd:]
  534. else:
  535. raise ApplyDeltaError("Invalid opcode 0")
  536. if delta != "":
  537. raise ApplyDeltaError("delta not empty: %r" % delta)
  538. if dest_size != len(out):
  539. raise ApplyDeltaError("dest size incorrect")
  540. return out
  541. def write_pack_index_v2(filename, entries, pack_checksum):
  542. """Write a new pack index file.
  543. :param filename: The filename of the new pack index file.
  544. :param entries: List of tuples with object name (sha), offset_in_pack, and
  545. crc32_checksum.
  546. :param pack_checksum: Checksum of the pack file.
  547. """
  548. # Sort entries first
  549. entries = sorted(entries)
  550. f = open(filename, 'w')
  551. f = SHA1Writer(f)
  552. f.write('\377tOc')
  553. f.write(struct.pack(">L", 2))
  554. fan_out_table = defaultdict(lambda: 0)
  555. for (name, offset, entry_checksum) in entries:
  556. fan_out_table[ord(name[0])] += 1
  557. # Fan-out table
  558. for i in range(0x100):
  559. f.write(struct.pack(">L", fan_out_table[i]))
  560. fan_out_table[i+1] += fan_out_table[i]
  561. for (name, offset, entry_checksum) in entries:
  562. f.write(name)
  563. for (name, offset, entry_checksum) in entries:
  564. f.write(struct.pack(">L", entry_checksum))
  565. for (name, offset, entry_checksum) in entries:
  566. # FIXME: handle if MSBit is set in offset
  567. f.write(struct.pack(">L", offset))
  568. # FIXME: handle table for pack files > 8 Gb
  569. assert len(pack_checksum) == 20
  570. f.write(pack_checksum)
  571. f.close()
  572. class Pack(object):
  573. def __init__(self, basename):
  574. self._basename = basename
  575. self._idx = PackIndex(basename + ".idx")
  576. self._data = None
  577. def _get_data(self):
  578. if self._data is None:
  579. self._data = PackData(self._basename + ".pack")
  580. assert len(self._idx) == len(self._data)
  581. assert self._idx.get_stored_checksums()[0] == self._data.get_stored_checksum()
  582. return self._data
  583. def close(self):
  584. if self._data is not None:
  585. self._data.close()
  586. self._idx.close()
  587. def __eq__(self, other):
  588. return type(self) == type(other) and self._idx == other._idx
  589. def __len__(self):
  590. """Number of entries in this pack."""
  591. return len(self._idx)
  592. def __repr__(self):
  593. return "Pack(%r)" % self._basename
  594. def __iter__(self):
  595. """Iterate over all the sha1s of the objects in this pack."""
  596. return iter(self._idx)
  597. def check(self):
  598. return self._idx.check() and self._get_data().check()
  599. def get_stored_checksum(self):
  600. return self._get_data().get_stored_checksum()
  601. def __contains__(self, sha1):
  602. """Check whether this pack contains a particular SHA1."""
  603. return (self._idx.object_index(sha1) is not None)
  604. def _get_text(self, sha1):
  605. offset = self._idx.object_index(sha1)
  606. if offset is None:
  607. raise KeyError(sha1)
  608. type, obj = self._get_data().get_object_at(offset)
  609. assert isinstance(offset, int)
  610. return resolve_object(offset, type, obj, self._get_text,
  611. self._get_data().get_object_at)
  612. def __getitem__(self, sha1):
  613. """Retrieve the specified SHA1."""
  614. type, uncomp = self._get_text(sha1)
  615. return ShaFile.from_raw_string(type, uncomp)
  616. def iterobjects(self):
  617. for offset, type, obj in self._get_data().iterobjects():
  618. assert isinstance(offset, int)
  619. yield ShaFile.from_raw_string(
  620. *resolve_object(offset, type, obj, self._get_text,
  621. self._get_data().get_object_at))
  622. def load_packs(path):
  623. for name in os.listdir(path):
  624. yield Pack(os.path.join(path, name.rstrip(".pack")))