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
):
234 prev
= repo
[parent
].manifest().copy()
238 if (cur
.flags(fn
) != prev
.flags(fn
) or cur
[fn
] != prev
[fn
]):
243 removed |
= set(prev
.keys())
245 return added | modified
, removed
247 def fixup_user_git(user
):
249 user
= user
.replace('"', '')
250 m
= AUTHOR_RE
.match(user
)
253 mail
= m
.group(2).strip()
255 m
= EMAIL_RE
.match(user
)
260 m
= NAME_RE
.match(user
)
262 name
= m
.group(1).strip()
265 def fixup_user_hg(user
):
267 # stole this from hg-git
268 return re
.sub('[<>\n]', '?', name
.lstrip('< ').rstrip('> '))
270 m
= AUTHOR_HG_RE
.match(user
)
272 name
= sanitize(m
.group(1))
273 mail
= sanitize(m
.group(2))
276 name
+= ' ext:(' + urllib
.quote(ex
) + ')'
278 name
= sanitize(user
)
286 def fixup_user(user
):
287 global mode
, bad_mail
290 name
, mail
= fixup_user_git(user
)
292 name
, mail
= fixup_user_hg(user
)
299 return '%s <%s>' % (name
, mail
)
301 def get_repo(url
, alias
):
305 myui
.setconfig('ui', 'interactive', 'off')
306 myui
.fout
= sys
.stderr
309 if get_config('remote-hg.insecure') == 'true\n':
310 myui
.setconfig('web', 'cacerts', '')
311 except subprocess
.CalledProcessError
:
315 mod
= extensions
.load(myui
, 'hgext.schemes', None)
321 repo
= hg
.repository(myui
, url
)
323 local_path
= os
.path
.join(dirname
, 'clone')
324 if not os
.path
.exists(local_path
):
326 peer
, dstpeer
= hg
.clone(myui
, {}, url
, local_path
, update
=True, pull
=True)
328 die('Repository error')
329 repo
= dstpeer
.local()
331 repo
= hg
.repository(myui
, local_path
)
333 peer
= hg
.peer(myui
, {}, url
)
335 die('Repository error')
336 repo
.pull(peer
, heads
=None, force
=True)
340 def rev_to_mark(rev
):
342 return marks
.from_rev(rev
)
344 def mark_to_rev(mark
):
346 return marks
.to_rev(mark
)
348 def export_ref(repo
, name
, kind
, head
):
349 global prefix
, marks
, mode
351 ename
= '%s/%s' % (kind
, name
)
352 tip
= marks
.get_tip(ename
)
354 # mercurial takes too much time checking this
355 if tip
and tip
== head
.rev():
358 revs
= xrange(tip
, head
.rev() + 1)
361 revs
= [rev
for rev
in revs
if not marks
.is_marked(rev
)]
366 (manifest
, user
, (time
, tz
), files
, desc
, extra
) = repo
.changelog
.read(c
.node())
367 rev_branch
= extra
['branch']
369 author
= "%s %d %s" % (fixup_user(user
), time
, gittz(tz
))
370 if 'committer' in extra
:
371 user
, time
, tz
= extra
['committer'].rsplit(' ', 2)
372 committer
= "%s %s %s" % (user
, time
, gittz(int(tz
)))
376 parents
= [p
for p
in repo
.changelog
.parentrevs(rev
) if p
>= 0]
378 if len(parents
) == 0:
379 modified
= c
.manifest().keys()
382 modified
, removed
= get_filechanges(repo
, c
, parents
[0])
389 if rev_branch
!= 'default':
390 extra_msg
+= 'branch : %s\n' % rev_branch
394 if f
not in c
.manifest():
396 rename
= c
.filectx(f
).renamed()
398 renames
.append((rename
[0], f
))
401 extra_msg
+= "rename : %s => %s\n" % e
403 for key
, value
in extra
.iteritems():
404 if key
in ('author', 'committer', 'encoding', 'message', 'branch', 'hg-git'):
407 extra_msg
+= "extra : %s : %s\n" % (key
, urllib
.quote(value
))
410 desc
+= '\n--HG--\n' + extra_msg
412 if len(parents
) == 0 and rev
:
413 print 'reset %s/%s' % (prefix
, ename
)
415 print "commit %s/%s" % (prefix
, ename
)
416 print "mark :%d" % (marks
.get_mark(rev
))
417 print "author %s" % (author
)
418 print "committer %s" % (committer
)
419 print "data %d" % (len(desc
))
423 print "from :%s" % (rev_to_mark(parents
[0]))
425 print "merge :%s" % (rev_to_mark(parents
[1]))
428 export_file(c
.filectx(f
))
430 print "D %s" % (fix_file_path(f
))
434 if (count
% 100 == 0):
435 print "progress revision %d '%s' (%d/%d)" % (rev
, name
, count
, len(revs
))
436 print "#############################################################"
438 # make sure the ref is updated
439 print "reset %s/%s" % (prefix
, ename
)
440 print "from :%u" % rev_to_mark(rev
)
443 marks
.set_tip(ename
, rev
)
445 def export_tag(repo
, tag
):
446 export_ref(repo
, tag
, 'tags', repo
[hgref(tag
)])
448 def export_bookmark(repo
, bmark
):
449 head
= bmarks
[hgref(bmark
)]
450 export_ref(repo
, bmark
, 'bookmarks', head
)
452 def export_branch(repo
, branch
):
453 tip
= get_branch_tip(repo
, branch
)
455 export_ref(repo
, branch
, 'branches', head
)
457 def export_head(repo
):
459 export_ref(repo
, g_head
[0], 'bookmarks', g_head
[1])
461 def do_capabilities(parser
):
462 global prefix
, dirname
466 print "refspec refs/heads/branches/*:%s/branches/*" % prefix
467 print "refspec refs/heads/*:%s/bookmarks/*" % prefix
468 print "refspec refs/tags/*:%s/tags/*" % prefix
470 path
= os
.path
.join(dirname
, 'marks-git')
472 if os
.path
.exists(path
):
473 print "*import-marks %s" % path
474 print "*export-marks %s" % path
478 def branch_tip(repo
, branch
):
479 # older versions of mercurial don't have this
480 if hasattr(repo
, 'branchtip'):
481 return repo
.branchtip(branch
)
483 return repo
.branchtags()[branch
]
485 def get_branch_tip(repo
, branch
):
488 heads
= branches
.get(hgref(branch
), None)
492 # verify there's only one head
494 warn("Branch '%s' has more than one head, consider merging" % branch
)
495 return branch_tip(repo
, hgref(branch
))
499 def list_head(repo
, cur
):
500 global g_head
, bmarks
502 head
= bookmarks
.readcurrent(repo
)
506 # fake bookmark from current branch
513 if head
== 'default':
518 print "@refs/heads/%s HEAD" % head
519 g_head
= (head
, node
)
522 global branches
, bmarks
, mode
, track_branches
525 for bmark
, node
in bookmarks
.listbookmarks(repo
).iteritems():
526 bmarks
[bmark
] = repo
[node
]
528 cur
= repo
.dirstate
.branch()
533 for branch
in repo
.branchmap():
534 heads
= repo
.branchheads(branch
)
536 branches
[branch
] = heads
538 for branch
in branches
:
539 print "? refs/heads/branches/%s" % gitref(branch
)
542 print "? refs/heads/%s" % gitref(bmark
)
544 for tag
, node
in repo
.tagslist():
547 print "? refs/tags/%s" % gitref(tag
)
551 def do_import(parser
):
554 path
= os
.path
.join(dirname
, 'marks-git')
557 if os
.path
.exists(path
):
558 print "feature import-marks=%s" % path
559 print "feature export-marks=%s" % path
562 tmp
= encoding
.encoding
563 encoding
.encoding
= 'utf-8'
565 # lets get all the import lines
566 while parser
.check('import'):
571 elif ref
.startswith('refs/heads/branches/'):
572 branch
= ref
[len('refs/heads/branches/'):]
573 export_branch(repo
, branch
)
574 elif ref
.startswith('refs/heads/'):
575 bmark
= ref
[len('refs/heads/'):]
576 export_bookmark(repo
, bmark
)
577 elif ref
.startswith('refs/tags/'):
578 tag
= ref
[len('refs/tags/'):]
579 export_tag(repo
, tag
)
583 encoding
.encoding
= tmp
587 def parse_blob(parser
):
591 mark
= parser
.get_mark()
593 data
= parser
.get_data()
594 blob_marks
[mark
] = data
597 def get_merge_files(repo
, p1
, p2
, files
):
598 for e
in repo
[p1
].files():
600 if e
not in repo
[p1
].manifest():
602 f
= { 'ctx' : repo
[p1
][e
] }
605 def parse_commit(parser
):
606 global marks
, blob_marks
, parsed_refs
609 from_mark
= merge_mark
= None
614 commit_mark
= parser
.get_mark()
616 author
= parser
.get_author()
618 committer
= parser
.get_author()
620 data
= parser
.get_data()
622 if parser
.check('from'):
623 from_mark
= parser
.get_mark()
625 if parser
.check('merge'):
626 merge_mark
= parser
.get_mark()
628 if parser
.check('merge'):
629 die('octopus merges are not supported yet')
634 if parser
.check('M'):
635 t
, m
, mark_ref
, path
= line
.split(' ', 3)
636 mark
= int(mark_ref
[1:])
637 f
= { 'mode' : hgmode(m
), 'data' : blob_marks
[mark
] }
638 elif parser
.check('D'):
639 t
, path
= line
.split(' ', 1)
640 f
= { 'deleted' : True }
642 die('Unknown file command: %s' % line
)
645 def getfilectx(repo
, memctx
, f
):
651 is_exec
= of
['mode'] == 'x'
652 is_link
= of
['mode'] == 'l'
653 rename
= of
.get('rename', None)
654 return context
.memfilectx(f
, of
['data'],
655 is_link
, is_exec
, rename
)
659 user
, date
, tz
= author
662 if committer
!= author
:
663 extra
['committer'] = "%s %u %u" % committer
666 p1
= repo
.changelog
.node(mark_to_rev(from_mark
))
671 p2
= repo
.changelog
.node(mark_to_rev(merge_mark
))
676 # If files changed from any of the parents, hg wants to know, but in git if
677 # nothing changed from the first parent, nothing changed.
680 get_merge_files(repo
, p1
, p2
, files
)
682 # Check if the ref is supposed to be a named branch
683 if ref
.startswith('refs/heads/branches/'):
684 branch
= ref
[len('refs/heads/branches/'):]
685 extra
['branch'] = hgref(branch
)
688 i
= data
.find('\n--HG--\n')
690 tmp
= data
[i
+ len('\n--HG--\n'):].strip()
691 for k
, v
in [e
.split(' : ', 1) for e
in tmp
.split('\n')]:
693 old
, new
= v
.split(' => ', 1)
694 files
[new
]['rename'] = old
698 ek
, ev
= v
.split(' : ', 1)
699 extra
[ek
] = urllib
.unquote(ev
)
702 ctx
= context
.memctx(repo
, (p1
, p2
), data
,
703 files
.keys(), getfilectx
,
704 user
, (date
, tz
), extra
)
706 tmp
= encoding
.encoding
707 encoding
.encoding
= 'utf-8'
709 node
= repo
.commitctx(ctx
)
711 encoding
.encoding
= tmp
713 rev
= repo
[node
].rev()
715 parsed_refs
[ref
] = node
716 marks
.new_mark(rev
, commit_mark
)
718 def parse_reset(parser
):
724 if parser
.check('commit'):
727 if not parser
.check('from'):
729 from_mark
= parser
.get_mark()
732 node
= parser
.repo
.changelog
.node(mark_to_rev(from_mark
))
733 parsed_refs
[ref
] = node
735 def parse_tag(parser
):
738 from_mark
= parser
.get_mark()
740 tagger
= parser
.get_author()
742 data
= parser
.get_data()
745 parsed_tags
[name
] = (tagger
, data
)
747 def write_tag(repo
, tag
, node
, msg
, author
):
748 branch
= repo
[node
].branch()
749 tip
= branch_tip(repo
, branch
)
752 def getfilectx(repo
, memctx
, f
):
754 fctx
= tip
.filectx(f
)
756 except error
.ManifestLookupError
:
758 content
= data
+ "%s %s\n" % (hghex(node
), tag
)
759 return context
.memfilectx(f
, content
, False, False, None)
764 author
= (None, 0, 0)
765 user
, date
, tz
= author
767 ctx
= context
.memctx(repo
, (p1
, p2
), msg
,
768 ['.hgtags'], getfilectx
,
769 user
, (date
, tz
), {'branch' : branch
})
771 tmp
= encoding
.encoding
772 encoding
.encoding
= 'utf-8'
774 tagnode
= repo
.commitctx(ctx
)
776 encoding
.encoding
= tmp
780 def do_export(parser
):
781 global parsed_refs
, bmarks
, peer
787 for line
in parser
.each_block('done'):
788 if parser
.check('blob'):
790 elif parser
.check('commit'):
792 elif parser
.check('reset'):
794 elif parser
.check('tag'):
796 elif parser
.check('feature'):
799 die('unhandled export command: %s' % line
)
801 for ref
, node
in parsed_refs
.iteritems():
802 if ref
.startswith('refs/heads/branches'):
803 branch
= ref
[len('refs/heads/branches/'):]
804 if branch
in branches
and node
in branches
[branch
]:
808 elif ref
.startswith('refs/heads/'):
809 bmark
= ref
[len('refs/heads/'):]
810 p_bmarks
.append((bmark
, node
))
812 elif ref
.startswith('refs/tags/'):
813 tag
= ref
[len('refs/tags/'):]
815 author
, msg
= parsed_tags
.get(tag
, (None, None))
818 msg
= 'Added tag %s for changeset %s' % (tag
, hghex(node
[:6]));
819 write_tag(parser
.repo
, tag
, node
, msg
, author
)
821 fp
= parser
.repo
.opener('localtags', 'a')
822 fp
.write('%s %s\n' % (hghex(node
), tag
))
826 # transport-helper/fast-export bugs
830 parser
.repo
.push(peer
, force
=force_push
)
833 for bmark
, node
in p_bmarks
:
834 ref
= 'refs/heads/' + bmark
838 old
= bmarks
[bmark
].hex()
845 if bmark
== 'master' and 'master' not in parser
.repo
._bookmarks
:
848 elif bookmarks
.pushbookmark(parser
.repo
, bmark
, old
, new
):
852 print "error %s" % ref
856 rb
= peer
.listkeys('bookmarks')
857 old
= rb
.get(bmark
, '')
858 if not peer
.pushkey('bookmarks', bmark
, old
, new
):
859 print "error %s" % ref
866 def fix_path(alias
, repo
, orig_url
):
867 url
= urlparse
.urlparse(orig_url
, 'file')
868 if url
.scheme
!= 'file' or os
.path
.isabs(url
.path
):
870 abs_url
= urlparse
.urljoin("%s/" % os
.getcwd(), orig_url
)
871 cmd
= ['git', 'config', 'remote.%s.url' % alias
, "hg::%s" % abs_url
]
875 global prefix
, dirname
, branches
, bmarks
876 global marks
, blob_marks
, parsed_refs
877 global peer
, mode
, bad_mail
, bad_name
878 global track_branches
, force_push
, is_tmp
885 hg_git_compat
= False
886 track_branches
= True
890 if get_config('remote-hg.hg-git-compat') == 'true\n':
892 track_branches
= False
893 if get_config('remote-hg.track-branches') == 'false\n':
894 track_branches
= False
895 if get_config('remote-hg.force-push') == 'false\n':
897 except subprocess
.CalledProcessError
:
902 bad_mail
= 'none@none'
911 alias
= util
.sha1(alias
).hexdigest()
915 gitdir
= os
.environ
['GIT_DIR']
916 dirname
= os
.path
.join(gitdir
, 'hg', alias
)
924 repo
= get_repo(url
, alias
)
925 prefix
= 'refs/hg/%s' % alias
928 fix_path(alias
, peer
or repo
, url
)
930 if not os
.path
.exists(dirname
):
933 marks_path
= os
.path
.join(dirname
, 'marks-hg')
934 marks
= Marks(marks_path
)
936 parser
= Parser(repo
)
938 if parser
.check('capabilities'):
939 do_capabilities(parser
)
940 elif parser
.check('list'):
942 elif parser
.check('import'):
944 elif parser
.check('export'):
947 die('unhandled command: %s' % line
)
956 shutil
.rmtree(dirname
)
959 sys
.exit(main(sys
.argv
))