pack.py 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480
  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. import mmap
  34. import os
  35. import struct
  36. import sys
  37. supports_mmap_offset = (sys.version_info[0] >= 3 or
  38. (sys.version_info[0] == 2 and sys.version_info[1] >= 6))
  39. from objects import (ShaFile,
  40. _decompress,
  41. )
  42. def hex_to_sha(hex):
  43. ret = ""
  44. for i in range(0, len(hex), 2):
  45. ret += chr(int(hex[i:i+2], 16))
  46. return ret
  47. def sha_to_hex(sha):
  48. ret = ""
  49. for i in sha:
  50. ret += "%02x" % ord(i)
  51. return ret
  52. MAX_MMAP_SIZE = 256 * 1024 * 1024
  53. def simple_mmap(f, offset, size, access=mmap.ACCESS_READ):
  54. if offset+size > MAX_MMAP_SIZE and not supports_mmap_offset:
  55. raise AssertionError("%s is larger than 256 meg, and this version "
  56. "of Python does not support the offset argument to mmap().")
  57. if supports_mmap_offset:
  58. return mmap.mmap(f.fileno(), size, access=access, offset=offset)
  59. else:
  60. class ArraySkipper(object):
  61. def __init__(self, array, offset):
  62. self.array = array
  63. self.offset = offset
  64. def __getslice__(self, i, j):
  65. return self.array[i+self.offset:j+self.offset]
  66. def __getitem__(self, i):
  67. return self.array[i+self.offset]
  68. def __len__(self):
  69. return len(self.array) - self.offset
  70. def __str__(self):
  71. return str(self.array[self.offset:])
  72. mem = mmap.mmap(f.fileno(), size+offset, access=access)
  73. if offset == 0:
  74. return mem
  75. return ArraySkipper(mem, offset)
  76. def multi_ord(map, start, count):
  77. value = 0
  78. for i in range(count):
  79. value = value * 0x100 + ord(map[start+i])
  80. return value
  81. class PackIndex(object):
  82. """An index in to a packfile.
  83. Given a sha id of an object a pack index can tell you the location in the
  84. packfile of that object if it has it.
  85. To do the loop it opens the file, and indexes first 256 4 byte groups
  86. with the first byte of the sha id. The value in the four byte group indexed
  87. is the end of the group that shares the same starting byte. Subtract one
  88. from the starting byte and index again to find the start of the group.
  89. The values are sorted by sha id within the group, so do the math to find
  90. the start and end offset and then bisect in to find if the value is present.
  91. """
  92. PACK_INDEX_HEADER_SIZE = 0x100 * 4
  93. sha_bytes = 20
  94. record_size = sha_bytes + 4
  95. def __init__(self, filename):
  96. """Create a pack index object.
  97. Provide it with the name of the index file to consider, and it will map
  98. it whenever required.
  99. """
  100. self._filename = filename
  101. assert os.path.exists(filename), "%s is not a pack index" % filename
  102. # Take the size now, so it can be checked each time we map the file to
  103. # ensure that it hasn't changed.
  104. self._size = os.path.getsize(filename)
  105. self._file = open(filename, 'r')
  106. self._contents = simple_mmap(self._file, 0, self._size)
  107. if self._contents[:4] != '\377tOc':
  108. self.version = 1
  109. self._fan_out_table = self._read_fan_out_table(0)
  110. else:
  111. (self.version, ) = struct.unpack_from(">L", self._contents, 4)
  112. assert self.version in (2,), "Version was %d" % self.version
  113. self._fan_out_table = self._read_fan_out_table(8)
  114. self._name_table_offset = 8 + 0x100 * 4
  115. self._crc32_table_offset = self._name_table_offset + 20 * len(self)
  116. self._pack_offset_table_offset = self._crc32_table_offset + 4 * len(self)
  117. def close(self):
  118. self._file.close()
  119. def __len__(self):
  120. """Return the number of entries in this pack index."""
  121. return self._fan_out_table[-1]
  122. def _unpack_entry(self, i):
  123. """Unpack the i-th entry in the index file.
  124. :return: Tuple with object name (SHA), offset in pack file and
  125. CRC32 checksum (if known)."""
  126. if self.version == 1:
  127. (offset, name) = struct.unpack_from(">L20s", self._contents,
  128. self.PACK_INDEX_HEADER_SIZE + (i * self.record_size))
  129. return (name, offset, None)
  130. else:
  131. return (self._unpack_name(i), self._unpack_offset(i),
  132. self._unpack_crc32_checksum(i))
  133. def _unpack_name(self, i):
  134. if self.version == 1:
  135. return self._unpack_entry(i)[0]
  136. else:
  137. return struct.unpack_from("20s", self._contents,
  138. self._name_table_offset + i * 20)[0]
  139. def _unpack_offset(self, i):
  140. if self.version == 1:
  141. return self._unpack_entry(i)[1]
  142. else:
  143. return struct.unpack_from(">L", self._contents,
  144. self._pack_offset_table_offset + i * 4)[0]
  145. def _unpack_crc32_checksum(self, i):
  146. if self.version == 1:
  147. return None
  148. else:
  149. return struct.unpack_from(">L", self._contents,
  150. self._crc32_table_offset + i * 4)[0]
  151. def __iter__(self):
  152. for i in range(len(self)):
  153. yield sha_to_hex(self._unpack_name(i))
  154. def iterentries(self):
  155. """Iterate over the entries in this pack index.
  156. Will yield tuples with object name, offset in packfile and crc32 checksum.
  157. """
  158. for i in range(len(self)):
  159. yield self._unpack_entry(i)
  160. def _read_fan_out_table(self, start_offset):
  161. ret = []
  162. for i in range(0x100):
  163. ret.append(struct.unpack(">L", self._contents[start_offset+i*4:start_offset+(i+1)*4])[0])
  164. return ret
  165. def check(self):
  166. """Check that the stored checksum matches the actual checksum."""
  167. return self.calculate_checksum() == self.get_stored_checksums()[1]
  168. def calculate_checksum(self):
  169. f = open(self._filename, 'r')
  170. try:
  171. return hashlib.sha1(self._contents[:-20]).digest()
  172. finally:
  173. f.close()
  174. def get_stored_checksums(self):
  175. """Return the SHA1 checksums stored for the corresponding packfile and
  176. this header file itself."""
  177. return str(self._contents[-40:-20]), str(self._contents[-20:])
  178. def object_index(self, sha):
  179. """Return the index in to the corresponding packfile for the object.
  180. Given the name of an object it will return the offset that object lives
  181. at within the corresponding pack file. If the pack file doesn't have the
  182. object then None will be returned.
  183. """
  184. size = os.path.getsize(self._filename)
  185. assert size == self._size, "Pack index %s has changed size, I don't " \
  186. "like that" % self._filename
  187. return self._object_index(hex_to_sha(sha))
  188. def _object_index(self, sha):
  189. """See object_index"""
  190. start = self._fan_out_table[ord(sha[0])-1]
  191. end = self._fan_out_table[ord(sha[0])]
  192. while start < end:
  193. i = (start + end)/2
  194. file_sha = self._unpack_name(i)
  195. if file_sha == sha:
  196. return self._unpack_offset(i)
  197. elif file_sha < sha:
  198. start = i + 1
  199. else:
  200. end = i - 1
  201. return None
  202. class PackData(object):
  203. """The data contained in a packfile.
  204. Pack files can be accessed both sequentially for exploding a pack, and
  205. directly with the help of an index to retrieve a specific object.
  206. The objects within are either complete or a delta aginst another.
  207. The header is variable length. If the MSB of each byte is set then it
  208. indicates that the subsequent byte is still part of the header.
  209. For the first byte the next MS bits are the type, which tells you the type
  210. of object, and whether it is a delta. The LS byte is the lowest bits of the
  211. size. For each subsequent byte the LS 7 bits are the next MS bits of the
  212. size, i.e. the last byte of the header contains the MS bits of the size.
  213. For the complete objects the data is stored as zlib deflated data.
  214. The size in the header is the uncompressed object size, so to uncompress
  215. you need to just keep feeding data to zlib until you get an object back,
  216. or it errors on bad data. This is done here by just giving the complete
  217. buffer from the start of the deflated object on. This is bad, but until I
  218. get mmap sorted out it will have to do.
  219. Currently there are no integrity checks done. Also no attempt is made to try
  220. and detect the delta case, or a request for an object at the wrong position.
  221. It will all just throw a zlib or KeyError.
  222. """
  223. def __init__(self, filename):
  224. """Create a PackData object that represents the pack in the given filename.
  225. The file must exist and stay readable until the object is disposed of. It
  226. must also stay the same size. It will be mapped whenever needed.
  227. Currently there is a restriction on the size of the pack as the python
  228. mmap implementation is flawed.
  229. """
  230. self._filename = filename
  231. assert os.path.exists(filename), "%s is not a packfile" % filename
  232. self._size = os.path.getsize(filename)
  233. self._read_header()
  234. def _read_header(self):
  235. f = open(self._filename, 'rb')
  236. try:
  237. header = f.read(12)
  238. f.seek(self._size-20)
  239. self._stored_checksum = f.read(20)
  240. finally:
  241. f.close()
  242. assert header[:4] == "PACK"
  243. (version,) = struct.unpack_from(">L", header, 4)
  244. assert version in (2, 3), "Version was %d" % version
  245. (self._num_objects,) = struct.unpack_from(">L", header, 8)
  246. def __len__(self):
  247. """Returns the number of objects in this pack."""
  248. return self._num_objects
  249. def calculate_checksum(self):
  250. f = open(self._filename, 'rb')
  251. try:
  252. map = simple_mmap(f, 0, self._size)
  253. return hashlib.sha1(map[:-20]).digest()
  254. finally:
  255. f.close()
  256. def check(self):
  257. return (self.calculate_checksum() == self._stored_checksum)
  258. def get_object_at(self, offset):
  259. """Given an offset in to the packfile return the object that is there.
  260. Using the associated index the location of an object can be looked up, and
  261. then the packfile can be asked directly for that object using this
  262. function.
  263. Currently only non-delta objects are supported.
  264. """
  265. assert isinstance(offset, long) or isinstance(offset, int)
  266. size = os.path.getsize(self._filename)
  267. assert size == self._size, "Pack data %s has changed size, I don't " \
  268. "like that" % self._filename
  269. f = open(self._filename, 'rb')
  270. try:
  271. map = simple_mmap(f, offset, size-offset)
  272. return self._get_object_at(map)
  273. finally:
  274. f.close()
  275. def _get_object_at(self, map):
  276. first_byte = ord(map[0])
  277. sign_extend = first_byte & 0x80
  278. type = (first_byte >> 4) & 0x07
  279. size = first_byte & 0x0f
  280. cur_offset = 0
  281. while sign_extend > 0:
  282. byte = ord(map[cur_offset+1])
  283. sign_extend = byte & 0x80
  284. size_part = byte & 0x7f
  285. size += size_part << ((cur_offset * 7) + 4)
  286. cur_offset += 1
  287. raw_base = cur_offset+1
  288. # The size is the inflated size, so we have no idea what the deflated size
  289. # is, so for now give it as much as we have. It should really iterate
  290. # feeding it more data if it doesn't decompress, but as we have the whole
  291. # thing then just use it.
  292. raw = map[raw_base:]
  293. uncomp = _decompress(raw)
  294. obj = ShaFile.from_raw_string(type, uncomp)
  295. return obj
  296. class SHA1Writer(object):
  297. def __init__(self, f):
  298. self.f = f
  299. self.sha1 = hashlib.sha1("")
  300. def write(self, data):
  301. self.sha1.update(data)
  302. self.f.write(data)
  303. def close(self):
  304. sha = self.sha1.digest()
  305. assert len(sha) == 20
  306. self.f.write(sha)
  307. self.f.close()
  308. return sha
  309. def write_pack(filename, objects):
  310. """Write a new pack file.
  311. :param filename: The filename of the new pack file.
  312. :param objects: List of objects to write.
  313. :return: List with (name, offset, crc32 checksum) entries, pack checksum
  314. """
  315. f = open(filename, 'w')
  316. entries = []
  317. f = SHA1Writer(f)
  318. f.write("PACK") # Pack header
  319. f.write(struct.pack(">L", 2)) # Pack version
  320. f.write(struct.pack(">L", len(objects))) # Number of objects in pack
  321. for o in objects:
  322. pass # FIXME: Write object
  323. return entries, f.close()
  324. def write_pack_index_v1(filename, entries, pack_checksum):
  325. """Write a new pack index file.
  326. :param filename: The filename of the new pack index file.
  327. :param entries: List of tuples with object name (sha), offset_in_pack, and
  328. crc32_checksum.
  329. :param pack_checksum: Checksum of the pack file.
  330. """
  331. # Sort entries first
  332. entries = sorted(entries)
  333. f = open(filename, 'w')
  334. f = SHA1Writer(f)
  335. fan_out_table = defaultdict(lambda: 0)
  336. for (name, offset, entry_checksum) in entries:
  337. fan_out_table[ord(name[0])] += 1
  338. # Fan-out table
  339. for i in range(0x100):
  340. f.write(struct.pack(">L", fan_out_table[i]))
  341. fan_out_table[i+1] += fan_out_table[i]
  342. for (name, offset, entry_checksum) in entries:
  343. f.write(struct.pack(">L20s", offset, name))
  344. assert len(pack_checksum) == 20
  345. f.write(pack_checksum)
  346. f.close()
  347. def write_pack_index_v2(filename, entries, pack_checksum):
  348. """Write a new pack index file.
  349. :param filename: The filename of the new pack index file.
  350. :param entries: List of tuples with object name (sha), offset_in_pack, and
  351. crc32_checksum.
  352. :param pack_checksum: Checksum of the pack file.
  353. """
  354. # Sort entries first
  355. entries = sorted(entries)
  356. f = open(filename, 'w')
  357. f = SHA1Writer(f)
  358. f.write('\377tOc')
  359. f.write(struct.pack(">L", 2))
  360. fan_out_table = defaultdict(lambda: 0)
  361. for (name, offset, entry_checksum) in entries:
  362. fan_out_table[ord(name[0])] += 1
  363. # Fan-out table
  364. for i in range(0x100):
  365. f.write(struct.pack(">L", fan_out_table[i]))
  366. fan_out_table[i+1] += fan_out_table[i]
  367. for (name, offset, entry_checksum) in entries:
  368. f.write(name)
  369. for (name, offset, entry_checksum) in entries:
  370. f.write(struct.pack(">L", entry_checksum))
  371. for (name, offset, entry_checksum) in entries:
  372. # FIXME: handle if MSBit is set in offset
  373. f.write(struct.pack(">L", offset))
  374. # FIXME: handle table for pack files > 8 Gb
  375. assert len(pack_checksum) == 20
  376. f.write(pack_checksum)
  377. f.close()
  378. class Pack(object):
  379. def __init__(self, basename):
  380. self._basename = basename
  381. self._idx = PackIndex(basename + ".idx")
  382. self._pack = PackData(basename + ".pack")
  383. assert len(self._idx) == len(self._pack)
  384. def __len__(self):
  385. return len(self._idx)
  386. def __repr__(self):
  387. return "Pack(%r)" % self._basename
  388. def __iter__(self):
  389. return iter(self._idx)
  390. def check(self):
  391. return self._idx.check() and self._pack.check()
  392. def __contains__(self, sha1):
  393. return (self._idx.object_index(sha1) is not None)
  394. def __getitem__(self, sha1):
  395. return self._pack.get_object_at(self._idx.object_index(sha1))