pack.py 8.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219
  1. # pack.py -- For dealing wih packed git objects.
  2. # Copyright (C) 2007 James Westby <jw+debian@jameswestby.net>
  3. # The code is loosely based on that in the sha1_file.c file from git itself,
  4. # which is Copyright (C) Linus Torvalds, 2005 and distributed under the
  5. # GPL version 2.
  6. #
  7. # This program is free software; you can redistribute it and/or
  8. # modify it under the terms of the GNU General Public License
  9. # as published by the Free Software Foundation; version 2
  10. # of the License.
  11. #
  12. # This program is distributed in the hope that it will be useful,
  13. # but WITHOUT ANY WARRANTY; without even the implied warranty of
  14. # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  15. # GNU General Public License for more details.
  16. #
  17. # You should have received a copy of the GNU General Public License
  18. # along with this program; if not, write to the Free Software
  19. # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
  20. # MA 02110-1301, USA.
  21. """Classes for dealing with packed git objects.
  22. A pack is a compact representation of a bunch of objects, stored
  23. using deltas where possible.
  24. They have two parts, the pack file, which stores the data, and an index
  25. that tells you where the data is.
  26. To find an object you look in all of the index files 'til you find a
  27. match for the object name. You then use the pointer got from this as
  28. a pointer in to the corresponding packfile.
  29. """
  30. import mmap
  31. import os
  32. from objects import (ShaFile,
  33. _decompress,
  34. )
  35. def hex_to_sha(hex):
  36. """Converts a hex value to the number it represents"""
  37. mapping = { '0' : 0, '1' : 1, '2' : 2, '3' : 3, '4' : 4, '5' : 5, '6' : 6,
  38. '7' : 7, '8' : 8, '9' : 9, 'a' : 10, 'b' : 11, 'c' : 12,
  39. 'd' : 13, 'e' : 14, 'f' : 15}
  40. value = 0
  41. for c in hex:
  42. value = (16 * value) + mapping[c]
  43. return value
  44. def multi_ord(map, start, count):
  45. value = 0
  46. for i in range(count):
  47. value = value * 256 + ord(map[start+i])
  48. return value
  49. max_size = 256 * 1024 * 1024
  50. class PackIndex(object):
  51. """An index in to a packfile.
  52. Given a sha id of an object a pack index can tell you the location in the
  53. packfile of that object if it has it.
  54. To do the looup it opens the file, and indexes first 256 4 byte groups
  55. with the first byte of the sha id. The value in the four byte group indexed
  56. is the end of the group that shares the same starting byte. Subtract one
  57. from the starting byte and index again to find the start of the group.
  58. The values are sorted by sha id within the group, so do the math to find
  59. the start and end offset and then bisect in to find if the value is present.
  60. """
  61. header_record_size = 4
  62. header_size = 256 * header_record_size
  63. index_size = 4
  64. sha_bytes = 20
  65. record_size = sha_bytes + index_size
  66. def __init__(self, filename):
  67. """Create a pack index object.
  68. Provide it with the name of the index file to consider, and it will map
  69. it whenever required.
  70. """
  71. self._filename = filename
  72. assert os.path.exists(filename), "%s is not a pack index" % filename
  73. # Take the size now, so it can be checked each time we map the file to
  74. # ensure that it hasn't changed.
  75. self._size = os.path.getsize(filename)
  76. assert self._size > self.header_size, "%s is too small to be a packfile" % \
  77. filename
  78. assert self._size < max_size, "%s is larger than 256 meg, and it " \
  79. "might not be a good idea to mmap it. If you want to go ahead " \
  80. "delete this check, or get python to support mmap offsets so that " \
  81. "I can map the files sensibly"
  82. def object_index(self, sha):
  83. """Return the index in to the corresponding packfile for the object.
  84. Given the name of an object it will return the offset that object lives
  85. at within the corresponding pack file. If the pack file doesn't have the
  86. object then None will be returned.
  87. """
  88. size = os.path.getsize(self._filename)
  89. assert size == self._size, "Pack index %s has changed size, I don't " \
  90. "like that" % self._filename
  91. f = open(self._filename, 'rb')
  92. try:
  93. map = mmap.mmap(f.fileno(), size, access=mmap.ACCESS_READ)
  94. return self._object_index(map, sha)
  95. finally:
  96. f.close()
  97. def _object_index(self, map, hexsha):
  98. """See object_index"""
  99. first_byte = hex_to_sha(hexsha[:2])
  100. header_offset = self.header_record_size * first_byte
  101. start = multi_ord(map, header_offset-self.header_record_size, self.header_record_size)
  102. end = multi_ord(map, header_offset, self.header_record_size)
  103. sha = hex_to_sha(hexsha)
  104. while start < end:
  105. i = (start + end)/2
  106. offset = self.header_size + (i * self.record_size)
  107. file_sha = multi_ord(map, offset + self.index_size, self.sha_bytes)
  108. if file_sha == sha:
  109. return multi_ord(map, offset, self.index_size)
  110. elif file_sha < sha:
  111. start = offset + 1
  112. else:
  113. end = offset - 1
  114. return None
  115. class PackData(object):
  116. """The data contained in a packfile.
  117. Pack files can be accessed both sequentially for exploding a pack, and
  118. directly with the help of an index to retrieve a specific object.
  119. The objects within are either complete or a delta aginst another.
  120. The header is variable length. If the MSB of each byte is set then it
  121. indicates that the subsequent byte is still part of the header.
  122. For the first byte the next MS bits are the type, which tells you the type
  123. of object, and whether it is a delta. The LS byte is the lowest bits of the
  124. size. For each subsequent byte the LS 7 bits are the next MS bits of the
  125. size, i.e. the last byte of the header contains the MS bits of the size.
  126. For the complete objects the data is stored as zlib deflated data.
  127. The size in the header is the uncompressed object size, so to uncompress
  128. you need to just keep feeding data to zlib until you get an object back,
  129. or it errors on bad data. This is done here by just giving the complete
  130. buffer from the start of the deflated object on. This is bad, but until I
  131. get mmap sorted out it will have to do.
  132. Currently there are no integrity checks done. Also no attempt is made to try
  133. and detect the delta case, or a request for an object at the wrong position.
  134. It will all just throw a zlib or KeyError.
  135. """
  136. def __init__(self, filename):
  137. """Create a PackData object that represents the pack in the given filename.
  138. The file must exist and stay readable until the object is disposed of. It
  139. must also stay the same size. It will be mapped whenever needed.
  140. Currently there is a restriction on the size of the pack as the python
  141. mmap implementation is flawed.
  142. """
  143. self._filename = filename
  144. assert os.path.exists(filename), "%s is not a packfile" % filename
  145. self._size = os.path.getsize(filename)
  146. assert self._size < max_size, "%s is larger than 256 meg, and it " \
  147. "might not be a good idea to mmap it. If you want to go ahead " \
  148. "delete this check, or get python to support mmap offsets so that " \
  149. "I can map the files sensibly"
  150. def get_object_at(self, offset):
  151. """Given an offset in to the packfile return the object that is there.
  152. Using the associated index the location of an object can be looked up, and
  153. then the packfile can be asked directly for that object using this
  154. function.
  155. Currently only non-delta objects are supported.
  156. """
  157. size = os.path.getsize(self._filename)
  158. assert size == self._size, "Pack data %s has changed size, I don't " \
  159. "like that" % self._filename
  160. f = open(self._filename, 'rb')
  161. try:
  162. map = mmap.mmap(f.fileno(), size, access=mmap.ACCESS_READ)
  163. return self._get_object_at(map, offset)
  164. finally:
  165. f.close()
  166. def _get_object_at(self, map, offset):
  167. first_byte = ord(map[offset])
  168. sign_extend = first_byte & 0x80
  169. type = (first_byte >> 4) & 0x07
  170. size = first_byte & 0x0f
  171. cur_offset = 0
  172. while sign_extend > 0:
  173. byte = ord(map[offset+cur_offset+1])
  174. sign_extend = byte & 0x80
  175. size_part = byte & 0x7f
  176. size += size_part << ((cur_offset * 7) + 4)
  177. cur_offset += 1
  178. raw_base = offset+cur_offset+1
  179. # The size is the inflated size, so we have no idea what the deflated size
  180. # is, so for now give it as much as we have. It should really iterate
  181. # feeding it more data if it doesn't decompress, but as we have the whole
  182. # thing then just use it.
  183. raw = map[raw_base:]
  184. uncomp = _decompress(raw)
  185. obj = ShaFile.from_raw_string(type, uncomp)
  186. return obj