object_store.py 7.9 KB

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