fastexport.py 8.5 KB

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