fastexport.py 7.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220
  1. # __init__.py -- Fast export/import functionality
  2. # Copyright (C) 2010 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. from dulwich.index import (
  21. commit_tree,
  22. )
  23. from dulwich.objects import (
  24. Blob,
  25. Commit,
  26. Tag,
  27. )
  28. from fastimport import (
  29. commands,
  30. errors as fastimport_errors,
  31. parser,
  32. processor,
  33. )
  34. import stat
  35. def split_email(text):
  36. (name, email) = text.rsplit(" <", 1)
  37. return (name, email.rstrip(">"))
  38. class GitFastExporter(object):
  39. """Generate a fast-export output stream for Git objects."""
  40. def __init__(self, outf, store):
  41. self.outf = outf
  42. self.store = store
  43. self.markers = {}
  44. self._marker_idx = 0
  45. def print_cmd(self, cmd):
  46. self.outf.write("%r\n" % cmd)
  47. def _allocate_marker(self):
  48. self._marker_idx+=1
  49. return str(self._marker_idx)
  50. def _export_blob(self, blob):
  51. marker = self._allocate_marker()
  52. self.markers[marker] = blob.id
  53. return (commands.BlobCommand(marker, blob.data), marker)
  54. def emit_blob(self, blob):
  55. (cmd, marker) = self._export_blob(blob)
  56. self.print_cmd(cmd)
  57. return marker
  58. def _iter_files(self, base_tree, new_tree):
  59. for (old_path, new_path), (old_mode, new_mode), (old_hexsha, new_hexsha) in \
  60. self.store.tree_changes(base_tree, new_tree):
  61. if new_path is None:
  62. yield commands.FileDeleteCommand(old_path)
  63. continue
  64. if not stat.S_ISDIR(new_mode):
  65. blob = self.store[new_hexsha]
  66. marker = self.emit_blob(blob)
  67. if old_path != new_path and old_path is not None:
  68. yield commands.FileRenameCommand(old_path, new_path)
  69. if old_mode != new_mode or old_hexsha != new_hexsha:
  70. yield commands.FileModifyCommand(new_path, new_mode, marker, None)
  71. def _export_commit(self, commit, ref, base_tree=None):
  72. file_cmds = list(self._iter_files(base_tree, commit.tree))
  73. marker = self._allocate_marker()
  74. if commit.parents:
  75. from_ = commit.parents[0]
  76. merges = commit.parents[1:]
  77. else:
  78. from_ = None
  79. merges = []
  80. author, author_email = split_email(commit.author)
  81. committer, committer_email = split_email(commit.committer)
  82. cmd = commands.CommitCommand(ref, marker,
  83. (author, author_email, commit.author_time, commit.author_timezone),
  84. (committer, committer_email, commit.commit_time, commit.commit_timezone),
  85. commit.message, from_, merges, file_cmds)
  86. return (cmd, marker)
  87. def emit_commit(self, commit, ref, base_tree=None):
  88. cmd, marker = self._export_commit(commit, ref, base_tree)
  89. self.print_cmd(cmd)
  90. return marker
  91. class GitImportProcessor(processor.ImportProcessor):
  92. """An import processor that imports into a Git repository using Dulwich.
  93. """
  94. # FIXME: Batch creation of objects?
  95. def __init__(self, repo, params=None, verbose=False, outf=None):
  96. processor.ImportProcessor.__init__(self, params, verbose)
  97. self.repo = repo
  98. self.last_commit = None
  99. self.markers = {}
  100. self._contents = {}
  101. def import_stream(self, stream):
  102. p = parser.ImportParser(stream)
  103. self.process(p.iter_commands)
  104. return self.markers
  105. def blob_handler(self, cmd):
  106. """Process a BlobCommand."""
  107. blob = Blob.from_string(cmd.data)
  108. self.repo.object_store.add_object(blob)
  109. if cmd.mark:
  110. self.markers[cmd.mark] = blob.id
  111. def checkpoint_handler(self, cmd):
  112. """Process a CheckpointCommand."""
  113. pass
  114. def commit_handler(self, cmd):
  115. """Process a CommitCommand."""
  116. commit = Commit()
  117. if cmd.author is not None:
  118. author = cmd.author
  119. else:
  120. author = cmd.committer
  121. (author_name, author_email, author_timestamp, author_timezone) = author
  122. (committer_name, committer_email, commit_timestamp, commit_timezone) = cmd.committer
  123. commit.author = "%s <%s>" % (author_name, author_email)
  124. commit.author_timezone = author_timezone
  125. commit.author_time = int(author_timestamp)
  126. commit.committer = "%s <%s>" % (committer_name, committer_email)
  127. commit.commit_timezone = commit_timezone
  128. commit.commit_time = int(commit_timestamp)
  129. commit.message = cmd.message
  130. commit.parents = []
  131. if cmd.from_:
  132. self._reset_base(cmd.from_)
  133. for filecmd in cmd.iter_files():
  134. if filecmd.name == "filemodify":
  135. if filecmd.data is not None:
  136. blob = Blob.from_string(filecmd.data)
  137. self.repo.object_store.add(blob)
  138. blob_id = blob.id
  139. else:
  140. assert filecmd.dataref[0] == ":", "non-marker refs not supported yet"
  141. blob_id = self.markers[filecmd.dataref[1:]]
  142. self._contents[filecmd.path] = (filecmd.mode, blob_id)
  143. elif filecmd.name == "filedelete":
  144. del self._contents[filecmd.path]
  145. elif filecmd.name == "filecopy":
  146. self._contents[filecmd.dest_path] = self._contents[filecmd.src_path]
  147. elif filecmd.name == "filerename":
  148. self._contents[filecmd.new_path] = self._contents[filecmd.old_path]
  149. del self._contents[filecmd.old_path]
  150. elif filecmd.name == "filedeleteall":
  151. self._contents = {}
  152. else:
  153. raise Exception("Command %s not supported" % filecmd.name)
  154. commit.tree = commit_tree(self.repo.object_store,
  155. ((path, hexsha, mode) for (path, (mode, hexsha)) in
  156. self._contents.iteritems()))
  157. if self.last_commit is not None:
  158. commit.parents.append(self.last_commit)
  159. commit.parents += cmd.merges
  160. self.repo.object_store.add_object(commit)
  161. self.repo[cmd.ref] = commit.id
  162. self.last_commit = commit.id
  163. if cmd.mark:
  164. self.markers[cmd.mark] = commit.id
  165. def progress_handler(self, cmd):
  166. """Process a ProgressCommand."""
  167. pass
  168. def _reset_base(self, commit_id):
  169. if self.last_commit == commit_id:
  170. return
  171. self.last_commit = commit_id
  172. self._contents = {}
  173. tree_id = self.repo[commit_id].tree
  174. for (path, mode, hexsha) in (
  175. self.repo.object_store.iter_tree_contents(tree_id)):
  176. self._contents[path] = (mode, hexsha)
  177. def reset_handler(self, cmd):
  178. """Process a ResetCommand."""
  179. self._reset_base(cmd.from_)
  180. self.rep.refs[cmd.from_] = cmd.id
  181. def tag_handler(self, cmd):
  182. """Process a TagCommand."""
  183. tag = Tag()
  184. tag.tagger = cmd.tagger
  185. tag.message = cmd.message
  186. tag.name = cmd.tag
  187. self.repo.add_object(tag)
  188. self.repo.refs["refs/tags/" + tag.name] = tag.id
  189. def feature_handler(self, cmd):
  190. """Process a FeatureCommand."""
  191. raise fastimport_errors.UnknownFeature(cmd.feature_name)