fastexport.py 8.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234
  1. # __init__.py -- Fast export/import functionality
  2. # Copyright (C) 2010-2013 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; version 2
  7. # of the License or (at your option) any later version of
  8. # the License.
  9. #
  10. # This program is distributed in the hope that it will be useful,
  11. # but WITHOUT ANY WARRANTY; without even the implied warranty of
  12. # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  13. # GNU General Public License for more details.
  14. #
  15. # You should have received a copy of the GNU General Public License
  16. # along with this program; if not, write to the Free Software
  17. # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
  18. # MA 02110-1301, USA.
  19. """Fast export/import functionality."""
  20. import sys
  21. from dulwich.index import (
  22. commit_tree,
  23. )
  24. from dulwich.objects import (
  25. Blob,
  26. Commit,
  27. Tag,
  28. )
  29. from fastimport import __version__ as fastimport_version
  30. if fastimport_version <= (0, 9, 5) and sys.version_info[0] == 3 and sys.version_info[1] < 5:
  31. raise ImportError("Older versions of fastimport don't support python3<3.5")
  32. from fastimport import (
  33. commands,
  34. errors as fastimport_errors,
  35. parser,
  36. processor,
  37. )
  38. import stat
  39. def split_email(text):
  40. (name, email) = text.rsplit(b" <", 1)
  41. return (name, email.rstrip(b">"))
  42. class GitFastExporter(object):
  43. """Generate a fast-export output stream for Git objects."""
  44. def __init__(self, outf, store):
  45. self.outf = outf
  46. self.store = store
  47. self.markers = {}
  48. self._marker_idx = 0
  49. def print_cmd(self, cmd):
  50. self.outf.write(getattr(cmd, "__bytes__", cmd.__repr__)() + b"\n")
  51. def _allocate_marker(self):
  52. self._marker_idx+=1
  53. return ("%d" % (self._marker_idx,)).encode('ascii')
  54. def _export_blob(self, blob):
  55. marker = self._allocate_marker()
  56. self.markers[marker] = blob.id
  57. return (commands.BlobCommand(marker, blob.data), marker)
  58. def emit_blob(self, blob):
  59. (cmd, marker) = self._export_blob(blob)
  60. self.print_cmd(cmd)
  61. return marker
  62. def _iter_files(self, base_tree, new_tree):
  63. for ((old_path, new_path), (old_mode, new_mode),
  64. (old_hexsha, new_hexsha)) in \
  65. self.store.tree_changes(base_tree, new_tree):
  66. if new_path is None:
  67. yield commands.FileDeleteCommand(old_path)
  68. continue
  69. if not stat.S_ISDIR(new_mode):
  70. blob = self.store[new_hexsha]
  71. marker = self.emit_blob(blob)
  72. if old_path != new_path and old_path is not None:
  73. yield commands.FileRenameCommand(old_path, new_path)
  74. if old_mode != new_mode or old_hexsha != new_hexsha:
  75. prefixed_marker = b':' + marker
  76. yield commands.FileModifyCommand(
  77. new_path, new_mode, prefixed_marker, None
  78. )
  79. def _export_commit(self, commit, ref, base_tree=None):
  80. file_cmds = list(self._iter_files(base_tree, commit.tree))
  81. marker = self._allocate_marker()
  82. if commit.parents:
  83. from_ = commit.parents[0]
  84. merges = commit.parents[1:]
  85. else:
  86. from_ = None
  87. merges = []
  88. author, author_email = split_email(commit.author)
  89. committer, committer_email = split_email(commit.committer)
  90. cmd = commands.CommitCommand(ref, marker,
  91. (author, author_email, commit.author_time, commit.author_timezone),
  92. (committer, committer_email, commit.commit_time,
  93. commit.commit_timezone),
  94. commit.message, from_, merges, file_cmds)
  95. return (cmd, marker)
  96. def emit_commit(self, commit, ref, base_tree=None):
  97. cmd, marker = self._export_commit(commit, ref, base_tree)
  98. self.print_cmd(cmd)
  99. return marker
  100. class GitImportProcessor(processor.ImportProcessor):
  101. """An import processor that imports into a Git repository using Dulwich.
  102. """
  103. # FIXME: Batch creation of objects?
  104. def __init__(self, repo, params=None, verbose=False, outf=None):
  105. processor.ImportProcessor.__init__(self, params, verbose)
  106. self.repo = repo
  107. self.last_commit = None
  108. self.markers = {}
  109. self._contents = {}
  110. def import_stream(self, stream):
  111. p = parser.ImportParser(stream)
  112. self.process(p.iter_commands)
  113. return self.markers
  114. def blob_handler(self, cmd):
  115. """Process a BlobCommand."""
  116. blob = Blob.from_string(cmd.data)
  117. self.repo.object_store.add_object(blob)
  118. if cmd.mark:
  119. self.markers[cmd.mark] = blob.id
  120. def checkpoint_handler(self, cmd):
  121. """Process a CheckpointCommand."""
  122. pass
  123. def commit_handler(self, cmd):
  124. """Process a CommitCommand."""
  125. commit = Commit()
  126. if cmd.author is not None:
  127. author = cmd.author
  128. else:
  129. author = cmd.committer
  130. (author_name, author_email, author_timestamp, author_timezone) = author
  131. (committer_name, committer_email, commit_timestamp,
  132. commit_timezone) = cmd.committer
  133. commit.author = author_name + b" <" + author_email + b">"
  134. commit.author_timezone = author_timezone
  135. commit.author_time = int(author_timestamp)
  136. commit.committer = committer_name + b" <" + committer_email + b">"
  137. commit.commit_timezone = commit_timezone
  138. commit.commit_time = int(commit_timestamp)
  139. commit.message = cmd.message
  140. commit.parents = []
  141. if cmd.from_:
  142. self._reset_base(cmd.from_)
  143. for filecmd in cmd.iter_files():
  144. if filecmd.name == b"filemodify":
  145. if filecmd.data is not None:
  146. blob = Blob.from_string(filecmd.data)
  147. self.repo.object_store.add(blob)
  148. blob_id = blob.id
  149. else:
  150. assert filecmd.dataref.startswith(b":"), \
  151. "non-marker refs not supported yet (%r)" % filecmd.dataref
  152. blob_id = self.markers[filecmd.dataref[1:]]
  153. self._contents[filecmd.path] = (filecmd.mode, blob_id)
  154. elif filecmd.name == b"filedelete":
  155. del self._contents[filecmd.path]
  156. elif filecmd.name == b"filecopy":
  157. self._contents[filecmd.dest_path] = self._contents[
  158. filecmd.src_path]
  159. elif filecmd.name == b"filerename":
  160. self._contents[filecmd.new_path] = self._contents[
  161. filecmd.old_path]
  162. del self._contents[filecmd.old_path]
  163. elif filecmd.name == b"filedeleteall":
  164. self._contents = {}
  165. else:
  166. raise Exception("Command %s not supported" % filecmd.name)
  167. commit.tree = commit_tree(self.repo.object_store,
  168. ((path, hexsha, mode) for (path, (mode, hexsha)) in
  169. self._contents.items()))
  170. if self.last_commit is not None:
  171. commit.parents.append(self.last_commit)
  172. commit.parents += cmd.merges
  173. self.repo.object_store.add_object(commit)
  174. self.repo[cmd.ref] = commit.id
  175. self.last_commit = commit.id
  176. if cmd.mark:
  177. self.markers[cmd.mark] = commit.id
  178. def progress_handler(self, cmd):
  179. """Process a ProgressCommand."""
  180. pass
  181. def _reset_base(self, commit_id):
  182. if self.last_commit == commit_id:
  183. return
  184. self.last_commit = commit_id
  185. self._contents = {}
  186. tree_id = self.repo[commit_id].tree
  187. for (path, mode, hexsha) in (
  188. self.repo.object_store.iter_tree_contents(tree_id)):
  189. self._contents[path] = (mode, hexsha)
  190. def reset_handler(self, cmd):
  191. """Process a ResetCommand."""
  192. self._reset_base(cmd.from_)
  193. self.repo.refs[cmd.ref] = cmd.from_
  194. def tag_handler(self, cmd):
  195. """Process a TagCommand."""
  196. tag = Tag()
  197. tag.tagger = cmd.tagger
  198. tag.message = cmd.message
  199. tag.name = cmd.tag
  200. self.repo.add_object(tag)
  201. self.repo.refs["refs/tags/" + tag.name] = tag.id
  202. def feature_handler(self, cmd):
  203. """Process a FeatureCommand."""
  204. raise fastimport_errors.UnknownFeature(cmd.feature_name)