2
0

fastexport.py 8.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243
  1. # __init__.py -- Fast export/import functionality
  2. # Copyright (C) 2010-2013 Jelmer Vernooij <jelmer@jelmer.uk>
  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. from dulwich.index import (
  22. commit_tree,
  23. )
  24. from dulwich.objects import (
  25. Blob,
  26. Commit,
  27. Tag,
  28. ZERO_SHA,
  29. )
  30. from fastimport import ( # noqa: E402
  31. commands,
  32. errors as fastimport_errors,
  33. parser,
  34. processor,
  35. )
  36. import stat # noqa: E402
  37. def split_email(text):
  38. (name, email) = text.rsplit(b" <", 1)
  39. return (name, email.rstrip(b">"))
  40. class GitFastExporter(object):
  41. """Generate a fast-export output stream for Git objects."""
  42. def __init__(self, outf, store):
  43. self.outf = outf
  44. self.store = store
  45. self.markers = {}
  46. self._marker_idx = 0
  47. def print_cmd(self, cmd):
  48. self.outf.write(getattr(cmd, "__bytes__", cmd.__repr__)() + b"\n")
  49. def _allocate_marker(self):
  50. self._marker_idx += 1
  51. return ("%d" % (self._marker_idx,)).encode('ascii')
  52. def _export_blob(self, blob):
  53. marker = self._allocate_marker()
  54. self.markers[marker] = blob.id
  55. return (commands.BlobCommand(marker, blob.data), marker)
  56. def emit_blob(self, blob):
  57. (cmd, marker) = self._export_blob(blob)
  58. self.print_cmd(cmd)
  59. return marker
  60. def _iter_files(self, base_tree, new_tree):
  61. for ((old_path, new_path), (old_mode, new_mode),
  62. (old_hexsha, new_hexsha)) in \
  63. self.store.tree_changes(base_tree, new_tree):
  64. if new_path is None:
  65. yield commands.FileDeleteCommand(old_path)
  66. continue
  67. if not stat.S_ISDIR(new_mode):
  68. blob = self.store[new_hexsha]
  69. marker = self.emit_blob(blob)
  70. if old_path != new_path and old_path is not None:
  71. yield commands.FileRenameCommand(old_path, new_path)
  72. if old_mode != new_mode or old_hexsha != new_hexsha:
  73. prefixed_marker = b':' + marker
  74. yield commands.FileModifyCommand(
  75. new_path, new_mode, prefixed_marker, None
  76. )
  77. def _export_commit(self, commit, ref, base_tree=None):
  78. file_cmds = list(self._iter_files(base_tree, commit.tree))
  79. marker = self._allocate_marker()
  80. if commit.parents:
  81. from_ = commit.parents[0]
  82. merges = commit.parents[1:]
  83. else:
  84. from_ = None
  85. merges = []
  86. author, author_email = split_email(commit.author)
  87. committer, committer_email = split_email(commit.committer)
  88. cmd = commands.CommitCommand(
  89. ref, marker,
  90. (author, author_email, commit.author_time, commit.author_timezone),
  91. (committer, committer_email, commit.commit_time,
  92. commit.commit_timezone),
  93. commit.message, from_, merges, file_cmds)
  94. return (cmd, marker)
  95. def emit_commit(self, commit, ref, base_tree=None):
  96. cmd, marker = self._export_commit(commit, ref, base_tree)
  97. self.print_cmd(cmd)
  98. return marker
  99. class GitImportProcessor(processor.ImportProcessor):
  100. """An import processor that imports into a Git repository using Dulwich.
  101. """
  102. # FIXME: Batch creation of objects?
  103. def __init__(self, repo, params=None, verbose=False, outf=None):
  104. processor.ImportProcessor.__init__(self, params, verbose)
  105. self.repo = repo
  106. self.last_commit = ZERO_SHA
  107. self.markers = {}
  108. self._contents = {}
  109. def lookup_object(self, objectish):
  110. if objectish.startswith(b":"):
  111. return self.markers[objectish[1:]]
  112. return objectish
  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. cmd.from_ = self.lookup_object(cmd.from_)
  146. self._reset_base(cmd.from_)
  147. for filecmd in cmd.iter_files():
  148. if filecmd.name == b"filemodify":
  149. if filecmd.data is not None:
  150. blob = Blob.from_string(filecmd.data)
  151. self.repo.object_store.add(blob)
  152. blob_id = blob.id
  153. else:
  154. blob_id = self.lookup_object(filecmd.dataref)
  155. self._contents[filecmd.path] = (filecmd.mode, blob_id)
  156. elif filecmd.name == b"filedelete":
  157. del self._contents[filecmd.path]
  158. elif filecmd.name == b"filecopy":
  159. self._contents[filecmd.dest_path] = self._contents[
  160. filecmd.src_path]
  161. elif filecmd.name == b"filerename":
  162. self._contents[filecmd.new_path] = self._contents[
  163. filecmd.old_path]
  164. del self._contents[filecmd.old_path]
  165. elif filecmd.name == b"filedeleteall":
  166. self._contents = {}
  167. else:
  168. raise Exception("Command %s not supported" % filecmd.name)
  169. commit.tree = commit_tree(
  170. self.repo.object_store,
  171. ((path, hexsha, mode) for (path, (mode, hexsha)) in
  172. self._contents.items()))
  173. if self.last_commit != ZERO_SHA:
  174. commit.parents.append(self.last_commit)
  175. for merge in cmd.merges:
  176. commit.parents.append(self.lookup_object(merge))
  177. self.repo.object_store.add_object(commit)
  178. self.repo[cmd.ref] = commit.id
  179. self.last_commit = commit.id
  180. if cmd.mark:
  181. self.markers[cmd.mark] = commit.id
  182. def progress_handler(self, cmd):
  183. """Process a ProgressCommand."""
  184. pass
  185. def _reset_base(self, commit_id):
  186. if self.last_commit == commit_id:
  187. return
  188. self._contents = {}
  189. self.last_commit = commit_id
  190. if commit_id != ZERO_SHA:
  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. if cmd.from_ is None:
  198. from_ = ZERO_SHA
  199. else:
  200. from_ = self.lookup_object(cmd.from_)
  201. self._reset_base(from_)
  202. self.repo.refs[cmd.ref] = from_
  203. def tag_handler(self, cmd):
  204. """Process a TagCommand."""
  205. tag = Tag()
  206. tag.tagger = cmd.tagger
  207. tag.message = cmd.message
  208. tag.name = cmd.tag
  209. self.repo.add_object(tag)
  210. self.repo.refs["refs/tags/" + tag.name] = tag.id
  211. def feature_handler(self, cmd):
  212. """Process a FeatureCommand."""
  213. raise fastimport_errors.UnknownFeature(cmd.feature_name)