object_store.py 7.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271
  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. # TODO: This can be more efficient
  54. try:
  55. self[sha]
  56. return True
  57. except KeyError:
  58. return False
  59. @property
  60. def packs(self):
  61. """List with pack objects."""
  62. if self._pack_cache is None:
  63. self._pack_cache = list(load_packs(self.pack_dir))
  64. return self._pack_cache
  65. def _add_known_pack(self, path):
  66. """Add a newly appeared pack to the cache by path.
  67. """
  68. if self._pack_cache is not None:
  69. self._pack_cache.append(Pack(path))
  70. def _get_shafile_path(self, sha):
  71. dir = sha[:2]
  72. file = sha[2:]
  73. # Check from object dir
  74. return os.path.join(self.path, dir, file)
  75. def _get_shafile(self, sha):
  76. path = self._get_shafile_path(sha)
  77. if os.path.exists(path):
  78. return ShaFile.from_file(path)
  79. return None
  80. def _add_shafile(self, sha, o):
  81. path = self._get_shafile_path(sha)
  82. f = os.path.open(path, 'w')
  83. try:
  84. f.write(o._header())
  85. f.write(o._text)
  86. finally:
  87. f.close()
  88. def get_raw(self, sha):
  89. """Obtain the raw text for an object.
  90. :param sha: Sha for the object.
  91. :return: tuple with object type and object contents.
  92. """
  93. for pack in self.packs:
  94. if sha in pack:
  95. return pack.get_raw(sha, self.get_raw)
  96. # FIXME: Are thin pack deltas ever against on-disk shafiles ?
  97. ret = self._get_shafile(sha)
  98. if ret is not None:
  99. return ret.as_raw_string()
  100. raise KeyError(sha)
  101. def __getitem__(self, sha):
  102. assert len(sha) == 40, "Incorrect length sha: %s" % str(sha)
  103. ret = self._get_shafile(sha)
  104. if ret is not None:
  105. return ret
  106. # Check from packs
  107. type, uncomp = self.get_raw(sha)
  108. return ShaFile.from_raw_string(type, uncomp)
  109. def move_in_thin_pack(self, path):
  110. """Move a specific file containing a pack into the pack directory.
  111. :note: The file should be on the same file system as the
  112. packs directory.
  113. :param path: Path to the pack file.
  114. """
  115. p = PackData(path)
  116. temppath = os.path.join(self.pack_dir,
  117. sha_to_hex(urllib2.randombytes(20))+".temppack")
  118. write_pack(temppath, p.iterobjects(self.get_raw), len(p))
  119. pack_sha = PackIndex(temppath+".idx").objects_sha1()
  120. newbasename = os.path.join(self.pack_dir, "pack-%s" % pack_sha)
  121. os.rename(temppath+".pack", newbasename+".pack")
  122. os.rename(temppath+".idx", newbasename+".idx")
  123. self._add_known_pack(newbasename)
  124. def move_in_pack(self, path):
  125. """Move a specific file containing a pack into the pack directory.
  126. :note: The file should be on the same file system as the
  127. packs directory.
  128. :param path: Path to the pack file.
  129. """
  130. p = PackData(path)
  131. entries = p.sorted_entries()
  132. basename = os.path.join(self.pack_dir,
  133. "pack-%s" % iter_sha1(entry[0] for entry in entries))
  134. write_pack_index_v2(basename+".idx", entries, p.get_stored_checksum())
  135. os.rename(path, basename + ".pack")
  136. self._add_known_pack(basename)
  137. def add_thin_pack(self):
  138. """Add a new thin pack to this object store.
  139. Thin packs are packs that contain deltas with parents that exist
  140. in a different pack.
  141. """
  142. fd, path = tempfile.mkstemp(dir=self.pack_dir, suffix=".pack")
  143. f = os.fdopen(fd, 'w')
  144. def commit():
  145. os.fsync(fd)
  146. f.close()
  147. if os.path.getsize(path) > 0:
  148. self.move_in_thin_pack(path)
  149. return f, commit
  150. def add_pack(self):
  151. """Add a new pack to this object store.
  152. :return: Fileobject to write to and a commit function to
  153. call when the pack is finished.
  154. """
  155. fd, path = tempfile.mkstemp(dir=self.pack_dir, suffix=".pack")
  156. f = os.fdopen(fd, 'w')
  157. def commit():
  158. os.fsync(fd)
  159. f.close()
  160. if os.path.getsize(path) > 0:
  161. self.move_in_pack(path)
  162. return f, commit
  163. def add_objects(self, objects):
  164. """Add a set of objects to this object store.
  165. :param objects: Iterable over a list of objects.
  166. """
  167. if len(objects) == 0:
  168. return
  169. f, commit = self.add_pack()
  170. write_pack_data(f, objects, len(objects))
  171. commit()
  172. class ObjectImporter(object):
  173. """Interface for importing objects."""
  174. def __init__(self, count):
  175. """Create a new ObjectImporter.
  176. :param count: Number of objects that's going to be imported.
  177. """
  178. self.count = count
  179. def add_object(self, object):
  180. """Add an object."""
  181. raise NotImplementedError(self.add_object)
  182. def finish(self, object):
  183. """Finish the imoprt and write objects to disk."""
  184. raise NotImplementedError(self.finish)
  185. class ObjectIterator(object):
  186. """Interface for iterating over objects."""
  187. def iterobjects(self):
  188. raise NotImplementedError(self.iterobjects)
  189. class ObjectStoreIterator(ObjectIterator):
  190. """ObjectIterator that works on top of an ObjectStore."""
  191. def __init__(self, store, sha_iter):
  192. self.store = store
  193. self.sha_iter = sha_iter
  194. self._shas = []
  195. def __iter__(self):
  196. for sha, path in self.itershas():
  197. yield self.store[sha], path
  198. def iterobjects(self):
  199. for o, path in self:
  200. yield o
  201. def itershas(self):
  202. for sha in self._shas:
  203. yield sha
  204. for sha in self.sha_iter:
  205. self._shas.append(sha)
  206. yield sha
  207. def __contains__(self, needle):
  208. """Check if an object is present.
  209. :param needle: SHA1 of the object to check for
  210. """
  211. # FIXME: This could be more efficient
  212. for sha, path in self.itershas():
  213. if sha == needle:
  214. return True
  215. return False
  216. def __getitem__(self, key):
  217. """Find an object by SHA1."""
  218. return self.store[key]
  219. def __len__(self):
  220. """Return the number of objects."""
  221. return len(list(self.itershas()))