fastexport.py 8.7 KB

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