fastexport.py 8.5 KB

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