fastexport.py 8.7 KB

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