3 # Copyright (c) 2012 Felipe Contreras
6 # Inspired by Rocco Rutte's hg-fast-export
8 # Just copy to your ~/bin, or anywhere in your $PATH.
9 # Then you can clone with:
10 # git clone hg::/path/to/mercurial/repo/
12 # For remote repositories a local clone is stored in
13 # "$GIT_DIR/hg/origin/clone/.hg/".
15 from mercurial import hg, ui, bookmarks, context, util, encoding, node, error
27 # If you want to switch to hg-git compatibility mode:
28 # git config --global remote-hg.hg-git-compat true
30 # If you are not in hg-git-compat mode and want to disable the tracking of
32 # git config --global remote-hg.track-branches false
34 # If you don't want to force pushes (and thus risk creating new remote heads):
35 # git config --global remote-hg.force-push false
37 # If you want the equivalent of hg's clone/pull--insecure option:
38 # git config remote-hg.insecure true
41 # Sensible defaults for git.
42 # hg bookmarks are exported as git branches, hg branches are prefixed
43 # with 'branches/', HEAD is a special case.
47 # Only hg bookmarks are exported as git branches.
48 # Commits are modified to preserve hg information and allow bidirectionality.
51 NAME_RE = re.compile('^([^<>]+)')
52 AUTHOR_RE = re.compile('^([^<>]+?)? ?<([^<>]*)>$')
53 AUTHOR_HG_RE = re.compile('^(.*?) ?<(.*?)(?:>(.+)?)?$')
54 RAW_AUTHOR_RE = re.compile('^(\w+) (?:(.+)? )?<(.*)> (\d+) ([+-]\d+)')
57 sys.stderr.write('ERROR: %s\n' % (msg % args))
61 sys.stderr.write('WARNING: %s\n' % (msg % args))
64 return 'l' in flags and '120000' or 'x' in flags and '100755' or '100644'
67 return '%+03d%02d' % (-tz / 3600, -tz % 3600 / 60)
70 m = { '100755': 'x', '120000': 'l' }
71 return m.get(mode, '')
74 return hg.node.hex(node)
76 def get_config(config):
77 cmd = ['git', 'config', '--get', config]
78 process = subprocess.Popen(cmd, stdout=subprocess.PIPE)
79 output, _ = process.communicate()
84 def __init__(self, path):
94 if not os.path.exists(self.path):
97 tmp = json.load(open(self.path))
99 self.tips = tmp['tips']
100 self.marks = tmp['marks']
101 self.last_mark = tmp['last-mark']
103 for rev, mark in self.marks.iteritems():
104 self.rev_marks[mark] = int(rev)
107 return { 'tips': self.tips, 'marks': self.marks, 'last-mark' : self.last_mark }
110 json.dump(self.dict(), open(self.path, 'w'))
113 return str(self.dict())
115 def from_rev(self, rev):
116 return self.marks[str(rev)]
118 def to_rev(self, mark):
119 return self.rev_marks[mark]
121 def get_mark(self, rev):
123 self.marks[str(rev)] = self.last_mark
124 return self.last_mark
126 def new_mark(self, rev, mark):
127 self.marks[str(rev)] = mark
128 self.rev_marks[mark] = rev
129 self.last_mark = mark
131 def is_marked(self, rev):
132 return self.marks.has_key(str(rev))
134 def get_tip(self, branch):
135 return self.tips.get(branch, 0)
137 def set_tip(self, branch, tip):
138 self.tips[branch] = tip
142 def __init__(self, repo):
144 self.line = self.get_line()
147 return sys.stdin.readline().strip()
149 def __getitem__(self, i):
150 return self.line.split()[i]
152 def check(self, word):
153 return self.line.startswith(word)
155 def each_block(self, separator):
156 while self.line != separator:
158 self.line = self.get_line()
161 return self.each_block('')
164 self.line = self.get_line()
165 if self.line == 'done':
169 i = self.line.index(':') + 1
170 return int(self.line[i:])
173 if not self.check('data'):
175 i = self.line.index(' ') + 1
176 size = int(self.line[i:])
177 return sys.stdin.read(size)
179 def get_author(self):
183 m = RAW_AUTHOR_RE.match(self.line)
186 _, name, email, date, tz = m.groups()
187 if name and 'ext:' in name:
188 m = re.match('^(.+?) ext:\((.+)\)$', name)
191 ex = urllib.unquote(m.group(2))
193 if email != bad_mail:
195 user = '%s <%s>' % (name, email)
197 user = '<%s>' % (email)
205 tz = ((tz / 100) * 3600) + ((tz % 100) * 60)
206 return (user, int(date), -tz)
210 print "M %s inline %s" % (gitmode(fc.flags()), fc.path())
211 print "data %d" % len(d)
214 def get_filechanges(repo, ctx, parent):
220 prev = repo[parent].manifest().copy()
224 if (cur.flags(fn) != prev.flags(fn) or cur[fn] != prev[fn]):
229 removed |= set(prev.keys())
231 return added | modified, removed
233 def fixup_user_git(user):
235 user = user.replace('"', '')
236 m = AUTHOR_RE.match(user)
239 mail = m.group(2).strip()
241 m = NAME_RE.match(user)
243 name = m.group(1).strip()
246 def fixup_user_hg(user):
248 # stole this from hg-git
249 return re.sub('[<>\n]', '?', name.lstrip('< ').rstrip('> '))
251 m = AUTHOR_HG_RE.match(user)
253 name = sanitize(m.group(1))
254 mail = sanitize(m.group(2))
257 name += ' ext:(' + urllib.quote(ex) + ')'
259 name = sanitize(user)
267 def fixup_user(user):
268 global mode, bad_mail
271 name, mail = fixup_user_git(user)
273 name, mail = fixup_user_hg(user)
280 return '%s <%s>' % (name, mail)
282 def get_repo(url, alias):
286 myui.setconfig('ui', 'interactive', 'off')
287 myui.fout = sys.stderr
290 if get_config('remote-hg.insecure') == 'true\n':
291 myui.setconfig('web', 'cacerts', '')
292 except subprocess.CalledProcessError:
296 repo = hg.repository(myui, url)
298 local_path = os.path.join(dirname, 'clone')
299 if not os.path.exists(local_path):
301 peer, dstpeer = hg.clone(myui, {}, url, local_path, update=True, pull=True)
303 die('Repository error')
304 repo = dstpeer.local()
306 repo = hg.repository(myui, local_path)
308 peer = hg.peer(myui, {}, url)
310 die('Repository error')
311 repo.pull(peer, heads=None, force=True)
315 def rev_to_mark(rev):
317 return marks.from_rev(rev)
319 def mark_to_rev(mark):
321 return marks.to_rev(mark)
323 def export_ref(repo, name, kind, head):
324 global prefix, marks, mode
326 ename = '%s/%s' % (kind, name)
327 tip = marks.get_tip(ename)
329 # mercurial takes too much time checking this
330 if tip and tip == head.rev():
333 revs = xrange(tip, head.rev() + 1)
336 revs = [rev for rev in revs if not marks.is_marked(rev)]
341 (manifest, user, (time, tz), files, desc, extra) = repo.changelog.read(c.node())
342 rev_branch = extra['branch']
344 author = "%s %d %s" % (fixup_user(user), time, gittz(tz))
345 if 'committer' in extra:
346 user, time, tz = extra['committer'].rsplit(' ', 2)
347 committer = "%s %s %s" % (user, time, gittz(int(tz)))
351 parents = [p for p in repo.changelog.parentrevs(rev) if p >= 0]
353 if len(parents) == 0:
354 modified = c.manifest().keys()
357 modified, removed = get_filechanges(repo, c, parents[0])
362 if rev_branch != 'default':
363 extra_msg += 'branch : %s\n' % rev_branch
367 if f not in c.manifest():
369 rename = c.filectx(f).renamed()
371 renames.append((rename[0], f))
374 extra_msg += "rename : %s => %s\n" % e
376 for key, value in extra.iteritems():
377 if key in ('author', 'committer', 'encoding', 'message', 'branch', 'hg-git'):
380 extra_msg += "extra : %s : %s\n" % (key, urllib.quote(value))
384 desc += '\n--HG--\n' + extra_msg
386 if len(parents) == 0 and rev:
387 print 'reset %s/%s' % (prefix, ename)
389 print "commit %s/%s" % (prefix, ename)
390 print "mark :%d" % (marks.get_mark(rev))
391 print "author %s" % (author)
392 print "committer %s" % (committer)
393 print "data %d" % (len(desc))
397 print "from :%s" % (rev_to_mark(parents[0]))
399 print "merge :%s" % (rev_to_mark(parents[1]))
402 export_file(c.filectx(f))
408 if (count % 100 == 0):
409 print "progress revision %d '%s' (%d/%d)" % (rev, name, count, len(revs))
410 print "#############################################################"
412 # make sure the ref is updated
413 print "reset %s/%s" % (prefix, ename)
414 print "from :%u" % rev_to_mark(rev)
417 marks.set_tip(ename, rev)
419 def export_tag(repo, tag):
420 export_ref(repo, tag, 'tags', repo[tag])
422 def export_bookmark(repo, bmark):
424 export_ref(repo, bmark, 'bookmarks', head)
426 def export_branch(repo, branch):
427 tip = get_branch_tip(repo, branch)
429 export_ref(repo, branch, 'branches', head)
431 def export_head(repo):
433 export_ref(repo, g_head[0], 'bookmarks', g_head[1])
435 def do_capabilities(parser):
436 global prefix, dirname
440 print "refspec refs/heads/branches/*:%s/branches/*" % prefix
441 print "refspec refs/heads/*:%s/bookmarks/*" % prefix
442 print "refspec refs/tags/*:%s/tags/*" % prefix
444 path = os.path.join(dirname, 'marks-git')
446 if os.path.exists(path):
447 print "*import-marks %s" % path
448 print "*export-marks %s" % path
452 def get_branch_tip(repo, branch):
455 heads = branches.get(branch, None)
459 # verify there's only one head
461 warn("Branch '%s' has more than one head, consider merging" % branch)
462 # older versions of mercurial don't have this
463 if hasattr(repo, "branchtip"):
464 return repo.branchtip(branch)
468 def list_head(repo, cur):
469 global g_head, bmarks
471 head = bookmarks.readcurrent(repo)
475 # fake bookmark from current branch
482 if head == 'default':
486 print "@refs/heads/%s HEAD" % head
487 g_head = (head, node)
490 global branches, bmarks, mode, track_branches
493 for bmark, node in bookmarks.listbookmarks(repo).iteritems():
494 bmarks[bmark] = repo[node]
496 cur = repo.dirstate.branch()
501 for branch in repo.branchmap():
502 heads = repo.branchheads(branch)
504 branches[branch] = heads
506 for branch in branches:
507 print "? refs/heads/branches/%s" % branch
510 print "? refs/heads/%s" % bmark
512 for tag, node in repo.tagslist():
515 print "? refs/tags/%s" % tag
519 def do_import(parser):
522 path = os.path.join(dirname, 'marks-git')
525 if os.path.exists(path):
526 print "feature import-marks=%s" % path
527 print "feature export-marks=%s" % path
530 tmp = encoding.encoding
531 encoding.encoding = 'utf-8'
533 # lets get all the import lines
534 while parser.check('import'):
539 elif ref.startswith('refs/heads/branches/'):
540 branch = ref[len('refs/heads/branches/'):]
541 export_branch(repo, branch)
542 elif ref.startswith('refs/heads/'):
543 bmark = ref[len('refs/heads/'):]
544 export_bookmark(repo, bmark)
545 elif ref.startswith('refs/tags/'):
546 tag = ref[len('refs/tags/'):]
547 export_tag(repo, tag)
551 encoding.encoding = tmp
555 def parse_blob(parser):
559 mark = parser.get_mark()
561 data = parser.get_data()
562 blob_marks[mark] = data
565 def get_merge_files(repo, p1, p2, files):
566 for e in repo[p1].files():
568 if e not in repo[p1].manifest():
570 f = { 'ctx' : repo[p1][e] }
573 def parse_commit(parser):
574 global marks, blob_marks, parsed_refs
577 from_mark = merge_mark = None
582 commit_mark = parser.get_mark()
584 author = parser.get_author()
586 committer = parser.get_author()
588 data = parser.get_data()
590 if parser.check('from'):
591 from_mark = parser.get_mark()
593 if parser.check('merge'):
594 merge_mark = parser.get_mark()
596 if parser.check('merge'):
597 die('octopus merges are not supported yet')
602 if parser.check('M'):
603 t, m, mark_ref, path = line.split(' ', 3)
604 mark = int(mark_ref[1:])
605 f = { 'mode' : hgmode(m), 'data' : blob_marks[mark] }
606 elif parser.check('D'):
607 t, path = line.split(' ', 1)
608 f = { 'deleted' : True }
610 die('Unknown file command: %s' % line)
613 def getfilectx(repo, memctx, f):
619 is_exec = of['mode'] == 'x'
620 is_link = of['mode'] == 'l'
621 rename = of.get('rename', None)
622 return context.memfilectx(f, of['data'],
623 is_link, is_exec, rename)
627 user, date, tz = author
630 if committer != author:
631 extra['committer'] = "%s %u %u" % committer
634 p1 = repo.changelog.node(mark_to_rev(from_mark))
639 p2 = repo.changelog.node(mark_to_rev(merge_mark))
644 # If files changed from any of the parents, hg wants to know, but in git if
645 # nothing changed from the first parent, nothing changed.
648 get_merge_files(repo, p1, p2, files)
650 # Check if the ref is supposed to be a named branch
651 if ref.startswith('refs/heads/branches/'):
652 extra['branch'] = ref[len('refs/heads/branches/'):]
655 i = data.find('\n--HG--\n')
657 tmp = data[i + len('\n--HG--\n'):].strip()
658 for k, v in [e.split(' : ', 1) for e in tmp.split('\n')]:
660 old, new = v.split(' => ', 1)
661 files[new]['rename'] = old
665 ek, ev = v.split(' : ', 1)
666 extra[ek] = urllib.unquote(ev)
669 ctx = context.memctx(repo, (p1, p2), data,
670 files.keys(), getfilectx,
671 user, (date, tz), extra)
673 tmp = encoding.encoding
674 encoding.encoding = 'utf-8'
676 node = repo.commitctx(ctx)
678 encoding.encoding = tmp
680 rev = repo[node].rev()
682 parsed_refs[ref] = node
683 marks.new_mark(rev, commit_mark)
685 def parse_reset(parser):
691 if parser.check('commit'):
694 if not parser.check('from'):
696 from_mark = parser.get_mark()
699 node = parser.repo.changelog.node(mark_to_rev(from_mark))
700 parsed_refs[ref] = node
702 def parse_tag(parser):
705 from_mark = parser.get_mark()
707 tagger = parser.get_author()
709 data = parser.get_data()
714 def do_export(parser):
715 global parsed_refs, bmarks, peer
721 for line in parser.each_block('done'):
722 if parser.check('blob'):
724 elif parser.check('commit'):
726 elif parser.check('reset'):
728 elif parser.check('tag'):
730 elif parser.check('feature'):
733 die('unhandled export command: %s' % line)
735 for ref, node in parsed_refs.iteritems():
736 if ref.startswith('refs/heads/branches'):
738 elif ref.startswith('refs/heads/'):
739 bmark = ref[len('refs/heads/'):]
740 p_bmarks.append((bmark, node))
742 elif ref.startswith('refs/tags/'):
743 tag = ref[len('refs/tags/'):]
745 msg = 'Added tag %s for changeset %s' % (tag, hghex(node[:6]));
746 parser.repo.tag([tag], node, msg, False, None, {})
748 parser.repo.tag([tag], node, None, True, None, {})
751 # transport-helper/fast-export bugs
755 parser.repo.push(peer, force=force_push)
758 for bmark, node in p_bmarks:
759 ref = 'refs/heads/' + bmark
763 old = bmarks[bmark].hex()
767 if bmark == 'master' and 'master' not in parser.repo._bookmarks:
770 elif bookmarks.pushbookmark(parser.repo, bmark, old, new):
774 print "error %s" % ref
778 if not peer.pushkey('bookmarks', bmark, old, new):
779 print "error %s" % ref
786 def fix_path(alias, repo, orig_url):
787 repo_url = util.url(repo.url())
788 url = util.url(orig_url)
789 if str(url) == str(repo_url):
791 cmd = ['git', 'config', 'remote.%s.url' % alias, "hg::%s" % repo_url]
795 global prefix, dirname, branches, bmarks
796 global marks, blob_marks, parsed_refs
797 global peer, mode, bad_mail, bad_name
798 global track_branches, force_push, is_tmp
804 hg_git_compat = False
805 track_branches = True
809 if get_config('remote-hg.hg-git-compat') == 'true\n':
811 track_branches = False
812 if get_config('remote-hg.track-branches') == 'false\n':
813 track_branches = False
814 if get_config('remote-hg.force-push') == 'false\n':
816 except subprocess.CalledProcessError:
821 bad_mail = 'none@none'
830 alias = util.sha1(alias).hexdigest()
834 gitdir = os.environ['GIT_DIR']
835 dirname = os.path.join(gitdir, 'hg', alias)
842 repo = get_repo(url, alias)
843 prefix = 'refs/hg/%s' % alias
846 fix_path(alias, peer or repo, url)
848 if not os.path.exists(dirname):
851 marks_path = os.path.join(dirname, 'marks-hg')
852 marks = Marks(marks_path)
854 parser = Parser(repo)
856 if parser.check('capabilities'):
857 do_capabilities(parser)
858 elif parser.check('list'):
860 elif parser.check('import'):
862 elif parser.check('export'):
865 die('unhandled command: %s' % line)
874 shutil.rmtree(dirname)
877 sys.exit(main(sys.argv))