object_store.py 6.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223
  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. from dulwich.objects import (
  19. hex_to_sha,
  20. ShaFile,
  21. )
  22. from dulwich.pack import (
  23. iter_sha1,
  24. load_packs,
  25. write_pack_index_v2,
  26. PackData,
  27. )
  28. import os
  29. import tempfile
  30. import urllib2
  31. PACKDIR = 'pack'
  32. class ObjectStore(object):
  33. def __init__(self, path):
  34. self.path = path
  35. self._packs = None
  36. def iter_shas(self, shas):
  37. return ObjectStoreIterator(self, shas)
  38. def pack_dir(self):
  39. return os.path.join(self.path, PACKDIR)
  40. def __contains__(self, sha):
  41. # TODO: This can be more efficient
  42. try:
  43. self[sha]
  44. return True
  45. except KeyError:
  46. return False
  47. @property
  48. def packs(self):
  49. """List with pack objects."""
  50. if self._packs is None:
  51. self._packs = list(load_packs(self.pack_dir()))
  52. return self._packs
  53. def _get_shafile_path(self, sha):
  54. dir = sha[:2]
  55. file = sha[2:]
  56. # Check from object dir
  57. return os.path.join(self.path, dir, file)
  58. def _get_shafile(self, sha):
  59. path = self._get_shafile_path(sha)
  60. if os.path.exists(path):
  61. return ShaFile.from_file(path)
  62. return None
  63. def _add_shafile(self, sha, o):
  64. path = self._get_shafile_path(sha)
  65. f = os.path.open(path, 'w')
  66. try:
  67. f.write(o._header())
  68. f.write(o._text)
  69. finally:
  70. f.close()
  71. def get_raw(self, sha):
  72. """Obtain the raw text for an object.
  73. :param sha: Sha for the object.
  74. :return: tuple with object type and object contents.
  75. """
  76. for pack in self.packs:
  77. if sha in pack:
  78. return pack.get_raw(sha, self.get_raw)
  79. # FIXME: Are pack deltas ever against on-disk shafiles ?
  80. ret = self._get_shafile(sha)
  81. if ret is not None:
  82. return ret.as_raw_string()
  83. raise KeyError(sha)
  84. def __getitem__(self, sha):
  85. assert len(sha) == 40, "Incorrect length sha: %s" % str(sha)
  86. ret = self._get_shafile(sha)
  87. if ret is not None:
  88. return ret
  89. # Check from packs
  90. type, uncomp = self.get_raw(sha)
  91. return ShaFile.from_raw_string(type, uncomp)
  92. def add_objects(self, num_objects, objects):
  93. # TODO: If numb_objects is high enough, write a pack?
  94. for sha, o in objects:
  95. self._add_shafile(sha, o)
  96. def move_in_thin_pack(self, path):
  97. """Move a specific file containing a pack into the pack directory.
  98. :note: The file should be on the same file system as the
  99. packs directory.
  100. :param path: Path to the pack file.
  101. """
  102. p = PackData(path)
  103. temppath = os.path.join(self.pack_dir(), sha_to_hex(urllib2.randombytes(20))+".temppack")
  104. write_pack(temppath, p.iterobjects(self.get_raw), len(p))
  105. pack_sha = PackIndex(temppath+".idx").objects_sha1()
  106. os.rename(temppath+".pack",
  107. os.path.join(self.pack_dir(), "pack-%s.pack" % pack_sha))
  108. os.rename(temppath+".idx",
  109. os.path.join(self.pack_dir(), "pack-%s.idx" % pack_sha))
  110. def move_in_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. entries = p.sorted_entries()
  118. basename = os.path.join(self.pack_dir(),
  119. "pack-%s" % iter_sha1(entry[0] for entry in entries))
  120. write_pack_index_v2(basename+".idx", entries, p.calculate_checksum())
  121. os.rename(path, basename + ".pack")
  122. def add_thin_pack(self):
  123. """Add a new thin pack to this object store.
  124. Thin packs are packs that contain deltas with parents that exist
  125. in a different pack.
  126. """
  127. fd, path = tempfile.mkstemp(dir=self.pack_dir(), suffix=".pack")
  128. f = os.fdopen(fd, 'w')
  129. def commit():
  130. if os.path.getsize(path) > 0:
  131. self.move_in_thin_pack(path)
  132. return f, commit
  133. def add_pack(self):
  134. """Add a new pack to this object store.
  135. :return: Fileobject to write to and a commit function to
  136. call when the pack is finished.
  137. """
  138. fd, path = tempfile.mkstemp(dir=self.pack_dir(), suffix=".pack")
  139. f = os.fdopen(fd, 'w')
  140. def commit():
  141. if os.path.getsize(path) > 0:
  142. self.move_in_pack(path)
  143. return f, commit
  144. def add_objects(self, objects):
  145. if len(objects) == 0:
  146. return
  147. f, commit = self.add_pack()
  148. write_pack_data(f, objects, len(objects))
  149. commit()
  150. class ObjectImporter(object):
  151. def __init__(self, count):
  152. self.count = count
  153. def add_object(self, object):
  154. raise NotImplementedError(self.add_object)
  155. def finish(self, object):
  156. raise NotImplementedError(self.finish)
  157. class ObjectIterator(object):
  158. def iterobjects(self):
  159. raise NotImplementedError(self.iterobjects)
  160. class ObjectStoreIterator(ObjectIterator):
  161. def __init__(self, store, shas):
  162. self.store = store
  163. self.shas = shas
  164. def __iter__(self):
  165. return ((self.store[sha], path) for sha, path in self.shas)
  166. def iterobjects(self):
  167. for o, path in self:
  168. yield o
  169. def __contains__(self, needle):
  170. # FIXME: This could be more efficient
  171. for sha, path in self.shas:
  172. if sha == needle:
  173. return True
  174. return False
  175. def __getitem__(self, key):
  176. return self.store[key]
  177. def __len__(self):
  178. return len(self.shas)