Debian Codegraph @

hgext/convert/hg.py

raw
1 # hg.py - hg backend for convert extension
2 #
3 # Copyright 2005-2009 Olivia Mackall <[email protected]> and others
4 #
5 # This software may be used and distributed according to the terms of the
6 # GNU General Public License version 2 or any later version.
7
8 # Notes for hg->hg conversion:
9 #
10 # * Old versions of Mercurial didn't trim the whitespace from the ends
11 # of commit messages, but new versions do. Changesets created by
12 # those older versions, then converted, may thus have different
13 # hashes for changesets that are otherwise identical.
14 #
15 # * Using "--config convert.hg.saverev=true" will make the source
16 # identifier to be stored in the converted revision. This will cause
17 # the converted revision to have a different identity than the
18 # source.
19
20 from __future__ import annotations
21
22 import os
23 import re
24 import time
25
26 from mercurial.i18n import _
27 from mercurial.interfaces.types import (
28 RepoT,
29 )
30 from mercurial.node import (
31 bin,
32 hex,
33 sha1nodeconstants,
34 )
35 from mercurial import (
36 bookmarks,
37 context,
38 error,
39 exchange,
40 lock as lockmod,
41 logcmdutil,
42 merge as mergemod,
43 mergestate,
44 phases,
45 util,
46 )
47 from mercurial.repo import factory as repo_factory
48 from mercurial.utils import dateutil
49
50 stringio = util.stringio
51
52 from . import common
53
54 mapfile = common.mapfile
55 NoRepo = common.NoRepo
56
57 sha1re = re.compile(br'\b[0-9a-f]{12,40}\b')
58
59
60 class mercurial_sink(common.converter_sink):
61 def __init__(self, ui, repotype, path):
62 common.converter_sink.__init__(self, ui, repotype, path)
63 self.branchnames = ui.configbool(b'convert', b'hg.usebranchnames')
64 self.clonebranches = ui.configbool(b'convert', b'hg.clonebranches')
65 self.tagsbranch = ui.config(b'convert', b'hg.tagsbranch')
66 self.lastbranch = None
67 if os.path.isdir(path) and len(os.listdir(path)) > 0:
68 try:
69 self.repo = repo_factory.repository(self.ui, path)
70 if not self.repo.local():
71 raise NoRepo(
72 _(b'%s is not a local Mercurial repository') % path
73 )
74 except error.RepoError as err:
75 ui.traceback()
76 raise NoRepo(err.args[0])
77 else:
78 try:
79 ui.status(_(b'initializing destination %s repository\n') % path)
80 self.repo = repo_factory.repository(self.ui, path, create=True)
81 if not self.repo.local():
82 raise NoRepo(
83 _(b'%s is not a local Mercurial repository') % path
84 )
85 self.created.append(path)
86 except error.RepoError:
87 ui.traceback()
88 raise NoRepo(
89 _(b"could not create hg repository %s as sink") % path
90 )
91 self.lock = None
92 self.wlock = None
93 self.filemapmode = False
94 self.subrevmaps = {}
95
96 def before(self):
97 self.ui.debug(b'run hg sink pre-conversion action\n')
98 self.wlock = self.repo.wlock()
99 self.lock = self.repo.lock()
100
101 def after(self):
102 self.ui.debug(b'run hg sink post-conversion action\n')
103 if self.lock:
104 self.lock.release()
105 if self.wlock:
106 self.wlock.release()
107
108 def revmapfile(self):
109 return self.repo.vfs.join(b"shamap")
110
111 def authorfile(self):
112 return self.repo.vfs.join(b"authormap")
113
114 def setbranch(self, branch, pbranches):
115 if not self.clonebranches:
116 return
117
118 setbranch = branch != self.lastbranch
119 self.lastbranch = branch
120 if not branch:
121 branch = b'default'
122 pbranches = [(b[0], b[1] and b[1] or b'default') for b in pbranches]
123
124 branchpath = os.path.join(self.path, branch)
125 if setbranch:
126 self.after()
127 try:
128 self.repo = repo_factory.repository(self.ui, branchpath)
129 except Exception:
130 self.repo = repo_factory.repository(
131 self.ui,
132 branchpath,
133 create=True,
134 )
135 self.before()
136
137 # pbranches may bring revisions from other branches (merge parents)
138 # Make sure we have them, or pull them.
139 missings = {}
140 for b in pbranches:
141 try:
142 self.repo.lookup(b[0])
143 except Exception:
144 missings.setdefault(b[1], []).append(b[0])
145
146 if missings:
147 self.after()
148 for pbranch, heads in sorted(missings.items()):
149 pbranchpath = os.path.join(self.path, pbranch)
150 prepo = repo_factory.peer(self.ui, {}, pbranchpath)
151 self.ui.note(
152 _(b'pulling from %s into %s\n') % (pbranch, branch)
153 )
154 exchange.pull(
155 self.repo, prepo, heads=[prepo.lookup(h) for h in heads]
156 )
157 self.before()
158
159 def _rewritetags(self, source, revmap, data):
160 fp = stringio()
161 for line in data.splitlines():
162 s = line.split(b' ', 1)
163 if len(s) != 2:
164 self.ui.warn(_(b'invalid tag entry: "%s"\n') % line)
165 fp.write(b'%s\n' % line) # Bogus, but keep for hash stability
166 continue
167 revid = revmap.get(source.lookuprev(s[0]))
168 if not revid:
169 if s[0] == sha1nodeconstants.nullhex:
170 revid = s[0]
171 else:
172 # missing, but keep for hash stability
173 self.ui.warn(_(b'missing tag entry: "%s"\n') % line)
174 fp.write(b'%s\n' % line)
175 continue
176 fp.write(b'%s %s\n' % (revid, s[1]))
177 return fp.getvalue()
178
179 def _rewritesubstate(self, source, data):
180 fp = stringio()
181 for line in data.splitlines():
182 s = line.split(b' ', 1)
183 if len(s) != 2:
184 continue
185
186 revid = s[0]
187 subpath = s[1]
188 if revid != sha1nodeconstants.nullhex:
189 revmap = self.subrevmaps.get(subpath)
190 if revmap is None:
191 revmap = mapfile(
192 self.ui, self.repo.wjoin(subpath, b'.hg/shamap')
193 )
194 self.subrevmaps[subpath] = revmap
195
196 # It is reasonable that one or more of the subrepos don't
197 # need to be converted, in which case they can be cloned
198 # into place instead of converted. Therefore, only warn
199 # once.
200 msg = _(b'no ".hgsubstate" updates will be made for "%s"\n')
201 if len(revmap) == 0:
202 sub = self.repo.wvfs.reljoin(subpath, b'.hg')
203
204 if self.repo.wvfs.exists(sub):
205 self.ui.warn(msg % subpath)
206
207 newid = revmap.get(revid)
208 if not newid:
209 if len(revmap) > 0:
210 self.ui.warn(
211 _(b"%s is missing from %s/.hg/shamap\n")
212 % (revid, subpath)
213 )
214 else:
215 revid = newid
216
217 fp.write(b'%s %s\n' % (revid, subpath))
218
219 return fp.getvalue()
220
221 def _calculatemergedfiles(self, source, p1ctx, p2ctx):
222 """Calculates the files from p2 that we need to pull in when merging p1
223 and p2, given that the merge is coming from the given source.
224
225 This prevents us from losing files that only exist in the target p2 and
226 that don't come from the source repo (like if you're merging multiple
227 repositories together).
228 """
229 anc = [p1ctx.ancestor(p2ctx)]
230 # Calculate what files are coming from p2
231 # TODO: mresult.commitinfo might be able to get that info
232 mresult = mergemod.calculateupdates(
233 self.repo,
234 p1ctx,
235 p2ctx,
236 anc,
237 branchmerge=True,
238 force=True,
239 acceptremote=False,
240 followcopies=False,
241 )
242
243 for file, (action, info, msg) in mresult.filemap():
244 if source.targetfilebelongstosource(file):
245 # If the file belongs to the source repo, ignore the p2
246 # since it will be covered by the existing fileset.
247 continue
248
249 # If the file requires actual merging, abort. We don't have enough
250 # context to resolve merges correctly.
251 if action in mergestate.CONVERT_MERGE_ACTIONS:
252 raise error.Abort(
253 _(
254 b"unable to convert merge commit "
255 b"since target parents do not merge cleanly (file "
256 b"%s, parents %s and %s)"
257 )
258 % (file, p1ctx, p2ctx)
259 )
260 elif action == mergestate.ACTION_KEEP:
261 # 'keep' means nothing changed from p1
262 continue
263 else:
264 # Any other change means we want to take the p2 version
265 yield file
266
267 def putcommit(
268 self, files, copies, parents, commit, source, revmap, full, cleanp2
269 ):
270 files = dict(files)
271
272 def getfilectx(repo, memctx, f):
273 if p2ctx and f in p2files and f not in copies:
274 self.ui.debug(b'reusing %s from p2\n' % f)
275 try:
276 return p2ctx[f]
277 except error.ManifestLookupError:
278 # If the file doesn't exist in p2, then we're syncing a
279 # delete, so just return None.
280 return None
281 try:
282 v = files[f]
283 except KeyError:
284 return None
285 data, mode = source.getfile(f, v)
286 if data is None:
287 return None
288 if f == b'.hgtags':
289 data = self._rewritetags(source, revmap, data)
290 if f == b'.hgsubstate':
291 data = self._rewritesubstate(source, data)
292 return context.memfilectx(
293 self.repo,
294 memctx,
295 f,
296 data,
297 b'l' in mode,
298 b'x' in mode,
299 copies.get(f),
300 )
301
302 pl = []
303 for p in parents:
304 if p not in pl:
305 pl.append(p)
306 parents = pl
307 nparents = len(parents)
308 if self.filemapmode and nparents == 1:
309 parent = parents[0]
310 p1_node = bin(parent)
311 m1node = self.repo.changelog.changelogrevision(p1_node).manifest
312
313 if len(parents) < 2:
314 parents.append(self.repo.nullid)
315 if len(parents) < 2:
316 parents.append(self.repo.nullid)
317 p2 = parents.pop(0)
318
319 text = commit.desc
320
321 sha1s = re.findall(sha1re, text)
322 for sha1 in sha1s:
323 oldrev = source.lookuprev(sha1)
324 newrev = revmap.get(oldrev)
325 if newrev is not None:
326 text = text.replace(sha1, newrev[: len(sha1)])
327
328 extra = commit.extra.copy()
329
330 sourcename = self.repo.ui.config(b'convert', b'hg.sourcename')
331 if sourcename:
332 extra[b'convert_source'] = sourcename
333
334 for label in (
335 b'source',
336 b'transplant_source',
337 b'rebase_source',
338 b'intermediate-source',
339 ):
340 node = extra.get(label)
341
342 if node is None:
343 continue
344
345 # Only transplant stores its reference in binary
346 if label == b'transplant_source':
347 node = hex(node)
348
349 newrev = revmap.get(node)
350 if newrev is not None:
351 if label == b'transplant_source':
352 newrev = bin(newrev)
353
354 extra[label] = newrev
355
356 if self.branchnames and commit.branch:
357 extra[b'branch'] = commit.branch
358 if commit.rev and commit.saverev:
359 extra[b'convert_revision'] = commit.rev
360
361 while parents:
362 p1 = p2
363 p2 = parents.pop(0)
364 p1ctx = self.repo[p1]
365 p2ctx = None
366 if p2 != self.repo.nullid:
367 p2ctx = self.repo[p2]
368 fileset = set(files)
369 if full:
370 fileset.update(self.repo[p1])
371 fileset.update(self.repo[p2])
372
373 if p2ctx:
374 p2files = set(cleanp2)
375 for file in self._calculatemergedfiles(source, p1ctx, p2ctx):
376 p2files.add(file)
377 fileset.add(file)
378
379 ctx = context.memctx(
380 self.repo,
381 (p1, p2),
382 text,
383 fileset,
384 getfilectx,
385 commit.author,
386 commit.date,
387 extra,
388 )
389
390 # We won't know if the conversion changes the node until after the
391 # commit, so copy the source's phase for now.
392 self.repo.ui.setconfig(
393 b'phases',
394 b'new-commit',
395 phases.phasenames[commit.phase],
396 b'convert',
397 )
398
399 with self.repo.transaction(b"convert") as tr:
400 if self.repo.ui.config(b'convert', b'hg.preserve-hash'):
401 origctx = commit.ctx
402 else:
403 origctx = None
404 node = hex(self.repo.commitctx(ctx, origctx=origctx))
405
406 # If the node value has changed, but the phase is lower than
407 # draft, set it back to draft since it hasn't been exposed
408 # anywhere.
409 if commit.rev != node:
410 ctx = self.repo[node]
411 if ctx.phase() < phases.draft:
412 phases.registernew(
413 self.repo, tr, phases.draft, [ctx.rev()]
414 )
415
416 text = b"(octopus merge fixup)\n"
417 p2 = node
418
419 if self.filemapmode and nparents == 1:
420 man = self.repo.manifestlog.getstorage(b'')
421 mnode = self.repo.changelog.read(bin(p2))[0]
422 closed = b'close' in commit.extra
423 if not closed and not man.cmp(m1node, man.revision(mnode)):
424 self.ui.status(_(b"filtering out empty revision\n"))
425 self.repo.rollback(force=True)
426 return parent
427 return p2
428
429 def puttags(self, tags):
430 tagparent = self.repo.branchtip(self.tagsbranch, ignoremissing=True)
431 tagparent = tagparent or self.repo.nullid
432
433 oldlines = set()
434 bm = self.repo.branchmap()
435 for branch in bm:
436 for h in bm.branchheads(branch, closed=True):
437 if b'.hgtags' in self.repo[h]:
438 oldlines.update(
439 set(self.repo[h][b'.hgtags'].data().splitlines(True))
440 )
441 oldlines = sorted(list(oldlines))
442
443 newlines = sorted([(b"%s %s\n" % (tags[tag], tag)) for tag in tags])
444 if newlines == oldlines:
445 return None, None
446
447 # if the old and new tags match, then there is nothing to update
448 oldtags = set()
449 newtags = set()
450 for line in oldlines:
451 s = line.strip().split(b' ', 1)
452 if len(s) != 2:
453 continue
454 oldtags.add(s[1])
455 for line in newlines:
456 s = line.strip().split(b' ', 1)
457 if len(s) != 2:
458 continue
459 if s[1] not in oldtags:
460 newtags.add(s[1].strip())
461
462 if not newtags:
463 return None, None
464
465 data = b"".join(newlines)
466
467 def getfilectx(repo, memctx, f):
468 return context.memfilectx(repo, memctx, f, data, False, False, None)
469
470 self.ui.status(_(b"updating tags\n"))
471 date = b"%d 0" % int(time.mktime(time.gmtime()))
472 extra = {b'branch': self.tagsbranch}
473 ctx = context.memctx(
474 self.repo,
475 (tagparent, None),
476 b"update tags",
477 [b".hgtags"],
478 getfilectx,
479 b"convert-repo",
480 date,
481 extra,
482 )
483 node = self.repo.commitctx(ctx)
484 return hex(node), hex(tagparent)
485
486 def setfilemapmode(self, active):
487 self.filemapmode = active
488
489 def putbookmarks(self, updatedbookmark):
490 if not len(updatedbookmark):
491 return
492 wlock = lock = tr = None
493 try:
494 wlock = self.repo.wlock()
495 lock = self.repo.lock()
496 tr = self.repo.transaction(b'bookmark')
497 self.ui.status(_(b"updating bookmarks\n"))
498 destmarks = self.repo._bookmarks
499 changes = [
500 (bookmark, bin(updatedbookmark[bookmark]))
501 for bookmark in updatedbookmark
502 ]
503 destmarks.applychanges(self.repo, tr, changes)
504 tr.close()
505 finally:
506 lockmod.release(lock, wlock, tr)
507
508 def hascommitfrommap(self, rev):
509 # the exact semantics of clonebranches is unclear so we can't say no
510 return rev in self.repo or self.clonebranches
511
512 def hascommitforsplicemap(self, rev):
513 if rev not in self.repo and self.clonebranches:
514 raise error.Abort(
515 _(
516 b'revision %s not found in destination '
517 b'repository (lookups with clonebranches=true '
518 b'are not implemented)'
519 )
520 % rev
521 )
522 return rev in self.repo
523
524
525 class mercurial_source(common.converter_source):
526 def __init__(self, ui, repotype, path, revs=None):
527 common.converter_source.__init__(self, ui, repotype, path, revs)
528 self.ignoreerrors = ui.configbool(b'convert', b'hg.ignoreerrors')
529 self.ignored = set()
530 self.saverev = ui.configbool(b'convert', b'hg.saverev')
531 try:
532 self.repo: RepoT = repo_factory.repository(self.ui, path)
533 # try to provoke an exception if this isn't really a hg
534 # repo, but some other bogus compatible-looking url
535 if not self.repo.local():
536 raise error.RepoError
537 except error.RepoError:
538 ui.traceback()
539 raise NoRepo(_(b"%s is not a local Mercurial repository") % path)
540 self.lastrev = None
541 self.lastctx = None
542 self._changescache = None, None
543 self.convertfp = None
544 # Restrict converted revisions to startrev descendants
545 startnode = ui.config(b'convert', b'hg.startrev')
546 hgrevs = ui.config(b'convert', b'hg.revs')
547 if hgrevs is None:
548 if startnode is not None:
549 try:
550 startnode = self.repo.lookup(startnode)
551 except error.RepoError:
552 raise error.Abort(
553 _(b'%s is not a valid start revision') % startnode
554 )
555 startrev = self.repo.changelog.rev(startnode)
556 children = {startnode: 1}
557 for r in self.repo.changelog.descendants([startrev]):
558 children[self.repo.changelog.node(r)] = 1
559 self.keep = children.__contains__
560 else:
561 self.keep = util.always
562 if revs:
563 self._heads = [self.repo.lookup(r) for r in revs]
564 else:
565 self._heads = self.repo.heads()
566 else:
567 if revs or startnode is not None:
568 raise error.Abort(
569 _(
570 b'hg.revs cannot be combined with '
571 b'hg.startrev or --rev'
572 )
573 )
574 nodes = set()
575 parents = set()
576 for r in logcmdutil.revrange(self.repo, [hgrevs]):
577 ctx = self.repo[r]
578 nodes.add(ctx.node())
579 parents.update(p.node() for p in ctx.parents())
580 self.keep = nodes.__contains__
581 self._heads = nodes - parents
582
583 def _changectx(self, rev):
584 if self.lastrev != rev:
585 self.lastctx = self.repo[rev]
586 self.lastrev = rev
587 return self.lastctx
588
589 def _parents(self, ctx):
590 return [p for p in ctx.parents() if p and self.keep(p.node())]
591
592 def getheads(self):
593 return [hex(h) for h in self._heads if self.keep(h)]
594
595 def getfile(self, name, rev):
596 try:
597 fctx = self._changectx(rev)[name]
598 return fctx.data(), fctx.flags()
599 except error.LookupError:
600 return None, None
601
602 def _changedfiles(self, ctx1, ctx2):
603 ma, r = [], []
604 maappend = ma.append
605 rappend = r.append
606 d = ctx1.manifest().diff(ctx2.manifest())
607 for f, ((node1, flag1), (node2, flag2)) in d.items():
608 if node2 is None:
609 rappend(f)
610 else:
611 maappend(f)
612 return ma, r
613
614 def getchanges(self, rev, full):
615 ctx = self._changectx(rev)
616 parents = self._parents(ctx)
617 if full or not parents:
618 files = copyfiles = ctx.manifest()
619 if parents:
620 if self._changescache[0] == rev:
621 # TODO: add type hints to avoid this warning, instead of
622 # suppressing it:
623 # No attribute '__iter__' on None [attribute-error]
624 ma, r = self._changescache[1] # pytype: disable=attribute-error
625 else:
626 ma, r = self._changedfiles(parents[0], ctx)
627 if not full:
628 files = ma + r
629 copyfiles = ma
630 # _getcopies() is also run for roots and before filtering so missing
631 # revlogs are detected early
632 copies = self._getcopies(ctx, parents, copyfiles)
633 cleanp2 = set()
634 if len(parents) == 2:
635 d = parents[1].manifest().diff(ctx.manifest(), clean=True)
636 for f, value in d.items():
637 if value is None:
638 cleanp2.add(f)
639 changes = [(f, rev) for f in files if f not in self.ignored]
640 changes.sort()
641 return changes, copies, cleanp2
642
643 def _getcopies(self, ctx, parents, files):
644 copies = {}
645 for name in files:
646 if name in self.ignored:
647 continue
648 try:
649 copysource = ctx.filectx(name).copysource()
650 if copysource in self.ignored:
651 continue
652 # Ignore copy sources not in parent revisions
653 if not any(copysource in p for p in parents):
654 continue
655 copies[name] = copysource
656 except TypeError:
657 pass
658 except error.LookupError as e:
659 if not self.ignoreerrors:
660 raise
661 self.ignored.add(name)
662 self.ui.warn(_(b'ignoring: %s\n') % e)
663 return copies
664
665 def getcommit(self, rev):
666 ctx = self._changectx(rev)
667 _parents = self._parents(ctx)
668 parents = [p.hex() for p in _parents]
669 optparents = [p.hex() for p in ctx.parents() if p and p not in _parents]
670 crev = rev
671
672 return common.commit(
673 author=ctx.user(),
674 date=dateutil.datestr(ctx.date(), b'%Y-%m-%d %H:%M:%S %1%2'),
675 desc=ctx.description(),
676 rev=crev,
677 parents=parents,
678 optparents=optparents,
679 branch=ctx.branch(),
680 extra=ctx.extra(),
681 sortkey=ctx.rev(),
682 saverev=self.saverev,
683 phase=ctx.phase(),
684 ctx=ctx,
685 )
686
687 def numcommits(self):
688 return len(self.repo)
689
690 def gettags(self):
691 # This will get written to .hgtags, filter non global tags out.
692 tags = [
693 t
694 for t in self.repo.tagslist()
695 if self.repo.tagtype(t[0]) == b'global'
696 ]
697 return {name: hex(node) for name, node in tags if self.keep(node)}
698
699 def getchangedfiles(self, rev, i):
700 ctx = self._changectx(rev)
701 parents = self._parents(ctx)
702 if not parents and i is None:
703 i = 0
704 ma, r = ctx.manifest().keys(), []
705 else:
706 i = i or 0
707 ma, r = self._changedfiles(parents[i], ctx)
708 ma, r = ([f for f in l if f not in self.ignored] for l in (ma, r))
709
710 if i == 0:
711 self._changescache = (rev, (ma, r))
712
713 return ma + r
714
715 def converted(self, rev, destrev):
716 if self.convertfp is None:
717 self.convertfp = open(self.repo.vfs.join(b'shamap'), 'ab')
718 self.convertfp.write(util.tonativeeol(b'%s %s\n' % (destrev, rev)))
719 self.convertfp.flush()
720
721 def before(self):
722 self.ui.debug(b'run hg source pre-conversion action\n')
723
724 def after(self):
725 self.ui.debug(b'run hg source post-conversion action\n')
726
727 def hasnativeorder(self):
728 return True
729
730 def hasnativeclose(self):
731 return True
732
733 def lookuprev(self, rev):
734 try:
735 return hex(self.repo.lookup(rev))
736 except (error.RepoError, error.LookupError):
737 return None
738
739 def getbookmarks(self):
740 return bookmarks.listbookmarks(self.repo)
741
742 def checkrevformat(self, revstr, mapname=b'splicemap'):
743 """Mercurial, revision string is a 40 byte hex"""
744 self.checkhexformat(revstr, mapname)