Debian Codegraph @

hgext/fastexport.py

raw
1 # Copyright 2020 Joerg Sonnenberger <[email protected]>
2 #
3 # This software may be used and distributed according to the terms of the
4 # GNU General Public License version 2 or any later version.
5 """export repositories as git fast-import stream"""
6
7 # The format specification for fast-import streams can be found at
8 # https://git-scm.com/docs/git-fast-import#_input_format
9
10 from __future__ import annotations
11
12 import re
13
14 from mercurial.i18n import _
15 from mercurial.node import hex, nullrev
16 from mercurial.utils import stringutil
17 from mercurial import (
18 error,
19 logcmdutil,
20 registrar,
21 scmutil,
22 )
23 from .convert import convcmd
24
25 # Note for extension authors: ONLY specify testedwith = 'ships-with-hg-core' for
26 # extensions which SHIP WITH MERCURIAL. Non-mainline extensions should
27 # be specifying the version(s) of Mercurial they are tested with, or
28 # leave the attribute unspecified.
29 testedwith = b"ships-with-hg-core"
30
31 cmdtable = {}
32 command = registrar.command(cmdtable)
33
34 configtable = {}
35 configitem = registrar.configitem(configtable)
36 configitem(
37 b'fastexport',
38 b'on-pre-existing-gitmodules',
39 default=b'abort',
40 )
41
42 GIT_PERSON_PROHIBITED = re.compile(b'[<>\n"]')
43 GIT_EMAIL_PROHIBITED = re.compile(b"[<> \n]")
44
45
46 def convert_to_git_user(authormap, user, rev):
47 mapped_user = authormap.get(user, user)
48 user_person = stringutil.person(mapped_user)
49 user_email = stringutil.email(mapped_user)
50 if GIT_EMAIL_PROHIBITED.match(user_email) or GIT_PERSON_PROHIBITED.match(
51 user_person
52 ):
53 raise error.Abort(
54 _(b"Unable to parse user into person and email for revision %s")
55 % rev
56 )
57 if user_person:
58 return b'"%s" <%s>' % (user_person, user_email)
59 else:
60 return b"<%s>" % user_email
61
62
63 def convert_to_git_date(date):
64 timestamp, utcoff = date
65 tzsign = b"+" if utcoff <= 0 else b"-"
66 if utcoff % 60 != 0:
67 raise error.Abort(
68 _(b"UTC offset in %r is not an integer number of minutes") % (date,)
69 )
70 utcoff = abs(utcoff) // 60
71 tzh = utcoff // 60
72 tzmin = utcoff % 60
73 return b"%d " % int(timestamp) + tzsign + b"%02d%02d" % (tzh, tzmin)
74
75
76 def convert_to_git_ref(branch):
77 # XXX filter/map depending on git restrictions
78 return b"refs/heads/" + branch
79
80
81 def write_data(buf, data, add_newline=False):
82 buf.append(b"data %d\n" % len(data))
83 buf.append(data)
84 if add_newline or data[-1:] != b"\n":
85 buf.append(b"\n")
86
87
88 def export_commit(
89 ui, repo, rev, marks, authormap, emitted_unsupported_kind_warnings
90 ):
91 ctx = repo[rev]
92 revid = ctx.hex()
93 if revid in marks:
94 ui.debug(b"warning: revision %s already exported, skipped\n" % revid)
95 return
96 parents = [p for p in ctx.parents() if p.rev() != nullrev]
97 for p in parents:
98 if p.hex() not in marks:
99 ui.warn(
100 _(b"warning: parent %s of %s has not been exported, skipped\n")
101 % (p, revid)
102 )
103 return
104
105 # For all files modified by the commit, check if they have already
106 # been exported and otherwise dump the blob with the new mark.
107 for fname in ctx.files():
108 if fname not in ctx or fname == b'.gitmodules':
109 continue
110 filectx = ctx.filectx(fname)
111 filerev = hex(filectx.filenode())
112 if filerev not in marks:
113 mark = len(marks) + 1
114 marks[filerev] = mark
115 data = filectx.data()
116 buf = [b"blob\n", b"mark :%d\n" % mark]
117 write_data(buf, data, True)
118 ui.write(*buf, keepprogressbar=True)
119 del buf
120
121 # Assign a mark for the current revision for references by
122 # latter merge commits.
123 mark = len(marks) + 1
124 marks[revid] = mark
125
126 ref = convert_to_git_ref(ctx.branch())
127 buf = [
128 b"commit %s\n" % ref,
129 b"mark :%d\n" % mark,
130 b"committer %s %s\n"
131 % (
132 convert_to_git_user(authormap, ctx.user(), revid),
133 convert_to_git_date(ctx.date()),
134 ),
135 ]
136 write_data(buf, ctx.description())
137 if parents:
138 buf.append(b"from :%d\n" % marks[parents[0].hex()])
139 if len(parents) == 2:
140 buf.append(b"merge :%d\n" % marks[parents[1].hex()])
141 p0ctx = repo[parents[0]]
142 files = ctx.manifest().diff(p0ctx.manifest())
143 else:
144 files = ctx.files()
145 filebuf = []
146 subrepos_changed = False
147 for fname in files:
148 if fname == b'.gitmodules':
149 existing_gitmodules_behavior = ui.config(
150 b'fastexport', b'on-pre-existing-gitmodules'
151 )
152 if existing_gitmodules_behavior == b'abort':
153 msg = _(b".gitmodules already present in source repository")
154 hint = _(
155 b"to ignore this error, set config "
156 b"fastexport.on-pre-existing-gitmodules=ignore"
157 )
158 raise error.Abort(msg, hint=hint)
159 elif existing_gitmodules_behavior == b'ignore':
160 msg = _(
161 b"warning: ignoring change of .gitmodules in revision "
162 b"%s\n"
163 )
164 msg %= revid
165 ui.warn(msg)
166 ui.warn(_(b"instead, .gitmodules is generated from .hgsub)\n"))
167 continue
168 else:
169 msg = _(b"fastexport.on-pre-existing-gitmodules not valid")
170 hint = _(b"should be 'abort' or 'ignore', but is '%s'")
171 hint %= existing_gitmodules_behavior
172 raise error.ConfigError(msg, hint=hint)
173 elif fname not in ctx:
174 filebuf.append((fname, b"D %s\n" % fname))
175 else:
176 filectx = ctx.filectx(fname)
177 filerev = filectx.filenode()
178 if filectx.isexec():
179 fileperm = b"755"
180 elif filectx.islink():
181 fileperm = b"120000"
182 else:
183 fileperm = b"644"
184 changed = b"M %s :%d %s\n" % (fileperm, marks[hex(filerev)], fname)
185 filebuf.append((fname, changed))
186 if fname in (b".hgsub", b".hgsubstate"):
187 subrepos_changed = True
188
189 if subrepos_changed:
190 psubstate = ctx.p1().substate
191 substate = ctx.substate
192
193 # Create .gitmodules.
194 pgitmodules = [
195 (path, source)
196 for path, (source, rev, kind) in psubstate.items()
197 if kind == b"git"
198 ]
199 gitmodules = [
200 (path, source)
201 for path, (source, rev, kind) in substate.items()
202 if kind == b"git"
203 ]
204 if gitmodules == pgitmodules:
205 pass
206 elif not gitmodules:
207 filebuf.append((b".gitmodules", b"D .gitmodules\n"))
208 else:
209 gitmodules_file = b"".join(
210 b'[submodule "%s"]\n\tpath = %s\n\turl = %s\n'
211 % (path, path, source)
212 for path, source in gitmodules
213 )
214 gitmodules_buf = [b"M 644 inline .gitmodules\n"]
215 write_data(gitmodules_buf, gitmodules_file, True)
216 filebuf.append((b".gitmodules", b"".join(gitmodules_buf)))
217
218 # Handle deleted subrepositories.
219 for path in psubstate.keys() - substate.keys():
220 kind = psubstate[path][2]
221 if kind == b"git":
222 filebuf.append((path, b"D %s\n" % path))
223
224 # Handle added or changed subrepositories.
225 for path, (source, rev, kind) in substate.items() - psubstate.items():
226 if kind == b"git":
227 filebuf.append((path, b"M 160000 %s %s\n" % (rev, path)))
228 elif kind not in emitted_unsupported_kind_warnings:
229 emitted_unsupported_kind_warnings.add(kind)
230 ui.warn(
231 _(
232 b"warning: subrepositories of kind %s are not supported\n"
233 )
234 % (kind)
235 )
236
237 filebuf.sort()
238 buf.extend(changed for (fname, changed) in filebuf)
239 del filebuf
240 buf.append(b"\n")
241 ui.write(*buf, keepprogressbar=True)
242 del buf
243
244
245 isrev = re.compile(b"^[0-9a-f]{40}$")
246
247
248 @command(
249 b"fastexport",
250 [
251 (b"r", b"rev", [], _(b"revisions to export"), _(b"REV")),
252 (b"i", b"import-marks", b"", _(b"old marks file to read"), _(b"FILE")),
253 (b"e", b"export-marks", b"", _(b"new marks file to write"), _(b"FILE")),
254 (
255 b"A",
256 b"authormap",
257 b"",
258 _(b"remap usernames using this file"),
259 _(b"FILE"),
260 ),
261 ],
262 _(b"[OPTION]... [REV]..."),
263 helpcategory=command.CATEGORY_IMPORT_EXPORT,
264 )
265 def fastexport(ui, repo, *revs, **opts):
266 """export repository as git fast-import stream
267
268 This command lets you dump a repository as a human-readable text stream.
269 It can be piped into corresponding import routines like "git fast-import".
270 Incremental dumps can be created by using marks files.
271 """
272 revs += tuple(opts.get("rev", []))
273 if not revs:
274 revs = scmutil.revrange(repo, [b"all()"])
275 else:
276 revs = logcmdutil.revrange(repo, revs)
277 if not revs:
278 raise error.Abort(_(b"no revisions matched"))
279 authorfile = opts.get("authormap")
280 if authorfile:
281 authormap = convcmd.readauthormap(ui, authorfile)
282 else:
283 authormap = {}
284
285 import_marks = opts.get("import_marks")
286 marks = {}
287 if import_marks:
288 with open(import_marks, "rb") as import_marks_file:
289 for line in import_marks_file:
290 line = line.strip()
291 if not isrev.match(line) or line in marks:
292 raise error.Abort(_(b"Corrupted marks file"))
293 marks[line] = len(marks) + 1
294
295 revs.sort()
296 emitted_unsupported_kind_warnings = set()
297 with ui.makeprogress(
298 _(b"exporting"), unit=_(b"revisions"), total=len(revs)
299 ) as progress:
300 for rev in revs:
301 export_commit(
302 ui,
303 repo,
304 rev,
305 marks,
306 authormap,
307 emitted_unsupported_kind_warnings,
308 )
309 progress.increment()
310
311 export_marks = opts.get("export_marks")
312 if export_marks:
313 with open(export_marks, "wb") as export_marks_file:
314 output_marks = [None] * len(marks)
315 for k, v in marks.items():
316 output_marks[v - 1] = k
317 for k in output_marks:
318 export_marks_file.write(k + b"\n")