fastexport.py 8.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258
  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 (
  62. (old_path, new_path),
  63. (old_mode, new_mode),
  64. (old_hexsha, new_hexsha),
  65. ) in 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(
  91. ref,
  92. marker,
  93. (author, author_email, commit.author_time, commit.author_timezone),
  94. (
  95. committer,
  96. committer_email,
  97. commit.commit_time,
  98. commit.commit_timezone,
  99. ),
  100. commit.message,
  101. from_,
  102. merges,
  103. file_cmds,
  104. )
  105. return (cmd, marker)
  106. def emit_commit(self, commit, ref, base_tree=None):
  107. cmd, marker = self._export_commit(commit, ref, base_tree)
  108. self.print_cmd(cmd)
  109. return marker
  110. class GitImportProcessor(processor.ImportProcessor):
  111. """An import processor that imports into a Git repository using Dulwich."""
  112. # FIXME: Batch creation of objects?
  113. def __init__(self, repo, params=None, verbose=False, outf=None):
  114. processor.ImportProcessor.__init__(self, params, verbose)
  115. self.repo = repo
  116. self.last_commit = ZERO_SHA
  117. self.markers = {}
  118. self._contents = {}
  119. def lookup_object(self, objectish):
  120. if objectish.startswith(b":"):
  121. return self.markers[objectish[1:]]
  122. return objectish
  123. def import_stream(self, stream):
  124. p = parser.ImportParser(stream)
  125. self.process(p.iter_commands)
  126. return self.markers
  127. def blob_handler(self, cmd):
  128. """Process a BlobCommand."""
  129. blob = Blob.from_string(cmd.data)
  130. self.repo.object_store.add_object(blob)
  131. if cmd.mark:
  132. self.markers[cmd.mark] = blob.id
  133. def checkpoint_handler(self, cmd):
  134. """Process a CheckpointCommand."""
  135. pass
  136. def commit_handler(self, cmd):
  137. """Process a CommitCommand."""
  138. commit = Commit()
  139. if cmd.author is not None:
  140. author = cmd.author
  141. else:
  142. author = cmd.committer
  143. (author_name, author_email, author_timestamp, author_timezone) = author
  144. (
  145. committer_name,
  146. committer_email,
  147. commit_timestamp,
  148. commit_timezone,
  149. ) = cmd.committer
  150. commit.author = author_name + b" <" + author_email + b">"
  151. commit.author_timezone = author_timezone
  152. commit.author_time = int(author_timestamp)
  153. commit.committer = committer_name + b" <" + committer_email + b">"
  154. commit.commit_timezone = commit_timezone
  155. commit.commit_time = int(commit_timestamp)
  156. commit.message = cmd.message
  157. commit.parents = []
  158. if cmd.from_:
  159. cmd.from_ = self.lookup_object(cmd.from_)
  160. self._reset_base(cmd.from_)
  161. for filecmd in cmd.iter_files():
  162. if filecmd.name == b"filemodify":
  163. if filecmd.data is not None:
  164. blob = Blob.from_string(filecmd.data)
  165. self.repo.object_store.add(blob)
  166. blob_id = blob.id
  167. else:
  168. blob_id = self.lookup_object(filecmd.dataref)
  169. self._contents[filecmd.path] = (filecmd.mode, blob_id)
  170. elif filecmd.name == b"filedelete":
  171. del self._contents[filecmd.path]
  172. elif filecmd.name == b"filecopy":
  173. self._contents[filecmd.dest_path] = self._contents[filecmd.src_path]
  174. elif filecmd.name == b"filerename":
  175. self._contents[filecmd.new_path] = self._contents[filecmd.old_path]
  176. del self._contents[filecmd.old_path]
  177. elif filecmd.name == b"filedeleteall":
  178. self._contents = {}
  179. else:
  180. raise Exception("Command %s not supported" % filecmd.name)
  181. commit.tree = commit_tree(
  182. self.repo.object_store,
  183. ((path, hexsha, mode) for (path, (mode, hexsha)) in self._contents.items()),
  184. )
  185. if self.last_commit != ZERO_SHA:
  186. commit.parents.append(self.last_commit)
  187. for merge in cmd.merges:
  188. commit.parents.append(self.lookup_object(merge))
  189. self.repo.object_store.add_object(commit)
  190. self.repo[cmd.ref] = commit.id
  191. self.last_commit = commit.id
  192. if cmd.mark:
  193. self.markers[cmd.mark] = commit.id
  194. def progress_handler(self, cmd):
  195. """Process a ProgressCommand."""
  196. pass
  197. def _reset_base(self, commit_id):
  198. if self.last_commit == commit_id:
  199. return
  200. self._contents = {}
  201. self.last_commit = commit_id
  202. if commit_id != ZERO_SHA:
  203. tree_id = self.repo[commit_id].tree
  204. for (
  205. path,
  206. mode,
  207. hexsha,
  208. ) in self.repo.object_store.iter_tree_contents(tree_id):
  209. self._contents[path] = (mode, hexsha)
  210. def reset_handler(self, cmd):
  211. """Process a ResetCommand."""
  212. if cmd.from_ is None:
  213. from_ = ZERO_SHA
  214. else:
  215. from_ = self.lookup_object(cmd.from_)
  216. self._reset_base(from_)
  217. self.repo.refs[cmd.ref] = from_
  218. def tag_handler(self, cmd):
  219. """Process a TagCommand."""
  220. tag = Tag()
  221. tag.tagger = cmd.tagger
  222. tag.message = cmd.message
  223. tag.name = cmd.tag
  224. self.repo.add_object(tag)
  225. self.repo.refs["refs/tags/" + tag.name] = tag.id
  226. def feature_handler(self, cmd):
  227. """Process a FeatureCommand."""
  228. raise fastimport_errors.UnknownFeature(cmd.feature_name)