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
, encoding
, node
, error
, extensions
25 import urlparse
, hashlib
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
]
131 return self
.last_mark
133 def get_mark(self
, rev
):
135 self
.marks
[str(rev
)] = self
.last_mark
136 return self
.last_mark
138 def new_mark(self
, rev
, mark
):
139 self
.marks
[str(rev
)] = mark
140 self
.rev_marks
[mark
] = rev
141 self
.last_mark
= mark
143 def is_marked(self
, rev
):
144 return str(rev
) in self
.marks
146 def get_tip(self
, branch
):
147 return self
.tips
.get(branch
, 0)
149 def set_tip(self
, branch
, tip
):
150 self
.tips
[branch
] = tip
154 def __init__(self
, repo
):
156 self
.line
= self
.get_line()
159 return sys
.stdin
.readline().strip()
161 def __getitem__(self
, i
):
162 return self
.line
.split()[i
]
164 def check(self
, word
):
165 return self
.line
.startswith(word
)
167 def each_block(self
, separator
):
168 while self
.line
!= separator
:
170 self
.line
= self
.get_line()
173 return self
.each_block('')
176 self
.line
= self
.get_line()
177 if self
.line
== 'done':
181 i
= self
.line
.index(':') + 1
182 return int(self
.line
[i
:])
185 if not self
.check('data'):
187 i
= self
.line
.index(' ') + 1
188 size
= int(self
.line
[i
:])
189 return sys
.stdin
.read(size
)
191 def get_author(self
):
195 m
= RAW_AUTHOR_RE
.match(self
.line
)
198 _
, name
, email
, date
, tz
= m
.groups()
199 if name
and 'ext:' in name
:
200 m
= re
.match('^(.+?) ext:\((.+)\)$', name
)
203 ex
= urllib
.unquote(m
.group(2))
205 if email
!= bad_mail
:
207 user
= '%s <%s>' % (name
, email
)
209 user
= '<%s>' % (email
)
217 tz
= ((tz
/ 100) * 3600) + ((tz
% 100) * 60)
218 return (user
, int(date
), -tz
)
220 def fix_file_path(path
):
221 if not os
.path
.isabs(path
):
223 return os
.path
.relpath(path
, '/')
225 def export_files(files
):
226 global marks
, filenodes
230 fid
= node
.hex(f
.filenode())
233 mark
= filenodes
[fid
]
235 mark
= marks
.next_mark()
236 filenodes
[fid
] = mark
240 print "mark :%u" % mark
241 print "data %d" % len(d
)
244 path
= fix_file_path(f
.path())
245 final
.append((gitmode(f
.flags()), mark
, path
))
249 def get_filechanges(repo
, ctx
, parent
):
254 # load earliest manifest first for caching reasons
255 prev
= repo
[parent
].manifest().copy()
260 if (cur
.flags(fn
) != prev
.flags(fn
) or cur
[fn
] != prev
[fn
]):
265 removed |
= set(prev
.keys())
267 return added | modified
, removed
269 def fixup_user_git(user
):
271 user
= user
.replace('"', '')
272 m
= AUTHOR_RE
.match(user
)
275 mail
= m
.group(2).strip()
277 m
= EMAIL_RE
.match(user
)
282 m
= NAME_RE
.match(user
)
284 name
= m
.group(1).strip()
287 def fixup_user_hg(user
):
289 # stole this from hg-git
290 return re
.sub('[<>\n]', '?', name
.lstrip('< ').rstrip('> '))
292 m
= AUTHOR_HG_RE
.match(user
)
294 name
= sanitize(m
.group(1))
295 mail
= sanitize(m
.group(2))
298 name
+= ' ext:(' + urllib
.quote(ex
) + ')'
300 name
= sanitize(user
)
308 def fixup_user(user
):
309 global mode
, bad_mail
312 name
, mail
= fixup_user_git(user
)
314 name
, mail
= fixup_user_hg(user
)
321 return '%s <%s>' % (name
, mail
)
323 def get_repo(url
, alias
):
327 myui
.setconfig('ui', 'interactive', 'off')
328 myui
.fout
= sys
.stderr
330 if get_config('remote-hg.insecure') == 'true\n':
331 myui
.setconfig('web', 'cacerts', '')
334 mod
= extensions
.load(myui
, 'hgext.schemes', None)
340 repo
= hg
.repository(myui
, url
)
342 local_path
= os
.path
.join(dirname
, 'clone')
343 if not os
.path
.exists(local_path
):
345 peer
, dstpeer
= hg
.clone(myui
, {}, url
, local_path
, update
=True, pull
=True)
347 die('Repository error')
348 repo
= dstpeer
.local()
350 repo
= hg
.repository(myui
, local_path
)
352 peer
= hg
.peer(myui
, {}, url
)
354 die('Repository error')
355 repo
.pull(peer
, heads
=None, force
=True)
359 def rev_to_mark(rev
):
361 return marks
.from_rev(rev
)
363 def mark_to_rev(mark
):
365 return marks
.to_rev(mark
)
367 def export_ref(repo
, name
, kind
, head
):
368 global prefix
, marks
, mode
370 ename
= '%s/%s' % (kind
, name
)
371 tip
= marks
.get_tip(ename
)
373 revs
= xrange(tip
, head
.rev() + 1)
376 revs
= [rev
for rev
in revs
if not marks
.is_marked(rev
)]
381 (manifest
, user
, (time
, tz
), files
, desc
, extra
) = repo
.changelog
.read(c
.node())
382 rev_branch
= extra
['branch']
384 author
= "%s %d %s" % (fixup_user(user
), time
, gittz(tz
))
385 if 'committer' in extra
:
386 user
, time
, tz
= extra
['committer'].rsplit(' ', 2)
387 committer
= "%s %s %s" % (user
, time
, gittz(int(tz
)))
391 parents
= [p
for p
in repo
.changelog
.parentrevs(rev
) if p
>= 0]
393 if len(parents
) == 0:
394 modified
= c
.manifest().keys()
397 modified
, removed
= get_filechanges(repo
, c
, parents
[0])
404 if rev_branch
!= 'default':
405 extra_msg
+= 'branch : %s\n' % rev_branch
409 if f
not in c
.manifest():
411 rename
= c
.filectx(f
).renamed()
413 renames
.append((rename
[0], f
))
416 extra_msg
+= "rename : %s => %s\n" % e
418 for key
, value
in extra
.iteritems():
419 if key
in ('author', 'committer', 'encoding', 'message', 'branch', 'hg-git'):
422 extra_msg
+= "extra : %s : %s\n" % (key
, urllib
.quote(value
))
425 desc
+= '\n--HG--\n' + extra_msg
427 if len(parents
) == 0 and rev
:
428 print 'reset %s/%s' % (prefix
, ename
)
430 modified_final
= export_files(c
.filectx(f
) for f
in modified
)
432 print "commit %s/%s" % (prefix
, ename
)
433 print "mark :%d" % (marks
.get_mark(rev
))
434 print "author %s" % (author
)
435 print "committer %s" % (committer
)
436 print "data %d" % (len(desc
))
440 print "from :%s" % (rev_to_mark(parents
[0]))
442 print "merge :%s" % (rev_to_mark(parents
[1]))
444 for f
in modified_final
:
445 print "M %s :%u %s" % f
447 print "D %s" % (fix_file_path(f
))
451 if (count
% 100 == 0):
452 print "progress revision %d '%s' (%d/%d)" % (rev
, name
, count
, len(revs
))
454 # make sure the ref is updated
455 print "reset %s/%s" % (prefix
, ename
)
456 print "from :%u" % rev_to_mark(rev
)
459 marks
.set_tip(ename
, rev
)
461 def export_tag(repo
, tag
):
462 export_ref(repo
, tag
, 'tags', repo
[hgref(tag
)])
464 def export_bookmark(repo
, bmark
):
465 head
= bmarks
[hgref(bmark
)]
466 export_ref(repo
, bmark
, 'bookmarks', head
)
468 def export_branch(repo
, branch
):
469 tip
= get_branch_tip(repo
, branch
)
471 export_ref(repo
, branch
, 'branches', head
)
473 def export_head(repo
):
475 export_ref(repo
, g_head
[0], 'bookmarks', g_head
[1])
477 def do_capabilities(parser
):
478 global prefix
, dirname
482 print "refspec refs/heads/branches/*:%s/branches/*" % prefix
483 print "refspec refs/heads/*:%s/bookmarks/*" % prefix
484 print "refspec refs/tags/*:%s/tags/*" % prefix
486 path
= os
.path
.join(dirname
, 'marks-git')
488 if os
.path
.exists(path
):
489 print "*import-marks %s" % path
490 print "*export-marks %s" % path
494 def branch_tip(repo
, branch
):
495 # older versions of mercurial don't have this
496 if hasattr(repo
, 'branchtip'):
497 return repo
.branchtip(branch
)
499 return repo
.branchtags()[branch
]
501 def get_branch_tip(repo
, branch
):
504 heads
= branches
.get(hgref(branch
), None)
508 # verify there's only one head
510 warn("Branch '%s' has more than one head, consider merging" % branch
)
511 return branch_tip(repo
, hgref(branch
))
515 def list_head(repo
, cur
):
516 global g_head
, bmarks
518 head
= bookmarks
.readcurrent(repo
)
522 # fake bookmark from current branch
529 if head
== 'default':
534 print "@refs/heads/%s HEAD" % head
535 g_head
= (head
, node
)
538 global branches
, bmarks
, track_branches
541 for bmark
, node
in bookmarks
.listbookmarks(repo
).iteritems():
542 bmarks
[bmark
] = repo
[node
]
544 cur
= repo
.dirstate
.branch()
549 for branch
in repo
.branchmap():
550 heads
= repo
.branchheads(branch
)
552 branches
[branch
] = heads
554 for branch
in branches
:
555 print "? refs/heads/branches/%s" % gitref(branch
)
558 print "? refs/heads/%s" % gitref(bmark
)
560 for tag
, node
in repo
.tagslist():
563 print "? refs/tags/%s" % gitref(tag
)
567 def do_import(parser
):
570 path
= os
.path
.join(dirname
, 'marks-git')
573 if os
.path
.exists(path
):
574 print "feature import-marks=%s" % path
575 print "feature export-marks=%s" % path
578 tmp
= encoding
.encoding
579 encoding
.encoding
= 'utf-8'
581 # lets get all the import lines
582 while parser
.check('import'):
587 elif ref
.startswith('refs/heads/branches/'):
588 branch
= ref
[len('refs/heads/branches/'):]
589 export_branch(repo
, branch
)
590 elif ref
.startswith('refs/heads/'):
591 bmark
= ref
[len('refs/heads/'):]
592 export_bookmark(repo
, bmark
)
593 elif ref
.startswith('refs/tags/'):
594 tag
= ref
[len('refs/tags/'):]
595 export_tag(repo
, tag
)
599 encoding
.encoding
= tmp
603 def parse_blob(parser
):
607 mark
= parser
.get_mark()
609 data
= parser
.get_data()
610 blob_marks
[mark
] = data
613 def get_merge_files(repo
, p1
, p2
, files
):
614 for e
in repo
[p1
].files():
616 if e
not in repo
[p1
].manifest():
618 f
= { 'ctx' : repo
[p1
][e
] }
621 def parse_commit(parser
):
622 global marks
, blob_marks
, parsed_refs
625 from_mark
= merge_mark
= None
630 commit_mark
= parser
.get_mark()
632 author
= parser
.get_author()
634 committer
= parser
.get_author()
636 data
= parser
.get_data()
638 if parser
.check('from'):
639 from_mark
= parser
.get_mark()
641 if parser
.check('merge'):
642 merge_mark
= parser
.get_mark()
644 if parser
.check('merge'):
645 die('octopus merges are not supported yet')
647 # fast-export adds an extra newline
654 if parser
.check('M'):
655 t
, m
, mark_ref
, path
= line
.split(' ', 3)
656 mark
= int(mark_ref
[1:])
657 f
= { 'mode' : hgmode(m
), 'data' : blob_marks
[mark
] }
658 elif parser
.check('D'):
659 t
, path
= line
.split(' ', 1)
660 f
= { 'deleted' : True }
662 die('Unknown file command: %s' % line
)
665 def getfilectx(repo
, memctx
, f
):
671 is_exec
= of
['mode'] == 'x'
672 is_link
= of
['mode'] == 'l'
673 rename
= of
.get('rename', None)
674 return context
.memfilectx(f
, of
['data'],
675 is_link
, is_exec
, rename
)
679 user
, date
, tz
= author
682 if committer
!= author
:
683 extra
['committer'] = "%s %u %u" % committer
686 p1
= repo
.changelog
.node(mark_to_rev(from_mark
))
691 p2
= repo
.changelog
.node(mark_to_rev(merge_mark
))
696 # If files changed from any of the parents, hg wants to know, but in git if
697 # nothing changed from the first parent, nothing changed.
700 get_merge_files(repo
, p1
, p2
, files
)
702 # Check if the ref is supposed to be a named branch
703 if ref
.startswith('refs/heads/branches/'):
704 branch
= ref
[len('refs/heads/branches/'):]
705 extra
['branch'] = hgref(branch
)
708 i
= data
.find('\n--HG--\n')
710 tmp
= data
[i
+ len('\n--HG--\n'):].strip()
711 for k
, v
in [e
.split(' : ', 1) for e
in tmp
.split('\n')]:
713 old
, new
= v
.split(' => ', 1)
714 files
[new
]['rename'] = old
718 ek
, ev
= v
.split(' : ', 1)
719 extra
[ek
] = urllib
.unquote(ev
)
722 ctx
= context
.memctx(repo
, (p1
, p2
), data
,
723 files
.keys(), getfilectx
,
724 user
, (date
, tz
), extra
)
726 tmp
= encoding
.encoding
727 encoding
.encoding
= 'utf-8'
729 node
= repo
.commitctx(ctx
)
731 encoding
.encoding
= tmp
733 rev
= repo
[node
].rev()
735 parsed_refs
[ref
] = node
736 marks
.new_mark(rev
, commit_mark
)
738 def parse_reset(parser
):
744 if parser
.check('commit'):
747 if not parser
.check('from'):
749 from_mark
= parser
.get_mark()
752 node
= parser
.repo
.changelog
.node(mark_to_rev(from_mark
))
753 parsed_refs
[ref
] = node
755 def parse_tag(parser
):
758 from_mark
= parser
.get_mark()
760 tagger
= parser
.get_author()
762 data
= parser
.get_data()
765 parsed_tags
[name
] = (tagger
, data
)
767 def write_tag(repo
, tag
, node
, msg
, author
):
768 branch
= repo
[node
].branch()
769 tip
= branch_tip(repo
, branch
)
772 def getfilectx(repo
, memctx
, f
):
774 fctx
= tip
.filectx(f
)
776 except error
.ManifestLookupError
:
778 content
= data
+ "%s %s\n" % (hghex(node
), tag
)
779 return context
.memfilectx(f
, content
, False, False, None)
784 author
= (None, 0, 0)
785 user
, date
, tz
= author
787 ctx
= context
.memctx(repo
, (p1
, p2
), msg
,
788 ['.hgtags'], getfilectx
,
789 user
, (date
, tz
), {'branch' : branch
})
791 tmp
= encoding
.encoding
792 encoding
.encoding
= 'utf-8'
794 tagnode
= repo
.commitctx(ctx
)
796 encoding
.encoding
= tmp
800 def do_export(parser
):
801 global parsed_refs
, bmarks
, peer
807 for line
in parser
.each_block('done'):
808 if parser
.check('blob'):
810 elif parser
.check('commit'):
812 elif parser
.check('reset'):
814 elif parser
.check('tag'):
816 elif parser
.check('feature'):
819 die('unhandled export command: %s' % line
)
821 for ref
, node
in parsed_refs
.iteritems():
822 if ref
.startswith('refs/heads/branches'):
823 branch
= ref
[len('refs/heads/branches/'):]
824 if branch
in branches
and node
in branches
[branch
]:
828 elif ref
.startswith('refs/heads/'):
829 bmark
= ref
[len('refs/heads/'):]
830 p_bmarks
.append((bmark
, node
))
832 elif ref
.startswith('refs/tags/'):
833 tag
= ref
[len('refs/tags/'):]
835 author
, msg
= parsed_tags
.get(tag
, (None, None))
838 msg
= 'Added tag %s for changeset %s' % (tag
, hghex(node
[:6]));
839 write_tag(parser
.repo
, tag
, node
, msg
, author
)
841 fp
= parser
.repo
.opener('localtags', 'a')
842 fp
.write('%s %s\n' % (hghex(node
), tag
))
846 # transport-helper/fast-export bugs
850 parser
.repo
.push(peer
, force
=force_push
)
853 for bmark
, node
in p_bmarks
:
854 ref
= 'refs/heads/' + bmark
858 old
= bmarks
[bmark
].hex()
865 if bmark
== 'master' and 'master' not in parser
.repo
._bookmarks
:
868 elif bookmarks
.pushbookmark(parser
.repo
, bmark
, old
, new
):
872 print "error %s" % ref
876 rb
= peer
.listkeys('bookmarks')
877 old
= rb
.get(bmark
, '')
878 if not peer
.pushkey('bookmarks', bmark
, old
, new
):
879 print "error %s" % ref
886 def fix_path(alias
, repo
, orig_url
):
887 url
= urlparse
.urlparse(orig_url
, 'file')
888 if url
.scheme
!= 'file' or os
.path
.isabs(url
.path
):
890 abs_url
= urlparse
.urljoin("%s/" % os
.getcwd(), orig_url
)
891 cmd
= ['git', 'config', 'remote.%s.url' % alias
, "hg::%s" % abs_url
]
895 global prefix
, dirname
, branches
, bmarks
896 global marks
, blob_marks
, parsed_refs
897 global peer
, mode
, bad_mail
, bad_name
898 global track_branches
, force_push
, is_tmp
906 hg_git_compat
= False
907 track_branches
= True
910 if get_config('remote-hg.hg-git-compat') == 'true\n':
912 track_branches
= False
913 if get_config('remote-hg.track-branches') == 'false\n':
914 track_branches
= False
915 if get_config('remote-hg.force-push') == 'false\n':
920 bad_mail
= 'none@none'
929 alias
= hashlib
.sha1(alias
).hexdigest()
933 gitdir
= os
.environ
['GIT_DIR']
934 dirname
= os
.path
.join(gitdir
, 'hg', alias
)
943 repo
= get_repo(url
, alias
)
944 prefix
= 'refs/hg/%s' % alias
947 fix_path(alias
, peer
or repo
, url
)
949 if not os
.path
.exists(dirname
):
952 marks_path
= os
.path
.join(dirname
, 'marks-hg')
953 marks
= Marks(marks_path
)
955 parser
= Parser(repo
)
957 if parser
.check('capabilities'):
958 do_capabilities(parser
)
959 elif parser
.check('list'):
961 elif parser
.check('import'):
963 elif parser
.check('export'):
966 die('unhandled command: %s' % line
)
975 shutil
.rmtree(dirname
)
978 sys
.exit(main(sys
.argv
))