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
, extensions
28 # If you want to switch to hg-git compatibility mode:
29 # git config --global remote-hg.hg-git-compat true
31 # If you are not in hg-git-compat mode and want to disable the tracking of
33 # git config --global remote-hg.track-branches false
35 # If you don't want to force pushes (and thus risk creating new remote heads):
36 # git config --global remote-hg.force-push false
38 # If you want the equivalent of hg's clone/pull--insecure option:
39 # git config remote-hg.insecure true
42 # Sensible defaults for git.
43 # hg bookmarks are exported as git branches, hg branches are prefixed
44 # with 'branches/', HEAD is a special case.
48 # Only hg bookmarks are exported as git branches.
49 # Commits are modified to preserve hg information and allow bidirectionality.
52 NAME_RE
= re
.compile('^([^<>]+)')
53 AUTHOR_RE
= re
.compile('^([^<>]+?)? ?<([^<>]*)>$')
54 EMAIL_RE
= re
.compile('^([^<>]+[^ \\\t<>])?\\b(?:[ \\t<>]*?)\\b([^ \\t<>]+@[^ \\t<>]+)')
55 AUTHOR_HG_RE
= re
.compile('^(.*?) ?<(.*?)(?:>(.+)?)?$')
56 RAW_AUTHOR_RE
= re
.compile('^(\w+) (?:(.+)? )?<(.*)> (\d+) ([+-]\d+)')
59 sys
.stderr
.write('ERROR: %s\n' % (msg
% args
))
63 sys
.stderr
.write('WARNING: %s\n' % (msg
% args
))
66 return 'l' in flags
and '120000' or 'x' in flags
and '100755' or '100644'
69 return '%+03d%02d' % (-tz
/ 3600, -tz
% 3600 / 60)
72 m
= { '100755': 'x', '120000': 'l' }
73 return m
.get(mode
, '')
76 return hg
.node
.hex(node
)
79 return ref
.replace('___', ' ')
82 return ref
.replace(' ', '___')
84 def get_config(config
):
85 cmd
= ['git', 'config', '--get', config
]
86 process
= subprocess
.Popen(cmd
, stdout
=subprocess
.PIPE
)
87 output
, _
= process
.communicate()
92 def __init__(self
, path
):
102 if not os
.path
.exists(self
.path
):
105 tmp
= json
.load(open(self
.path
))
107 self
.tips
= tmp
['tips']
108 self
.marks
= tmp
['marks']
109 self
.last_mark
= tmp
['last-mark']
111 for rev
, mark
in self
.marks
.iteritems():
112 self
.rev_marks
[mark
] = int(rev
)
115 return { 'tips': self
.tips
, 'marks': self
.marks
, 'last-mark' : self
.last_mark
}
118 json
.dump(self
.dict(), open(self
.path
, 'w'))
121 return str(self
.dict())
123 def from_rev(self
, rev
):
124 return self
.marks
[str(rev
)]
126 def to_rev(self
, mark
):
127 return self
.rev_marks
[mark
]
129 def get_mark(self
, rev
):
131 self
.marks
[str(rev
)] = self
.last_mark
132 return self
.last_mark
134 def new_mark(self
, rev
, mark
):
135 self
.marks
[str(rev
)] = mark
136 self
.rev_marks
[mark
] = rev
137 self
.last_mark
= mark
139 def is_marked(self
, rev
):
140 return str(rev
) in self
.marks
142 def get_tip(self
, branch
):
143 return self
.tips
.get(branch
, 0)
145 def set_tip(self
, branch
, tip
):
146 self
.tips
[branch
] = tip
150 def __init__(self
, repo
):
152 self
.line
= self
.get_line()
155 return sys
.stdin
.readline().strip()
157 def __getitem__(self
, i
):
158 return self
.line
.split()[i
]
160 def check(self
, word
):
161 return self
.line
.startswith(word
)
163 def each_block(self
, separator
):
164 while self
.line
!= separator
:
166 self
.line
= self
.get_line()
169 return self
.each_block('')
172 self
.line
= self
.get_line()
173 if self
.line
== 'done':
177 i
= self
.line
.index(':') + 1
178 return int(self
.line
[i
:])
181 if not self
.check('data'):
183 i
= self
.line
.index(' ') + 1
184 size
= int(self
.line
[i
:])
185 return sys
.stdin
.read(size
)
187 def get_author(self
):
191 m
= RAW_AUTHOR_RE
.match(self
.line
)
194 _
, name
, email
, date
, tz
= m
.groups()
195 if name
and 'ext:' in name
:
196 m
= re
.match('^(.+?) ext:\((.+)\)$', name
)
199 ex
= urllib
.unquote(m
.group(2))
201 if email
!= bad_mail
:
203 user
= '%s <%s>' % (name
, email
)
205 user
= '<%s>' % (email
)
213 tz
= ((tz
/ 100) * 3600) + ((tz
% 100) * 60)
214 return (user
, int(date
), -tz
)
216 def fix_file_path(path
):
217 if not os
.path
.isabs(path
):
219 return os
.path
.relpath(path
, '/')
223 path
= fix_file_path(fc
.path())
224 print "M %s inline %s" % (gitmode(fc
.flags()), path
)
225 print "data %d" % len(d
)
228 def get_filechanges(repo
, ctx
, parent
):
233 # load earliest manifest first for caching reasons
234 prev
= repo
[parent
].manifest().copy()
239 if (cur
.flags(fn
) != prev
.flags(fn
) or cur
[fn
] != prev
[fn
]):
244 removed |
= set(prev
.keys())
246 return added | modified
, removed
248 def fixup_user_git(user
):
250 user
= user
.replace('"', '')
251 m
= AUTHOR_RE
.match(user
)
254 mail
= m
.group(2).strip()
256 m
= EMAIL_RE
.match(user
)
261 m
= NAME_RE
.match(user
)
263 name
= m
.group(1).strip()
266 def fixup_user_hg(user
):
268 # stole this from hg-git
269 return re
.sub('[<>\n]', '?', name
.lstrip('< ').rstrip('> '))
271 m
= AUTHOR_HG_RE
.match(user
)
273 name
= sanitize(m
.group(1))
274 mail
= sanitize(m
.group(2))
277 name
+= ' ext:(' + urllib
.quote(ex
) + ')'
279 name
= sanitize(user
)
287 def fixup_user(user
):
288 global mode
, bad_mail
291 name
, mail
= fixup_user_git(user
)
293 name
, mail
= fixup_user_hg(user
)
300 return '%s <%s>' % (name
, mail
)
302 def get_repo(url
, alias
):
306 myui
.setconfig('ui', 'interactive', 'off')
307 myui
.fout
= sys
.stderr
310 if get_config('remote-hg.insecure') == 'true\n':
311 myui
.setconfig('web', 'cacerts', '')
312 except subprocess
.CalledProcessError
:
316 mod
= extensions
.load(myui
, 'hgext.schemes', None)
322 repo
= hg
.repository(myui
, url
)
324 local_path
= os
.path
.join(dirname
, 'clone')
325 if not os
.path
.exists(local_path
):
327 peer
, dstpeer
= hg
.clone(myui
, {}, url
, local_path
, update
=True, pull
=True)
329 die('Repository error')
330 repo
= dstpeer
.local()
332 repo
= hg
.repository(myui
, local_path
)
334 peer
= hg
.peer(myui
, {}, url
)
336 die('Repository error')
337 repo
.pull(peer
, heads
=None, force
=True)
341 def rev_to_mark(rev
):
343 return marks
.from_rev(rev
)
345 def mark_to_rev(mark
):
347 return marks
.to_rev(mark
)
349 def export_ref(repo
, name
, kind
, head
):
350 global prefix
, marks
, mode
352 ename
= '%s/%s' % (kind
, name
)
353 tip
= marks
.get_tip(ename
)
355 # mercurial takes too much time checking this
356 if tip
and tip
== head
.rev():
359 revs
= xrange(tip
, head
.rev() + 1)
362 revs
= [rev
for rev
in revs
if not marks
.is_marked(rev
)]
367 (manifest
, user
, (time
, tz
), files
, desc
, extra
) = repo
.changelog
.read(c
.node())
368 rev_branch
= extra
['branch']
370 author
= "%s %d %s" % (fixup_user(user
), time
, gittz(tz
))
371 if 'committer' in extra
:
372 user
, time
, tz
= extra
['committer'].rsplit(' ', 2)
373 committer
= "%s %s %s" % (user
, time
, gittz(int(tz
)))
377 parents
= [p
for p
in repo
.changelog
.parentrevs(rev
) if p
>= 0]
379 if len(parents
) == 0:
380 modified
= c
.manifest().keys()
383 modified
, removed
= get_filechanges(repo
, c
, parents
[0])
390 if rev_branch
!= 'default':
391 extra_msg
+= 'branch : %s\n' % rev_branch
395 if f
not in c
.manifest():
397 rename
= c
.filectx(f
).renamed()
399 renames
.append((rename
[0], f
))
402 extra_msg
+= "rename : %s => %s\n" % e
404 for key
, value
in extra
.iteritems():
405 if key
in ('author', 'committer', 'encoding', 'message', 'branch', 'hg-git'):
408 extra_msg
+= "extra : %s : %s\n" % (key
, urllib
.quote(value
))
411 desc
+= '\n--HG--\n' + extra_msg
413 if len(parents
) == 0 and rev
:
414 print 'reset %s/%s' % (prefix
, ename
)
416 print "commit %s/%s" % (prefix
, ename
)
417 print "mark :%d" % (marks
.get_mark(rev
))
418 print "author %s" % (author
)
419 print "committer %s" % (committer
)
420 print "data %d" % (len(desc
))
424 print "from :%s" % (rev_to_mark(parents
[0]))
426 print "merge :%s" % (rev_to_mark(parents
[1]))
429 export_file(c
.filectx(f
))
431 print "D %s" % (fix_file_path(f
))
435 if (count
% 100 == 0):
436 print "progress revision %d '%s' (%d/%d)" % (rev
, name
, count
, len(revs
))
437 print "#############################################################"
439 # make sure the ref is updated
440 print "reset %s/%s" % (prefix
, ename
)
441 print "from :%u" % rev_to_mark(rev
)
444 marks
.set_tip(ename
, rev
)
446 def export_tag(repo
, tag
):
447 export_ref(repo
, tag
, 'tags', repo
[hgref(tag
)])
449 def export_bookmark(repo
, bmark
):
450 head
= bmarks
[hgref(bmark
)]
451 export_ref(repo
, bmark
, 'bookmarks', head
)
453 def export_branch(repo
, branch
):
454 tip
= get_branch_tip(repo
, branch
)
456 export_ref(repo
, branch
, 'branches', head
)
458 def export_head(repo
):
460 export_ref(repo
, g_head
[0], 'bookmarks', g_head
[1])
462 def do_capabilities(parser
):
463 global prefix
, dirname
467 print "refspec refs/heads/branches/*:%s/branches/*" % prefix
468 print "refspec refs/heads/*:%s/bookmarks/*" % prefix
469 print "refspec refs/tags/*:%s/tags/*" % prefix
471 path
= os
.path
.join(dirname
, 'marks-git')
473 if os
.path
.exists(path
):
474 print "*import-marks %s" % path
475 print "*export-marks %s" % path
479 def branch_tip(repo
, branch
):
480 # older versions of mercurial don't have this
481 if hasattr(repo
, 'branchtip'):
482 return repo
.branchtip(branch
)
484 return repo
.branchtags()[branch
]
486 def get_branch_tip(repo
, branch
):
489 heads
= branches
.get(hgref(branch
), None)
493 # verify there's only one head
495 warn("Branch '%s' has more than one head, consider merging" % branch
)
496 return branch_tip(repo
, hgref(branch
))
500 def list_head(repo
, cur
):
501 global g_head
, bmarks
503 head
= bookmarks
.readcurrent(repo
)
507 # fake bookmark from current branch
514 if head
== 'default':
519 print "@refs/heads/%s HEAD" % head
520 g_head
= (head
, node
)
523 global branches
, bmarks
, mode
, track_branches
526 for bmark
, node
in bookmarks
.listbookmarks(repo
).iteritems():
527 bmarks
[bmark
] = repo
[node
]
529 cur
= repo
.dirstate
.branch()
534 for branch
in repo
.branchmap():
535 heads
= repo
.branchheads(branch
)
537 branches
[branch
] = heads
539 for branch
in branches
:
540 print "? refs/heads/branches/%s" % gitref(branch
)
543 print "? refs/heads/%s" % gitref(bmark
)
545 for tag
, node
in repo
.tagslist():
548 print "? refs/tags/%s" % gitref(tag
)
552 def do_import(parser
):
555 path
= os
.path
.join(dirname
, 'marks-git')
558 if os
.path
.exists(path
):
559 print "feature import-marks=%s" % path
560 print "feature export-marks=%s" % path
563 tmp
= encoding
.encoding
564 encoding
.encoding
= 'utf-8'
566 # lets get all the import lines
567 while parser
.check('import'):
572 elif ref
.startswith('refs/heads/branches/'):
573 branch
= ref
[len('refs/heads/branches/'):]
574 export_branch(repo
, branch
)
575 elif ref
.startswith('refs/heads/'):
576 bmark
= ref
[len('refs/heads/'):]
577 export_bookmark(repo
, bmark
)
578 elif ref
.startswith('refs/tags/'):
579 tag
= ref
[len('refs/tags/'):]
580 export_tag(repo
, tag
)
584 encoding
.encoding
= tmp
588 def parse_blob(parser
):
592 mark
= parser
.get_mark()
594 data
= parser
.get_data()
595 blob_marks
[mark
] = data
598 def get_merge_files(repo
, p1
, p2
, files
):
599 for e
in repo
[p1
].files():
601 if e
not in repo
[p1
].manifest():
603 f
= { 'ctx' : repo
[p1
][e
] }
606 def parse_commit(parser
):
607 global marks
, blob_marks
, parsed_refs
610 from_mark
= merge_mark
= None
615 commit_mark
= parser
.get_mark()
617 author
= parser
.get_author()
619 committer
= parser
.get_author()
621 data
= parser
.get_data()
623 if parser
.check('from'):
624 from_mark
= parser
.get_mark()
626 if parser
.check('merge'):
627 merge_mark
= parser
.get_mark()
629 if parser
.check('merge'):
630 die('octopus merges are not supported yet')
635 if parser
.check('M'):
636 t
, m
, mark_ref
, path
= line
.split(' ', 3)
637 mark
= int(mark_ref
[1:])
638 f
= { 'mode' : hgmode(m
), 'data' : blob_marks
[mark
] }
639 elif parser
.check('D'):
640 t
, path
= line
.split(' ', 1)
641 f
= { 'deleted' : True }
643 die('Unknown file command: %s' % line
)
646 def getfilectx(repo
, memctx
, f
):
652 is_exec
= of
['mode'] == 'x'
653 is_link
= of
['mode'] == 'l'
654 rename
= of
.get('rename', None)
655 return context
.memfilectx(f
, of
['data'],
656 is_link
, is_exec
, rename
)
660 user
, date
, tz
= author
663 if committer
!= author
:
664 extra
['committer'] = "%s %u %u" % committer
667 p1
= repo
.changelog
.node(mark_to_rev(from_mark
))
672 p2
= repo
.changelog
.node(mark_to_rev(merge_mark
))
677 # If files changed from any of the parents, hg wants to know, but in git if
678 # nothing changed from the first parent, nothing changed.
681 get_merge_files(repo
, p1
, p2
, files
)
683 # Check if the ref is supposed to be a named branch
684 if ref
.startswith('refs/heads/branches/'):
685 branch
= ref
[len('refs/heads/branches/'):]
686 extra
['branch'] = hgref(branch
)
689 i
= data
.find('\n--HG--\n')
691 tmp
= data
[i
+ len('\n--HG--\n'):].strip()
692 for k
, v
in [e
.split(' : ', 1) for e
in tmp
.split('\n')]:
694 old
, new
= v
.split(' => ', 1)
695 files
[new
]['rename'] = old
699 ek
, ev
= v
.split(' : ', 1)
700 extra
[ek
] = urllib
.unquote(ev
)
703 ctx
= context
.memctx(repo
, (p1
, p2
), data
,
704 files
.keys(), getfilectx
,
705 user
, (date
, tz
), extra
)
707 tmp
= encoding
.encoding
708 encoding
.encoding
= 'utf-8'
710 node
= repo
.commitctx(ctx
)
712 encoding
.encoding
= tmp
714 rev
= repo
[node
].rev()
716 parsed_refs
[ref
] = node
717 marks
.new_mark(rev
, commit_mark
)
719 def parse_reset(parser
):
725 if parser
.check('commit'):
728 if not parser
.check('from'):
730 from_mark
= parser
.get_mark()
733 node
= parser
.repo
.changelog
.node(mark_to_rev(from_mark
))
734 parsed_refs
[ref
] = node
736 def parse_tag(parser
):
739 from_mark
= parser
.get_mark()
741 tagger
= parser
.get_author()
743 data
= parser
.get_data()
746 parsed_tags
[name
] = (tagger
, data
)
748 def write_tag(repo
, tag
, node
, msg
, author
):
749 branch
= repo
[node
].branch()
750 tip
= branch_tip(repo
, branch
)
753 def getfilectx(repo
, memctx
, f
):
755 fctx
= tip
.filectx(f
)
757 except error
.ManifestLookupError
:
759 content
= data
+ "%s %s\n" % (hghex(node
), tag
)
760 return context
.memfilectx(f
, content
, False, False, None)
765 author
= (None, 0, 0)
766 user
, date
, tz
= author
768 ctx
= context
.memctx(repo
, (p1
, p2
), msg
,
769 ['.hgtags'], getfilectx
,
770 user
, (date
, tz
), {'branch' : branch
})
772 tmp
= encoding
.encoding
773 encoding
.encoding
= 'utf-8'
775 tagnode
= repo
.commitctx(ctx
)
777 encoding
.encoding
= tmp
781 def do_export(parser
):
782 global parsed_refs
, bmarks
, peer
788 for line
in parser
.each_block('done'):
789 if parser
.check('blob'):
791 elif parser
.check('commit'):
793 elif parser
.check('reset'):
795 elif parser
.check('tag'):
797 elif parser
.check('feature'):
800 die('unhandled export command: %s' % line
)
802 for ref
, node
in parsed_refs
.iteritems():
803 if ref
.startswith('refs/heads/branches'):
804 branch
= ref
[len('refs/heads/branches/'):]
805 if branch
in branches
and node
in branches
[branch
]:
809 elif ref
.startswith('refs/heads/'):
810 bmark
= ref
[len('refs/heads/'):]
811 p_bmarks
.append((bmark
, node
))
813 elif ref
.startswith('refs/tags/'):
814 tag
= ref
[len('refs/tags/'):]
816 author
, msg
= parsed_tags
.get(tag
, (None, None))
819 msg
= 'Added tag %s for changeset %s' % (tag
, hghex(node
[:6]));
820 write_tag(parser
.repo
, tag
, node
, msg
, author
)
822 fp
= parser
.repo
.opener('localtags', 'a')
823 fp
.write('%s %s\n' % (hghex(node
), tag
))
827 # transport-helper/fast-export bugs
831 parser
.repo
.push(peer
, force
=force_push
)
834 for bmark
, node
in p_bmarks
:
835 ref
= 'refs/heads/' + bmark
839 old
= bmarks
[bmark
].hex()
846 if bmark
== 'master' and 'master' not in parser
.repo
._bookmarks
:
849 elif bookmarks
.pushbookmark(parser
.repo
, bmark
, old
, new
):
853 print "error %s" % ref
857 rb
= peer
.listkeys('bookmarks')
858 old
= rb
.get(bmark
, '')
859 if not peer
.pushkey('bookmarks', bmark
, old
, new
):
860 print "error %s" % ref
867 def fix_path(alias
, repo
, orig_url
):
868 url
= urlparse
.urlparse(orig_url
, 'file')
869 if url
.scheme
!= 'file' or os
.path
.isabs(url
.path
):
871 abs_url
= urlparse
.urljoin("%s/" % os
.getcwd(), orig_url
)
872 cmd
= ['git', 'config', 'remote.%s.url' % alias
, "hg::%s" % abs_url
]
876 global prefix
, dirname
, branches
, bmarks
877 global marks
, blob_marks
, parsed_refs
878 global peer
, mode
, bad_mail
, bad_name
879 global track_branches
, force_push
, is_tmp
886 hg_git_compat
= False
887 track_branches
= True
891 if get_config('remote-hg.hg-git-compat') == 'true\n':
893 track_branches
= False
894 if get_config('remote-hg.track-branches') == 'false\n':
895 track_branches
= False
896 if get_config('remote-hg.force-push') == 'false\n':
898 except subprocess
.CalledProcessError
:
903 bad_mail
= 'none@none'
912 alias
= util
.sha1(alias
).hexdigest()
916 gitdir
= os
.environ
['GIT_DIR']
917 dirname
= os
.path
.join(gitdir
, 'hg', alias
)
925 repo
= get_repo(url
, alias
)
926 prefix
= 'refs/hg/%s' % alias
929 fix_path(alias
, peer
or repo
, url
)
931 if not os
.path
.exists(dirname
):
934 marks_path
= os
.path
.join(dirname
, 'marks-hg')
935 marks
= Marks(marks_path
)
937 parser
= Parser(repo
)
939 if parser
.check('capabilities'):
940 do_capabilities(parser
)
941 elif parser
.check('list'):
943 elif parser
.check('import'):
945 elif parser
.check('export'):
948 die('unhandled command: %s' % line
)
957 shutil
.rmtree(dirname
)
960 sys
.exit(main(sys
.argv
))