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
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 AUTHOR_HG_RE
= re
.compile('^(.*?) ?<(.*?)(?:>(.+)?)?$')
55 RAW_AUTHOR_RE
= re
.compile('^(\w+) (?:(.+)? )?<(.*)> (\d+) ([+-]\d+)')
58 sys
.stderr
.write('ERROR: %s\n' % (msg
% args
))
62 sys
.stderr
.write('WARNING: %s\n' % (msg
% args
))
65 return 'l' in flags
and '120000' or 'x' in flags
and '100755' or '100644'
68 return '%+03d%02d' % (-tz
/ 3600, -tz
% 3600 / 60)
71 m
= { '100755': 'x', '120000': 'l' }
72 return m
.get(mode
, '')
75 return hg
.node
.hex(node
)
77 def get_config(config
):
78 cmd
= ['git', 'config', '--get', config
]
79 process
= subprocess
.Popen(cmd
, stdout
=subprocess
.PIPE
)
80 output
, _
= process
.communicate()
85 def __init__(self
, path
):
95 if not os
.path
.exists(self
.path
):
98 tmp
= json
.load(open(self
.path
))
100 self
.tips
= tmp
['tips']
101 self
.marks
= tmp
['marks']
102 self
.last_mark
= tmp
['last-mark']
104 for rev
, mark
in self
.marks
.iteritems():
105 self
.rev_marks
[mark
] = int(rev
)
108 return { 'tips': self
.tips
, 'marks': self
.marks
, 'last-mark' : self
.last_mark
}
111 json
.dump(self
.dict(), open(self
.path
, 'w'))
114 return str(self
.dict())
116 def from_rev(self
, rev
):
117 return self
.marks
[str(rev
)]
119 def to_rev(self
, mark
):
120 return self
.rev_marks
[mark
]
122 def get_mark(self
, rev
):
124 self
.marks
[str(rev
)] = self
.last_mark
125 return self
.last_mark
127 def new_mark(self
, rev
, mark
):
128 self
.marks
[str(rev
)] = mark
129 self
.rev_marks
[mark
] = rev
130 self
.last_mark
= mark
132 def is_marked(self
, rev
):
133 return str(rev
) in self
.marks
135 def get_tip(self
, branch
):
136 return self
.tips
.get(branch
, 0)
138 def set_tip(self
, branch
, tip
):
139 self
.tips
[branch
] = tip
143 def __init__(self
, repo
):
145 self
.line
= self
.get_line()
148 return sys
.stdin
.readline().strip()
150 def __getitem__(self
, i
):
151 return self
.line
.split()[i
]
153 def check(self
, word
):
154 return self
.line
.startswith(word
)
156 def each_block(self
, separator
):
157 while self
.line
!= separator
:
159 self
.line
= self
.get_line()
162 return self
.each_block('')
165 self
.line
= self
.get_line()
166 if self
.line
== 'done':
170 i
= self
.line
.index(':') + 1
171 return int(self
.line
[i
:])
174 if not self
.check('data'):
176 i
= self
.line
.index(' ') + 1
177 size
= int(self
.line
[i
:])
178 return sys
.stdin
.read(size
)
180 def get_author(self
):
184 m
= RAW_AUTHOR_RE
.match(self
.line
)
187 _
, name
, email
, date
, tz
= m
.groups()
188 if name
and 'ext:' in name
:
189 m
= re
.match('^(.+?) ext:\((.+)\)$', name
)
192 ex
= urllib
.unquote(m
.group(2))
194 if email
!= bad_mail
:
196 user
= '%s <%s>' % (name
, email
)
198 user
= '<%s>' % (email
)
206 tz
= ((tz
/ 100) * 3600) + ((tz
% 100) * 60)
207 return (user
, int(date
), -tz
)
209 def fix_file_path(path
):
210 if not os
.path
.isabs(path
):
212 return os
.path
.relpath(path
, '/')
216 path
= fix_file_path(fc
.path())
217 print "M %s inline %s" % (gitmode(fc
.flags()), path
)
218 print "data %d" % len(d
)
221 def get_filechanges(repo
, ctx
, parent
):
227 prev
= repo
[parent
].manifest().copy()
231 if (cur
.flags(fn
) != prev
.flags(fn
) or cur
[fn
] != prev
[fn
]):
236 removed |
= set(prev
.keys())
238 return added | modified
, removed
240 def fixup_user_git(user
):
242 user
= user
.replace('"', '')
243 m
= AUTHOR_RE
.match(user
)
246 mail
= m
.group(2).strip()
248 m
= NAME_RE
.match(user
)
250 name
= m
.group(1).strip()
253 def fixup_user_hg(user
):
255 # stole this from hg-git
256 return re
.sub('[<>\n]', '?', name
.lstrip('< ').rstrip('> '))
258 m
= AUTHOR_HG_RE
.match(user
)
260 name
= sanitize(m
.group(1))
261 mail
= sanitize(m
.group(2))
264 name
+= ' ext:(' + urllib
.quote(ex
) + ')'
266 name
= sanitize(user
)
274 def fixup_user(user
):
275 global mode
, bad_mail
278 name
, mail
= fixup_user_git(user
)
280 name
, mail
= fixup_user_hg(user
)
287 return '%s <%s>' % (name
, mail
)
289 def get_repo(url
, alias
):
293 myui
.setconfig('ui', 'interactive', 'off')
294 myui
.fout
= sys
.stderr
297 if get_config('remote-hg.insecure') == 'true\n':
298 myui
.setconfig('web', 'cacerts', '')
299 except subprocess
.CalledProcessError
:
303 repo
= hg
.repository(myui
, url
)
305 local_path
= os
.path
.join(dirname
, 'clone')
306 if not os
.path
.exists(local_path
):
308 peer
, dstpeer
= hg
.clone(myui
, {}, url
, local_path
, update
=True, pull
=True)
310 die('Repository error')
311 repo
= dstpeer
.local()
313 repo
= hg
.repository(myui
, local_path
)
315 peer
= hg
.peer(myui
, {}, url
)
317 die('Repository error')
318 repo
.pull(peer
, heads
=None, force
=True)
322 def rev_to_mark(rev
):
324 return marks
.from_rev(rev
)
326 def mark_to_rev(mark
):
328 return marks
.to_rev(mark
)
330 def export_ref(repo
, name
, kind
, head
):
331 global prefix
, marks
, mode
333 ename
= '%s/%s' % (kind
, name
)
334 tip
= marks
.get_tip(ename
)
336 # mercurial takes too much time checking this
337 if tip
and tip
== head
.rev():
340 revs
= xrange(tip
, head
.rev() + 1)
343 revs
= [rev
for rev
in revs
if not marks
.is_marked(rev
)]
348 (manifest
, user
, (time
, tz
), files
, desc
, extra
) = repo
.changelog
.read(c
.node())
349 rev_branch
= extra
['branch']
351 author
= "%s %d %s" % (fixup_user(user
), time
, gittz(tz
))
352 if 'committer' in extra
:
353 user
, time
, tz
= extra
['committer'].rsplit(' ', 2)
354 committer
= "%s %s %s" % (user
, time
, gittz(int(tz
)))
358 parents
= [p
for p
in repo
.changelog
.parentrevs(rev
) if p
>= 0]
360 if len(parents
) == 0:
361 modified
= c
.manifest().keys()
364 modified
, removed
= get_filechanges(repo
, c
, parents
[0])
371 if rev_branch
!= 'default':
372 extra_msg
+= 'branch : %s\n' % rev_branch
376 if f
not in c
.manifest():
378 rename
= c
.filectx(f
).renamed()
380 renames
.append((rename
[0], f
))
383 extra_msg
+= "rename : %s => %s\n" % e
385 for key
, value
in extra
.iteritems():
386 if key
in ('author', 'committer', 'encoding', 'message', 'branch', 'hg-git'):
389 extra_msg
+= "extra : %s : %s\n" % (key
, urllib
.quote(value
))
392 desc
+= '\n--HG--\n' + extra_msg
394 if len(parents
) == 0 and rev
:
395 print 'reset %s/%s' % (prefix
, ename
)
397 print "commit %s/%s" % (prefix
, ename
)
398 print "mark :%d" % (marks
.get_mark(rev
))
399 print "author %s" % (author
)
400 print "committer %s" % (committer
)
401 print "data %d" % (len(desc
))
405 print "from :%s" % (rev_to_mark(parents
[0]))
407 print "merge :%s" % (rev_to_mark(parents
[1]))
410 export_file(c
.filectx(f
))
412 print "D %s" % (fix_file_path(f
))
416 if (count
% 100 == 0):
417 print "progress revision %d '%s' (%d/%d)" % (rev
, name
, count
, len(revs
))
418 print "#############################################################"
420 # make sure the ref is updated
421 print "reset %s/%s" % (prefix
, ename
)
422 print "from :%u" % rev_to_mark(rev
)
425 marks
.set_tip(ename
, rev
)
427 def export_tag(repo
, tag
):
428 export_ref(repo
, tag
, 'tags', repo
[tag
])
430 def export_bookmark(repo
, bmark
):
432 export_ref(repo
, bmark
, 'bookmarks', head
)
434 def export_branch(repo
, branch
):
435 tip
= get_branch_tip(repo
, branch
)
437 export_ref(repo
, branch
, 'branches', head
)
439 def export_head(repo
):
441 export_ref(repo
, g_head
[0], 'bookmarks', g_head
[1])
443 def do_capabilities(parser
):
444 global prefix
, dirname
448 print "refspec refs/heads/branches/*:%s/branches/*" % prefix
449 print "refspec refs/heads/*:%s/bookmarks/*" % prefix
450 print "refspec refs/tags/*:%s/tags/*" % prefix
452 path
= os
.path
.join(dirname
, 'marks-git')
454 if os
.path
.exists(path
):
455 print "*import-marks %s" % path
456 print "*export-marks %s" % path
460 def branch_tip(repo
, branch
):
461 # older versions of mercurial don't have this
462 if hasattr(repo
, 'branchtip'):
463 return repo
.branchtip(branch
)
465 return repo
.branchtags()[branch
]
467 def get_branch_tip(repo
, branch
):
470 heads
= branches
.get(branch
, None)
474 # verify there's only one head
476 warn("Branch '%s' has more than one head, consider merging" % branch
)
477 return branch_tip(repo
, branch
)
481 def list_head(repo
, cur
):
482 global g_head
, bmarks
484 head
= bookmarks
.readcurrent(repo
)
488 # fake bookmark from current branch
495 if head
== 'default':
499 print "@refs/heads/%s HEAD" % head
500 g_head
= (head
, node
)
503 global branches
, bmarks
, mode
, track_branches
506 for bmark
, node
in bookmarks
.listbookmarks(repo
).iteritems():
507 bmarks
[bmark
] = repo
[node
]
509 cur
= repo
.dirstate
.branch()
514 for branch
in repo
.branchmap():
515 heads
= repo
.branchheads(branch
)
517 branches
[branch
] = heads
519 for branch
in branches
:
520 print "? refs/heads/branches/%s" % branch
523 print "? refs/heads/%s" % bmark
525 for tag
, node
in repo
.tagslist():
528 print "? refs/tags/%s" % tag
532 def do_import(parser
):
535 path
= os
.path
.join(dirname
, 'marks-git')
538 if os
.path
.exists(path
):
539 print "feature import-marks=%s" % path
540 print "feature export-marks=%s" % path
543 tmp
= encoding
.encoding
544 encoding
.encoding
= 'utf-8'
546 # lets get all the import lines
547 while parser
.check('import'):
552 elif ref
.startswith('refs/heads/branches/'):
553 branch
= ref
[len('refs/heads/branches/'):]
554 export_branch(repo
, branch
)
555 elif ref
.startswith('refs/heads/'):
556 bmark
= ref
[len('refs/heads/'):]
557 export_bookmark(repo
, bmark
)
558 elif ref
.startswith('refs/tags/'):
559 tag
= ref
[len('refs/tags/'):]
560 export_tag(repo
, tag
)
564 encoding
.encoding
= tmp
568 def parse_blob(parser
):
572 mark
= parser
.get_mark()
574 data
= parser
.get_data()
575 blob_marks
[mark
] = data
578 def get_merge_files(repo
, p1
, p2
, files
):
579 for e
in repo
[p1
].files():
581 if e
not in repo
[p1
].manifest():
583 f
= { 'ctx' : repo
[p1
][e
] }
586 def parse_commit(parser
):
587 global marks
, blob_marks
, parsed_refs
590 from_mark
= merge_mark
= None
595 commit_mark
= parser
.get_mark()
597 author
= parser
.get_author()
599 committer
= parser
.get_author()
601 data
= parser
.get_data()
603 if parser
.check('from'):
604 from_mark
= parser
.get_mark()
606 if parser
.check('merge'):
607 merge_mark
= parser
.get_mark()
609 if parser
.check('merge'):
610 die('octopus merges are not supported yet')
615 if parser
.check('M'):
616 t
, m
, mark_ref
, path
= line
.split(' ', 3)
617 mark
= int(mark_ref
[1:])
618 f
= { 'mode' : hgmode(m
), 'data' : blob_marks
[mark
] }
619 elif parser
.check('D'):
620 t
, path
= line
.split(' ', 1)
621 f
= { 'deleted' : True }
623 die('Unknown file command: %s' % line
)
626 def getfilectx(repo
, memctx
, f
):
632 is_exec
= of
['mode'] == 'x'
633 is_link
= of
['mode'] == 'l'
634 rename
= of
.get('rename', None)
635 return context
.memfilectx(f
, of
['data'],
636 is_link
, is_exec
, rename
)
640 user
, date
, tz
= author
643 if committer
!= author
:
644 extra
['committer'] = "%s %u %u" % committer
647 p1
= repo
.changelog
.node(mark_to_rev(from_mark
))
652 p2
= repo
.changelog
.node(mark_to_rev(merge_mark
))
657 # If files changed from any of the parents, hg wants to know, but in git if
658 # nothing changed from the first parent, nothing changed.
661 get_merge_files(repo
, p1
, p2
, files
)
663 # Check if the ref is supposed to be a named branch
664 if ref
.startswith('refs/heads/branches/'):
665 extra
['branch'] = ref
[len('refs/heads/branches/'):]
668 i
= data
.find('\n--HG--\n')
670 tmp
= data
[i
+ len('\n--HG--\n'):].strip()
671 for k
, v
in [e
.split(' : ', 1) for e
in tmp
.split('\n')]:
673 old
, new
= v
.split(' => ', 1)
674 files
[new
]['rename'] = old
678 ek
, ev
= v
.split(' : ', 1)
679 extra
[ek
] = urllib
.unquote(ev
)
682 ctx
= context
.memctx(repo
, (p1
, p2
), data
,
683 files
.keys(), getfilectx
,
684 user
, (date
, tz
), extra
)
686 tmp
= encoding
.encoding
687 encoding
.encoding
= 'utf-8'
689 node
= repo
.commitctx(ctx
)
691 encoding
.encoding
= tmp
693 rev
= repo
[node
].rev()
695 parsed_refs
[ref
] = node
696 marks
.new_mark(rev
, commit_mark
)
698 def parse_reset(parser
):
704 if parser
.check('commit'):
707 if not parser
.check('from'):
709 from_mark
= parser
.get_mark()
712 node
= parser
.repo
.changelog
.node(mark_to_rev(from_mark
))
713 parsed_refs
[ref
] = node
715 def parse_tag(parser
):
718 from_mark
= parser
.get_mark()
720 tagger
= parser
.get_author()
722 data
= parser
.get_data()
725 parsed_tags
[name
] = (tagger
, data
)
727 def write_tag(repo
, tag
, node
, msg
, author
):
728 branch
= repo
[node
].branch()
729 tip
= branch_tip(repo
, branch
)
732 def getfilectx(repo
, memctx
, f
):
734 fctx
= tip
.filectx(f
)
736 except error
.ManifestLookupError
:
738 content
= data
+ "%s %s\n" % (hghex(node
), tag
)
739 return context
.memfilectx(f
, content
, False, False, None)
744 author
= (None, 0, 0)
745 user
, date
, tz
= author
747 ctx
= context
.memctx(repo
, (p1
, p2
), msg
,
748 ['.hgtags'], getfilectx
,
749 user
, (date
, tz
), {'branch' : branch
})
751 tmp
= encoding
.encoding
752 encoding
.encoding
= 'utf-8'
754 tagnode
= repo
.commitctx(ctx
)
756 encoding
.encoding
= tmp
760 def do_export(parser
):
761 global parsed_refs
, bmarks
, peer
767 for line
in parser
.each_block('done'):
768 if parser
.check('blob'):
770 elif parser
.check('commit'):
772 elif parser
.check('reset'):
774 elif parser
.check('tag'):
776 elif parser
.check('feature'):
779 die('unhandled export command: %s' % line
)
781 for ref
, node
in parsed_refs
.iteritems():
782 if ref
.startswith('refs/heads/branches'):
783 branch
= ref
[len('refs/heads/branches/'):]
784 if branch
in branches
and node
in branches
[branch
]:
788 elif ref
.startswith('refs/heads/'):
789 bmark
= ref
[len('refs/heads/'):]
790 p_bmarks
.append((bmark
, node
))
792 elif ref
.startswith('refs/tags/'):
793 tag
= ref
[len('refs/tags/'):]
794 author
, msg
= parsed_tags
.get(tag
, (None, None))
797 msg
= 'Added tag %s for changeset %s' % (tag
, hghex(node
[:6]));
798 write_tag(parser
.repo
, tag
, node
, msg
, author
)
800 parser
.repo
.tag([tag
], node
, None, True, None, {})
803 # transport-helper/fast-export bugs
807 parser
.repo
.push(peer
, force
=force_push
)
810 for bmark
, node
in p_bmarks
:
811 ref
= 'refs/heads/' + bmark
815 old
= bmarks
[bmark
].hex()
819 if bmark
== 'master' and 'master' not in parser
.repo
._bookmarks
:
822 elif bookmarks
.pushbookmark(parser
.repo
, bmark
, old
, new
):
826 print "error %s" % ref
830 rb
= peer
.listkeys('bookmarks')
831 old
= rb
.get(bmark
, '')
832 if not peer
.pushkey('bookmarks', bmark
, old
, new
):
833 print "error %s" % ref
840 def fix_path(alias
, repo
, orig_url
):
841 url
= urlparse
.urlparse(orig_url
, 'file')
842 if url
.scheme
!= 'file' or os
.path
.isabs(url
.path
):
844 abs_url
= urlparse
.urljoin("%s/" % os
.getcwd(), orig_url
)
845 cmd
= ['git', 'config', 'remote.%s.url' % alias
, "hg::%s" % abs_url
]
849 global prefix
, dirname
, branches
, bmarks
850 global marks
, blob_marks
, parsed_refs
851 global peer
, mode
, bad_mail
, bad_name
852 global track_branches
, force_push
, is_tmp
859 hg_git_compat
= False
860 track_branches
= True
864 if get_config('remote-hg.hg-git-compat') == 'true\n':
866 track_branches
= False
867 if get_config('remote-hg.track-branches') == 'false\n':
868 track_branches
= False
869 if get_config('remote-hg.force-push') == 'false\n':
871 except subprocess
.CalledProcessError
:
876 bad_mail
= 'none@none'
885 alias
= util
.sha1(alias
).hexdigest()
889 gitdir
= os
.environ
['GIT_DIR']
890 dirname
= os
.path
.join(gitdir
, 'hg', alias
)
898 repo
= get_repo(url
, alias
)
899 prefix
= 'refs/hg/%s' % alias
902 fix_path(alias
, peer
or repo
, url
)
904 if not os
.path
.exists(dirname
):
907 marks_path
= os
.path
.join(dirname
, 'marks-hg')
908 marks
= Marks(marks_path
)
910 parser
= Parser(repo
)
912 if parser
.check('capabilities'):
913 do_capabilities(parser
)
914 elif parser
.check('list'):
916 elif parser
.check('import'):
918 elif parser
.check('export'):
921 die('unhandled command: %s' % line
)
930 shutil
.rmtree(dirname
)
933 sys
.exit(main(sys
.argv
))