Debian Codegraph @

hgext/convert/convcmd.py

raw
1 # convcmd - convert extension commands definition
2 #
3 # Copyright 2005-2007 Olivia Mackall <[email protected]>
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 from __future__ import annotations
9
10 import collections
11 import heapq
12 import os
13 import shutil
14 import typing
15
16 from typing import (
17 AnyStr,
18 Mapping,
19 )
20
21 from mercurial.i18n import _
22 from mercurial import (
23 encoding,
24 error,
25 pycompat,
26 scmutil,
27 util,
28 )
29 from mercurial.cmd_impls import (
30 clone as clone_impl,
31 )
32 from mercurial.utils import dateutil
33
34 from . import (
35 bzr,
36 common,
37 cvs,
38 darcs,
39 filemap,
40 git,
41 gnuarch,
42 hg as hgconvert,
43 monotone,
44 p4,
45 subversion,
46 )
47
48 if typing.TYPE_CHECKING:
49 from mercurial import (
50 ui as uimod,
51 )
52
53 mapfile = common.mapfile
54 MissingTool = common.MissingTool
55 NoRepo = common.NoRepo
56 SKIPREV = common.SKIPREV
57
58 bzr_source = bzr.bzr_source
59 convert_cvs = cvs.convert_cvs
60 convert_git = git.convert_git
61 darcs_source = darcs.darcs_source
62 gnuarch_source = gnuarch.gnuarch_source
63 mercurial_sink = hgconvert.mercurial_sink
64 mercurial_source = hgconvert.mercurial_source
65 monotone_source = monotone.monotone_source
66 p4_source = p4.p4_source
67 svn_sink = subversion.svn_sink
68 svn_source = subversion.svn_source
69
70 orig_encoding: bytes = b'ascii'
71
72
73 def readauthormap(ui: uimod.ui, authorfile, authors=None):
74 if authors is None:
75 authors = {}
76 with open(authorfile, 'rb') as afile:
77 for line in afile:
78 line = line.strip()
79 if not line or line.startswith(b'#'):
80 continue
81
82 try:
83 srcauthor, dstauthor = line.split(b'=', 1)
84 except ValueError:
85 msg = _(b'ignoring bad line in author map file %s: %s\n')
86 ui.warn(msg % (authorfile, line.rstrip()))
87 continue
88
89 srcauthor = srcauthor.strip()
90 dstauthor = dstauthor.strip()
91 if authors.get(srcauthor) in (None, dstauthor):
92 msg = _(b'mapping author %s to %s\n')
93 ui.debug(msg % (srcauthor, dstauthor))
94 authors[srcauthor] = dstauthor
95 continue
96
97 m = _(b'overriding mapping for author %s, was %s, will be %s\n')
98 ui.status(m % (srcauthor, authors[srcauthor], dstauthor))
99 return authors
100
101
102 def recode(s: AnyStr) -> bytes:
103 if isinstance(s, str):
104 return s.encode(pycompat.sysstr(orig_encoding), 'replace')
105 else:
106 return s.decode('utf-8').encode(
107 pycompat.sysstr(orig_encoding), 'replace'
108 )
109
110
111 def mapbranch(branch: bytes, branchmap: Mapping[bytes, bytes]) -> bytes:
112 """
113 >>> bmap = {b'default': b'branch1'}
114 >>> for i in [b'', None]:
115 ... mapbranch(i, bmap)
116 'branch1'
117 'branch1'
118 >>> bmap = {b'None': b'branch2'}
119 >>> for i in [b'', None]:
120 ... mapbranch(i, bmap)
121 'branch2'
122 'branch2'
123 >>> bmap = {b'None': b'branch3', b'default': b'branch4'}
124 >>> for i in [b'None', b'', None, b'default', b'branch5']:
125 ... mapbranch(i, bmap)
126 'branch3'
127 'branch4'
128 'branch4'
129 'branch4'
130 'branch5'
131 """
132 # If branch is None or empty, this commit is coming from the source
133 # repository's default branch and destined for the default branch in the
134 # destination repository. For such commits, using a literal "default"
135 # in branchmap below allows the user to map "default" to an alternate
136 # default branch in the destination repository.
137 branch = branchmap.get(branch or b'default', branch)
138 # At some point we used "None" literal to denote the default branch,
139 # attempt to use that for backward compatibility.
140 if not branch:
141 branch = branchmap.get(b'None', branch)
142 return branch
143
144
145 source_converters = [
146 (b'cvs', convert_cvs, b'branchsort'),
147 (b'git', convert_git, b'branchsort'),
148 (b'svn', svn_source, b'branchsort'),
149 (b'hg', mercurial_source, b'sourcesort'),
150 (b'darcs', darcs_source, b'branchsort'),
151 (b'mtn', monotone_source, b'branchsort'),
152 (b'gnuarch', gnuarch_source, b'branchsort'),
153 (b'bzr', bzr_source, b'branchsort'),
154 (b'p4', p4_source, b'branchsort'),
155 ]
156
157 sink_converters = [
158 (b'hg', mercurial_sink),
159 (b'svn', svn_sink),
160 ]
161
162
163 def convertsource(ui: uimod.ui, path: bytes, type: bytes, revs):
164 exceptions = []
165 if type and type not in [s[0] for s in source_converters]:
166 raise error.Abort(_(b'%s: invalid source repository type') % type)
167 for name, source, sortmode in source_converters:
168 try:
169 if not type or name == type:
170 return source(ui, name, path, revs), sortmode
171 except (NoRepo, MissingTool) as inst:
172 exceptions.append(inst)
173 if not ui.quiet:
174 for inst in exceptions:
175 ui.write(b"%s\n" % pycompat.bytestr(inst.args[0]))
176 raise error.Abort(_(b'%s: missing or unsupported repository') % path)
177
178
179 def convertsink(
180 ui: uimod.ui, path: bytes, type: bytes
181 ) -> hgconvert.mercurial_sink | subversion.svn_sink:
182 if type and type not in [s[0] for s in sink_converters]:
183 raise error.Abort(_(b'%s: invalid destination repository type') % type)
184 for name, sink in sink_converters:
185 try:
186 if not type or name == type:
187 return sink(ui, name, path)
188 except NoRepo as inst:
189 ui.note(_(b"convert: %s\n") % inst)
190 except MissingTool as inst:
191 raise error.Abort(b'%s\n' % inst)
192 raise error.Abort(_(b'%s: unknown repository type') % path)
193
194
195 class progresssource:
196 def __init__(self, ui: uimod.ui, source, filecount: int | None) -> None:
197 self.ui = ui
198 self.source = source
199 self.progress = ui.makeprogress(
200 _(b'getting files'), unit=_(b'files'), total=filecount
201 )
202
203 def getfile(self, file, rev):
204 self.progress.increment(item=file)
205 return self.source.getfile(file, rev)
206
207 def targetfilebelongstosource(self, targetfilename):
208 return self.source.targetfilebelongstosource(targetfilename)
209
210 def lookuprev(self, rev):
211 return self.source.lookuprev(rev)
212
213 def close(self):
214 self.progress.complete()
215
216
217 # Sorters are used by the `toposort` function to maintain a set of revisions
218 # which can be converted immediately and pick one
219 class branchsorter:
220 """If the previously converted revision has a child in the
221 eligible revisions list, pick it. Return the list head
222 otherwise. Branch sort attempts to minimize branch
223 switching, which is harmful for Mercurial backend
224 compression.
225 """
226
227 def __init__(self, parents):
228 self.nodes = []
229 self.parents = parents
230 self.prev = None
231
232 def picknext(self):
233 next = self.nodes[0]
234 for n in self.nodes:
235 if self.prev in self.parents[n]:
236 next = n
237 break
238 self.prev = next
239 self.nodes.remove(next)
240 return next
241
242 def insert(self, node):
243 self.nodes.insert(0, node)
244
245 def __len__(self):
246 return self.nodes.__len__()
247
248
249 class keysorter:
250 """Key-based sort, ties broken by insertion order"""
251
252 def __init__(self, keyfn):
253 self.heap = []
254 self.keyfn = keyfn
255 self.counter = 0
256
257 def picknext(self):
258 return heapq.heappop(self.heap)[2]
259
260 def insert(self, node):
261 counter = self.counter
262 self.counter = counter + 1
263 key = self.keyfn(node)
264 heapq.heappush(self.heap, (key, counter, node))
265
266 def __len__(self):
267 return self.heap.__len__()
268
269
270 class converter:
271 def __init__(self, ui: uimod.ui, source, dest, revmapfile, opts) -> None:
272 self.source = source
273 self.dest = dest
274 self.ui = ui
275 self.opts = opts
276 self.commitcache = {}
277 self.authors = {}
278 self.authorfile = None
279
280 # Record converted revisions persistently: maps source revision
281 # ID to target revision ID (both strings). (This is how
282 # incremental conversions work.)
283 self.map = mapfile(ui, revmapfile)
284
285 # Read first the dst author map if any
286 authorfile = self.dest.authorfile()
287 if authorfile and os.path.exists(authorfile):
288 self.readauthormap(authorfile)
289 # Extend/Override with new author map if necessary
290 if opts.get(b'authormap'):
291 self.readauthormap(opts.get(b'authormap'))
292 self.authorfile = self.dest.authorfile()
293
294 self.splicemap = self.parsesplicemap(opts.get(b'splicemap'))
295 self.branchmap = mapfile(ui, opts.get(b'branchmap'))
296
297 def parsesplicemap(self, path: bytes) -> dict[bytes, list[bytes]]:
298 """check and validate the splicemap format and
299 return a child/parents dictionary.
300 Format checking has two parts.
301 1. generic format which is same across all source types
302 2. specific format checking which may be different for
303 different source type. This logic is implemented in
304 checkrevformat function in source files like
305 hg.py, subversion.py etc.
306 """
307
308 if not path:
309 return {}
310 m = {}
311 try:
312 with open(path, 'rb') as fp:
313 for i, line in enumerate(fp):
314 line = line.splitlines()[0].rstrip()
315 if not line:
316 # Ignore blank lines
317 continue
318 # split line
319 lex = common.shlexer(data=line, whitespace=b',')
320 line = list(lex)
321 # check number of parents
322 if not (2 <= len(line) <= 3):
323 raise error.Abort(
324 _(
325 b'syntax error in %s(%d): child parent1'
326 b'[,parent2] expected'
327 )
328 % (path, i + 1)
329 )
330 for part in line:
331 self.source.checkrevformat(part)
332 child, p1, p2 = line[0], line[1:2], line[2:]
333 if p1 == p2:
334 m[child] = p1
335 else:
336 m[child] = p1 + p2
337 # if file does not exist or error reading, exit
338 except OSError:
339 raise error.Abort(
340 _(b'splicemap file not found or error reading %s:') % path
341 )
342 return m
343
344 def walktree(self, heads):
345 """Return a mapping that identifies the uncommitted parents of every
346 uncommitted changeset."""
347 visit = list(heads)
348 known = set()
349 parents = {}
350 numcommits = self.source.numcommits()
351 progress = self.ui.makeprogress(
352 _(b'scanning'), unit=_(b'revisions'), total=numcommits
353 )
354 while visit:
355 n = visit.pop(0)
356 if n in known:
357 continue
358 if n in self.map:
359 m = self.map[n]
360 if m == SKIPREV or self.dest.hascommitfrommap(m):
361 continue
362 known.add(n)
363 progress.update(len(known))
364 commit = self.cachecommit(n)
365 parents[n] = []
366 for p in commit.parents:
367 parents[n].append(p)
368 visit.append(p)
369 progress.complete()
370
371 return parents
372
373 def mergesplicemap(self, parents, splicemap) -> None:
374 """A splicemap redefines child/parent relationships. Check the
375 map contains valid revision identifiers and merge the new
376 links in the source graph.
377 """
378 for c in sorted(splicemap):
379 if c not in parents:
380 if not self.dest.hascommitforsplicemap(self.map.get(c, c)):
381 # Could be in source but not converted during this run
382 self.ui.warn(
383 _(
384 b'splice map revision %s is not being '
385 b'converted, ignoring\n'
386 )
387 % c
388 )
389 continue
390 pc = []
391 for p in splicemap[c]:
392 # We do not have to wait for nodes already in dest.
393 if self.dest.hascommitforsplicemap(self.map.get(p, p)):
394 continue
395 # Parent is not in dest and not being converted, not good
396 if p not in parents:
397 raise error.Abort(_(b'unknown splice map parent: %s') % p)
398 pc.append(p)
399 parents[c] = pc
400
401 def toposort(self, parents, sortmode):
402 """Return an ordering such that every uncommitted changeset is
403 preceded by all its uncommitted ancestors."""
404
405 def mapchildren(parents):
406 """Return a (children, roots) tuple where 'children' maps parent
407 revision identifiers to children ones, and 'roots' is the list of
408 revisions without parents. 'parents' must be a mapping of revision
409 identifier to its parents ones.
410 """
411 visit = collections.deque(sorted(parents))
412 seen = set()
413 children = {}
414 roots = []
415
416 while visit:
417 n = visit.popleft()
418 if n in seen:
419 continue
420 seen.add(n)
421 # Ensure that nodes without parents are present in the
422 # 'children' mapping.
423 children.setdefault(n, [])
424 hasparent = False
425 for p in parents[n]:
426 if p not in self.map:
427 visit.append(p)
428 hasparent = True
429 children.setdefault(p, []).append(n)
430 if not hasparent:
431 roots.append(n)
432
433 return children, roots
434
435 def makesourcesorter():
436 """Source specific sort."""
437 keyfn = lambda n: self.commitcache[n].sortkey
438 return keysorter(keyfn)
439
440 def makeclosesorter():
441 """Close order sort."""
442 keyfn = lambda n: (
443 b'close' not in self.commitcache[n].extra,
444 self.commitcache[n].sortkey,
445 )
446 return keysorter(keyfn)
447
448 def makedatesorter():
449 """Sort revisions by date."""
450
451 def getdate(n):
452 commit = self.commitcache[n]
453 # The other entries are here as tie breaker for stability
454 return (
455 dateutil.parsedate(commit.date),
456 commit.rev,
457 commit.branch,
458 )
459
460 return keysorter(getdate)
461
462 if sortmode == b'branchsort':
463 sorter = branchsorter(parents)
464 elif sortmode == b'datesort':
465 sorter = makedatesorter()
466 elif sortmode == b'sourcesort':
467 sorter = makesourcesorter()
468 elif sortmode == b'closesort':
469 sorter = makeclosesorter()
470 else:
471 raise error.Abort(_(b'unknown sort mode: %s') % sortmode)
472
473 children, roots = mapchildren(parents)
474
475 for node in roots:
476 sorter.insert(node)
477
478 s = []
479 pendings = {}
480 while sorter:
481 n = sorter.picknext()
482 s.append(n)
483
484 # Update dependents list
485 for c in children.get(n, []):
486 if c not in pendings:
487 pendings[c] = [p for p in parents[c] if p not in self.map]
488 try:
489 pendings[c].remove(n)
490 except ValueError:
491 raise error.Abort(
492 _(b'cycle detected between %s and %s')
493 % (recode(c), recode(n))
494 )
495 if not pendings[c]:
496 # Parents are converted, node is eligible
497 sorter.insert(c)
498 pendings[c] = None
499
500 if len(s) != len(parents):
501 raise error.Abort(_(b"not all revisions were sorted"))
502
503 return s
504
505 def writeauthormap(self) -> None:
506 authorfile = self.authorfile
507 if authorfile:
508 self.ui.status(_(b'writing author map file %s\n') % authorfile)
509 with open(authorfile, 'wb+') as ofile:
510 for author in self.authors:
511 ofile.write(
512 util.tonativeeol(
513 b"%s=%s\n" % (author, self.authors[author])
514 )
515 )
516
517 def readauthormap(self, authorfile) -> None:
518 self.authors = readauthormap(self.ui, authorfile, self.authors)
519
520 def cachecommit(self, rev):
521 commit = self.source.getcommit(rev)
522 commit.author = self.authors.get(commit.author, commit.author)
523 commit.branch = mapbranch(commit.branch, self.branchmap)
524 self.commitcache[rev] = commit
525 return commit
526
527 def copy(self, rev) -> None:
528 commit = self.commitcache[rev]
529 full = self.opts.get(b'full')
530 changes = self.source.getchanges(rev, full)
531 if isinstance(changes, bytes):
532 if changes == SKIPREV:
533 dest = SKIPREV
534 else:
535 dest = self.map[changes]
536 self.map[rev] = dest
537 return
538 files, copies, cleanp2 = changes
539 pbranches = []
540 if commit.parents:
541 for prev in commit.parents:
542 if prev not in self.commitcache:
543 self.cachecommit(prev)
544 pbranches.append(
545 (self.map[prev], self.commitcache[prev].branch)
546 )
547 self.dest.setbranch(commit.branch, pbranches)
548 try:
549 parents = self.splicemap[rev]
550 self.ui.status(
551 _(b'spliced in %s as parents of %s\n')
552 % (_(b' and ').join(parents), rev)
553 )
554 parents = [self.map.get(p, p) for p in parents]
555 except KeyError:
556 parents = [b[0] for b in pbranches]
557 parents.extend(
558 self.map[x] for x in commit.optparents if x in self.map
559 )
560 if len(pbranches) != 2:
561 cleanp2 = set()
562 if len(parents) < 3:
563 source = progresssource(self.ui, self.source, len(files))
564 else:
565 # For an octopus merge, we end up traversing the list of
566 # changed files N-1 times. This tweak to the number of
567 # files makes it so the progress bar doesn't overflow
568 # itself.
569 source = progresssource(
570 self.ui, self.source, len(files) * (len(parents) - 1)
571 )
572 newnode = self.dest.putcommit(
573 files, copies, parents, commit, source, self.map, full, cleanp2
574 )
575 source.close()
576 self.source.converted(rev, newnode)
577 self.map[rev] = newnode
578
579 def convert(self, sortmode) -> None:
580 try:
581 self.source.before()
582 self.dest.before()
583 self.source.setrevmap(self.map)
584 self.ui.status(_(b"scanning source...\n"))
585 heads = self.source.getheads()
586 parents = self.walktree(heads)
587 self.mergesplicemap(parents, self.splicemap)
588 self.ui.status(_(b"sorting...\n"))
589 t = self.toposort(parents, sortmode)
590 num = len(t)
591 c = None
592
593 self.ui.status(_(b"converting...\n"))
594 progress = self.ui.makeprogress(
595 _(b'converting'), unit=_(b'revisions'), total=len(t)
596 )
597 for i, c in enumerate(t):
598 num -= 1
599 desc = self.commitcache[c].desc
600 if b"\n" in desc:
601 desc = desc.splitlines()[0]
602 # convert log message to local encoding without using
603 # tolocal() because the encoding.encoding convert()
604 # uses is 'utf-8'
605 self.ui.status(b"%d %s\n" % (num, recode(desc)))
606 self.ui.note(_(b"source: %s\n") % recode(c))
607 progress.update(i)
608 self.copy(c)
609 progress.complete()
610
611 if not self.ui.configbool(b'convert', b'skiptags'):
612 tags = self.source.gettags()
613 ctags = {}
614 for k in tags:
615 v = tags[k]
616 if self.map.get(v, SKIPREV) != SKIPREV:
617 ctags[k] = self.map[v]
618
619 if c and ctags:
620 nrev, tagsparent = self.dest.puttags(ctags)
621 if nrev and tagsparent:
622 # write another hash correspondence to override the
623 # previous one so we don't end up with extra tag heads
624 tagsparents = [
625 e for e in self.map.items() if e[1] == tagsparent
626 ]
627 if tagsparents:
628 self.map[tagsparents[0][0]] = nrev
629
630 bookmarks = self.source.getbookmarks()
631 cbookmarks = {}
632 for k in bookmarks:
633 v = bookmarks[k]
634 if self.map.get(v, SKIPREV) != SKIPREV:
635 cbookmarks[k] = self.map[v]
636
637 if c and cbookmarks:
638 self.dest.putbookmarks(cbookmarks)
639
640 self.writeauthormap()
641 finally:
642 self.cleanup()
643
644 def cleanup(self) -> None:
645 try:
646 self.dest.after()
647 finally:
648 self.source.after()
649 self.map.close()
650
651
652 def convert(
653 ui: uimod.ui, src, dest: bytes | None = None, revmapfile=None, **opts
654 ) -> None:
655 opts = pycompat.byteskwargs(opts)
656 global orig_encoding
657 orig_encoding = encoding.encoding
658 encoding.encoding = b'UTF-8'
659
660 # support --authors as an alias for --authormap
661 if not opts.get(b'authormap'):
662 opts[b'authormap'] = opts.get(b'authors')
663
664 if not dest:
665 dest = clone_impl.default_dest(src) + b"-hg"
666 ui.status(_(b"assuming destination %s\n") % dest)
667
668 destc = convertsink(ui, dest, opts.get(b'dest_type'))
669 destc = scmutil.wrapconvertsink(destc)
670
671 try:
672 srcc, defaultsort = convertsource(
673 ui, src, opts.get(b'source_type'), opts.get(b'rev')
674 )
675 except Exception:
676 for path in destc.created:
677 shutil.rmtree(path, True)
678 raise
679
680 sortmodes = (b'branchsort', b'datesort', b'sourcesort', b'closesort')
681 sortmode = [m for m in sortmodes if opts.get(m)]
682 if len(sortmode) > 1:
683 raise error.Abort(_(b'more than one sort mode specified'))
684 if sortmode:
685 sortmode = sortmode[0]
686 else:
687 sortmode = defaultsort
688
689 if sortmode == b'sourcesort' and not srcc.hasnativeorder():
690 raise error.Abort(
691 _(b'--sourcesort is not supported by this data source')
692 )
693 if sortmode == b'closesort' and not srcc.hasnativeclose():
694 raise error.Abort(
695 _(b'--closesort is not supported by this data source')
696 )
697
698 fmap = opts.get(b'filemap')
699 if fmap:
700 srcc = filemap.filemap_source(ui, srcc, fmap)
701 destc.setfilemapmode(True)
702
703 if not revmapfile:
704 revmapfile = destc.revmapfile()
705
706 c = converter(ui, srcc, destc, revmapfile, opts)
707 c.convert(sortmode)