object_store.py 7.7 KB

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