object_store.py 7.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274
  1. # object_store.py -- Object store for git objects
  2. # Copyright (C) 2008 Jelmer Vernooij <jelmer@samba.org>
  3. #
  4. # This program is free software; you can redistribute it and/or
  5. # modify it under the terms of the GNU General Public License
  6. # as published by the Free Software Foundation; either version 2
  7. # or (at your option) a later version of the License.
  8. #
  9. # This program is distributed in the hope that it will be useful,
  10. # but WITHOUT ANY WARRANTY; without even the implied warranty of
  11. # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  12. # GNU General Public License for more details.
  13. #
  14. # You should have received a copy of the GNU General Public License
  15. # along with this program; if not, write to the Free Software
  16. # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
  17. # MA 02110-1301, USA.
  18. import os
  19. import tempfile
  20. import urllib2
  21. from dulwich.objects import (
  22. ShaFile,
  23. hex_to_sha,
  24. sha_to_hex,
  25. )
  26. from dulwich.pack import (
  27. Pack,
  28. PackData,
  29. iter_sha1,
  30. load_packs,
  31. write_pack,
  32. write_pack_data,
  33. write_pack_index_v2,
  34. )
  35. PACKDIR = 'pack'
  36. class ObjectStore(object):
  37. """Object store."""
  38. def __init__(self, path):
  39. """Open an object store.
  40. :param path: Path of the object store.
  41. """
  42. self.path = path
  43. self._pack_cache = None
  44. self.pack_dir = os.path.join(self.path, PACKDIR)
  45. def determine_wants_all(self, refs):
  46. return [sha for (ref, sha) in refs.iteritems() if not sha in self and not ref.endswith("^{}")]
  47. def iter_shas(self, shas):
  48. """Iterate over the objects for the specified shas.
  49. :param shas: Iterable object with SHAs
  50. """
  51. return ObjectStoreIterator(self, shas)
  52. def __contains__(self, sha):
  53. for pack in self.packs:
  54. if sha in pack:
  55. return True
  56. ret = self._get_shafile(sha)
  57. if ret is not None:
  58. return True
  59. return False
  60. @property
  61. def packs(self):
  62. """List with pack objects."""
  63. if self._pack_cache is None:
  64. self._pack_cache = list(load_packs(self.pack_dir))
  65. return self._pack_cache
  66. def _add_known_pack(self, path):
  67. """Add a newly appeared pack to the cache by path.
  68. """
  69. if self._pack_cache is not None:
  70. self._pack_cache.append(Pack(path))
  71. def _get_shafile_path(self, sha):
  72. dir = sha[:2]
  73. file = sha[2:]
  74. # Check from object dir
  75. return os.path.join(self.path, dir, file)
  76. def _get_shafile(self, sha):
  77. path = self._get_shafile_path(sha)
  78. if os.path.exists(path):
  79. return ShaFile.from_file(path)
  80. return None
  81. def _add_shafile(self, sha, o):
  82. path = self._get_shafile_path(sha)
  83. f = os.path.open(path, 'w')
  84. try:
  85. f.write(o._header())
  86. f.write(o._text)
  87. finally:
  88. f.close()
  89. def get_raw(self, name):
  90. """Obtain the raw text for an object.
  91. :param name: sha for the object.
  92. :return: tuple with object type and object contents.
  93. """
  94. if len(name) == 40:
  95. sha = hex_to_sha(name)
  96. hexsha = name
  97. elif len(name) == 20:
  98. sha = name
  99. hexsha = None
  100. else:
  101. raise AssertionError
  102. for pack in self.packs:
  103. try:
  104. return pack.get_raw(sha)
  105. except KeyError:
  106. pass
  107. if hexsha is None:
  108. hexsha = sha_to_hex(name)
  109. ret = self._get_shafile(hexsha)
  110. if ret is not None:
  111. return ret.as_raw_string()
  112. raise KeyError(hexsha)
  113. def __getitem__(self, sha):
  114. type, uncomp = self.get_raw(sha)
  115. return ShaFile.from_raw_string(type, uncomp)
  116. def move_in_thin_pack(self, path):
  117. """Move a specific file containing a pack into the pack directory.
  118. :note: The file should be on the same file system as the
  119. packs directory.
  120. :param path: Path to the pack file.
  121. """
  122. p = PackData(path)
  123. temppath = os.path.join(self.pack_dir,
  124. sha_to_hex(urllib2.randombytes(20))+".temppack")
  125. write_pack(temppath, p.iterobjects(self.get_raw), len(p))
  126. pack_sha = PackIndex(temppath+".idx").objects_sha1()
  127. newbasename = os.path.join(self.pack_dir, "pack-%s" % pack_sha)
  128. os.rename(temppath+".pack", newbasename+".pack")
  129. os.rename(temppath+".idx", newbasename+".idx")
  130. self._add_known_pack(newbasename)
  131. def move_in_pack(self, path):
  132. """Move a specific file containing a pack into the pack directory.
  133. :note: The file should be on the same file system as the
  134. packs directory.
  135. :param path: Path to the pack file.
  136. """
  137. p = PackData(path)
  138. entries = p.sorted_entries()
  139. basename = os.path.join(self.pack_dir,
  140. "pack-%s" % iter_sha1(entry[0] for entry in entries))
  141. write_pack_index_v2(basename+".idx", entries, p.get_stored_checksum())
  142. os.rename(path, basename + ".pack")
  143. self._add_known_pack(basename)
  144. def add_thin_pack(self):
  145. """Add a new thin pack to this object store.
  146. Thin packs are packs that contain deltas with parents that exist
  147. in a different pack.
  148. """
  149. fd, path = tempfile.mkstemp(dir=self.pack_dir, suffix=".pack")
  150. f = os.fdopen(fd, 'w')
  151. def commit():
  152. os.fsync(fd)
  153. f.close()
  154. if os.path.getsize(path) > 0:
  155. self.move_in_thin_pack(path)
  156. return f, commit
  157. def add_pack(self):
  158. """Add a new pack to this object store.
  159. :return: Fileobject to write to and a commit function to
  160. call when the pack is finished.
  161. """
  162. fd, path = tempfile.mkstemp(dir=self.pack_dir, suffix=".pack")
  163. f = os.fdopen(fd, 'w')
  164. def commit():
  165. os.fsync(fd)
  166. f.close()
  167. if os.path.getsize(path) > 0:
  168. self.move_in_pack(path)
  169. return f, commit
  170. def add_objects(self, objects):
  171. """Add a set of objects to this object store.
  172. :param objects: Iterable over a list of objects.
  173. """
  174. if len(objects) == 0:
  175. return
  176. f, commit = self.add_pack()
  177. write_pack_data(f, objects, len(objects))
  178. commit()
  179. class ObjectImporter(object):
  180. """Interface for importing objects."""
  181. def __init__(self, count):
  182. """Create a new ObjectImporter.
  183. :param count: Number of objects that's going to be imported.
  184. """
  185. self.count = count
  186. def add_object(self, object):
  187. """Add an object."""
  188. raise NotImplementedError(self.add_object)
  189. def finish(self, object):
  190. """Finish the imoprt and write objects to disk."""
  191. raise NotImplementedError(self.finish)
  192. class ObjectIterator(object):
  193. """Interface for iterating over objects."""
  194. def iterobjects(self):
  195. raise NotImplementedError(self.iterobjects)
  196. class ObjectStoreIterator(ObjectIterator):
  197. """ObjectIterator that works on top of an ObjectStore."""
  198. def __init__(self, store, sha_iter):
  199. self.store = store
  200. self.sha_iter = sha_iter
  201. self._shas = []
  202. def __iter__(self):
  203. for sha, path in self.itershas():
  204. yield self.store[sha], path
  205. def iterobjects(self):
  206. for o, path in self:
  207. yield o
  208. def itershas(self):
  209. for sha in self._shas:
  210. yield sha
  211. for sha in self.sha_iter:
  212. self._shas.append(sha)
  213. yield sha
  214. def __contains__(self, needle):
  215. """Check if an object is present.
  216. :param needle: SHA1 of the object to check for
  217. """
  218. return needle in self.store
  219. def __getitem__(self, key):
  220. """Find an object by SHA1."""
  221. return self.store[key]
  222. def __len__(self):
  223. """Return the number of objects."""
  224. return len(list(self.itershas()))