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 are not in hg-git-compat mode and want to disable the tracking of
30 # git config --global remote-hg.track-branches false
32 # If you don't want to force pushes (and thus risk creating new remote heads):
33 # git config --global remote-hg.force-push false
35 # If you want the equivalent of hg's clone/pull--insecure option:
36 # git config --global remote-hg.insecure true
38 # If you want to switch to hg-git compatibility mode:
39 # git config --global remote-hg.hg-git-compat 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 hg
.node
.bin(node
)
82 return ref
.replace('___', ' ')
85 return ref
.replace(' ', '___')
87 def get_config(config
):
88 cmd
= ['git', 'config', '--get', config
]
89 process
= subprocess
.Popen(cmd
, stdout
=subprocess
.PIPE
)
90 output
, _
= process
.communicate()
93 def get_config_bool(config
, default
=False):
94 value
= get_config(config
).rstrip('\n')
97 elif value
== "false":
104 def __init__(self
, path
):
114 if not os
.path
.exists(self
.path
):
117 tmp
= json
.load(open(self
.path
))
119 self
.tips
= tmp
['tips']
120 self
.marks
= tmp
['marks']
121 self
.last_mark
= tmp
['last-mark']
123 for rev
, mark
in self
.marks
.iteritems():
124 self
.rev_marks
[mark
] = int(rev
)
127 return { 'tips': self
.tips
, 'marks': self
.marks
, 'last-mark' : self
.last_mark
}
130 json
.dump(self
.dict(), open(self
.path
, 'w'))
133 return str(self
.dict())
135 def from_rev(self
, rev
):
136 return self
.marks
[str(rev
)]
138 def to_rev(self
, mark
):
139 return self
.rev_marks
[mark
]
143 return self
.last_mark
145 def get_mark(self
, rev
):
147 self
.marks
[str(rev
)] = self
.last_mark
148 return self
.last_mark
150 def new_mark(self
, rev
, mark
):
151 self
.marks
[str(rev
)] = mark
152 self
.rev_marks
[mark
] = rev
153 self
.last_mark
= mark
155 def is_marked(self
, rev
):
156 return str(rev
) in self
.marks
158 def get_tip(self
, branch
):
159 return self
.tips
.get(branch
, 0)
161 def set_tip(self
, branch
, tip
):
162 self
.tips
[branch
] = tip
166 def __init__(self
, repo
):
168 self
.line
= self
.get_line()
171 return sys
.stdin
.readline().strip()
173 def __getitem__(self
, i
):
174 return self
.line
.split()[i
]
176 def check(self
, word
):
177 return self
.line
.startswith(word
)
179 def each_block(self
, separator
):
180 while self
.line
!= separator
:
182 self
.line
= self
.get_line()
185 return self
.each_block('')
188 self
.line
= self
.get_line()
189 if self
.line
== 'done':
193 i
= self
.line
.index(':') + 1
194 return int(self
.line
[i
:])
197 if not self
.check('data'):
199 i
= self
.line
.index(' ') + 1
200 size
= int(self
.line
[i
:])
201 return sys
.stdin
.read(size
)
203 def get_author(self
):
207 m
= RAW_AUTHOR_RE
.match(self
.line
)
210 _
, name
, email
, date
, tz
= m
.groups()
211 if name
and 'ext:' in name
:
212 m
= re
.match('^(.+?) ext:\((.+)\)$', name
)
215 ex
= urllib
.unquote(m
.group(2))
217 if email
!= bad_mail
:
219 user
= '%s <%s>' % (name
, email
)
221 user
= '<%s>' % (email
)
229 tz
= ((tz
/ 100) * 3600) + ((tz
% 100) * 60)
230 return (user
, int(date
), -tz
)
232 def fix_file_path(path
):
233 if not os
.path
.isabs(path
):
235 return os
.path
.relpath(path
, '/')
237 def export_files(files
):
238 global marks
, filenodes
242 fid
= node
.hex(f
.filenode())
245 mark
= filenodes
[fid
]
247 mark
= marks
.next_mark()
248 filenodes
[fid
] = mark
252 print "mark :%u" % mark
253 print "data %d" % len(d
)
256 path
= fix_file_path(f
.path())
257 final
.append((gitmode(f
.flags()), mark
, path
))
261 def get_filechanges(repo
, ctx
, parent
):
266 # load earliest manifest first for caching reasons
267 prev
= parent
.manifest().copy()
272 if (cur
.flags(fn
) != prev
.flags(fn
) or cur
[fn
] != prev
[fn
]):
277 removed |
= set(prev
.keys())
279 return added | modified
, removed
281 def fixup_user_git(user
):
283 user
= user
.replace('"', '')
284 m
= AUTHOR_RE
.match(user
)
287 mail
= m
.group(2).strip()
289 m
= EMAIL_RE
.match(user
)
294 m
= NAME_RE
.match(user
)
296 name
= m
.group(1).strip()
299 def fixup_user_hg(user
):
301 # stole this from hg-git
302 return re
.sub('[<>\n]', '?', name
.lstrip('< ').rstrip('> '))
304 m
= AUTHOR_HG_RE
.match(user
)
306 name
= sanitize(m
.group(1))
307 mail
= sanitize(m
.group(2))
310 name
+= ' ext:(' + urllib
.quote(ex
) + ')'
312 name
= sanitize(user
)
320 def fixup_user(user
):
321 global mode
, bad_mail
324 name
, mail
= fixup_user_git(user
)
326 name
, mail
= fixup_user_hg(user
)
333 return '%s <%s>' % (name
, mail
)
335 def get_repo(url
, alias
):
339 myui
.setconfig('ui', 'interactive', 'off')
340 myui
.fout
= sys
.stderr
342 if get_config_bool('remote-hg.insecure'):
343 myui
.setconfig('web', 'cacerts', '')
345 extensions
.loadall(myui
)
348 repo
= hg
.repository(myui
, url
)
349 if not os
.path
.exists(dirname
):
352 shared_path
= os
.path
.join(gitdir
, 'hg')
353 if not os
.path
.exists(shared_path
):
355 hg
.clone(myui
, {}, url
, shared_path
, update
=False, pull
=True)
357 die('Repository error')
359 if not os
.path
.exists(dirname
):
362 local_path
= os
.path
.join(dirname
, 'clone')
363 if not os
.path
.exists(local_path
):
364 hg
.share(myui
, shared_path
, local_path
, update
=False)
366 repo
= hg
.repository(myui
, local_path
)
368 peer
= hg
.peer(myui
, {}, url
)
370 die('Repository error')
371 repo
.pull(peer
, heads
=None, force
=True)
375 def rev_to_mark(rev
):
377 return marks
.from_rev(rev
)
379 def mark_to_rev(mark
):
381 return marks
.to_rev(mark
)
383 def export_ref(repo
, name
, kind
, head
):
384 global prefix
, marks
, mode
386 ename
= '%s/%s' % (kind
, name
)
387 tip
= marks
.get_tip(ename
)
389 revs
= xrange(tip
, head
.rev() + 1)
397 if marks
.is_marked(c
.hex()):
401 (manifest
, user
, (time
, tz
), files
, desc
, extra
) = repo
.changelog
.read(node
)
402 rev_branch
= extra
['branch']
404 author
= "%s %d %s" % (fixup_user(user
), time
, gittz(tz
))
405 if 'committer' in extra
:
406 user
, time
, tz
= extra
['committer'].rsplit(' ', 2)
407 committer
= "%s %s %s" % (user
, time
, gittz(int(tz
)))
411 parents
= [repo
[p
] for p
in repo
.changelog
.parentrevs(rev
) if p
>= 0]
413 if len(parents
) == 0:
414 modified
= c
.manifest().keys()
417 modified
, removed
= get_filechanges(repo
, c
, parents
[0])
424 if rev_branch
!= 'default':
425 extra_msg
+= 'branch : %s\n' % rev_branch
429 if f
not in c
.manifest():
431 rename
= c
.filectx(f
).renamed()
433 renames
.append((rename
[0], f
))
436 extra_msg
+= "rename : %s => %s\n" % e
438 for key
, value
in extra
.iteritems():
439 if key
in ('author', 'committer', 'encoding', 'message', 'branch', 'hg-git'):
442 extra_msg
+= "extra : %s : %s\n" % (key
, urllib
.quote(value
))
445 desc
+= '\n--HG--\n' + extra_msg
447 if len(parents
) == 0 and rev
:
448 print 'reset %s/%s' % (prefix
, ename
)
450 modified_final
= export_files(c
.filectx(f
) for f
in modified
)
452 print "commit %s/%s" % (prefix
, ename
)
453 print "mark :%d" % (marks
.get_mark(rev
))
454 print "author %s" % (author
)
455 print "committer %s" % (committer
)
456 print "data %d" % (len(desc
))
460 print "from :%s" % (rev_to_mark(parents
[0].rev()))
462 print "merge :%s" % (rev_to_mark(parents
[1].rev()))
464 for f
in modified_final
:
465 print "M %s :%u %s" % f
467 print "D %s" % (fix_file_path(f
))
471 if (count
% 100 == 0):
472 print "progress revision %d '%s' (%d/%d)" % (rev
, name
, count
, len(revs
))
474 # make sure the ref is updated
475 print "reset %s/%s" % (prefix
, ename
)
476 print "from :%u" % rev_to_mark(head
.rev())
479 marks
.set_tip(ename
, head
.rev())
481 def export_tag(repo
, tag
):
482 export_ref(repo
, tag
, 'tags', repo
[hgref(tag
)])
484 def export_bookmark(repo
, bmark
):
485 head
= bmarks
[hgref(bmark
)]
486 export_ref(repo
, bmark
, 'bookmarks', head
)
488 def export_branch(repo
, branch
):
489 tip
= get_branch_tip(repo
, branch
)
491 export_ref(repo
, branch
, 'branches', head
)
493 def export_head(repo
):
495 export_ref(repo
, g_head
[0], 'bookmarks', g_head
[1])
497 def do_capabilities(parser
):
498 global prefix
, dirname
502 print "refspec refs/heads/branches/*:%s/branches/*" % prefix
503 print "refspec refs/heads/*:%s/bookmarks/*" % prefix
504 print "refspec refs/tags/*:%s/tags/*" % prefix
506 path
= os
.path
.join(dirname
, 'marks-git')
508 if os
.path
.exists(path
):
509 print "*import-marks %s" % path
510 print "*export-marks %s" % path
514 def branch_tip(repo
, branch
):
515 # older versions of mercurial don't have this
516 if hasattr(repo
, 'branchtip'):
517 return repo
.branchtip(branch
)
519 return repo
.branchtags()[branch
]
521 def get_branch_tip(repo
, branch
):
524 heads
= branches
.get(hgref(branch
), None)
528 # verify there's only one head
530 warn("Branch '%s' has more than one head, consider merging" % branch
)
531 return branch_tip(repo
, hgref(branch
))
535 def list_head(repo
, cur
):
536 global g_head
, bmarks
538 head
= bookmarks
.readcurrent(repo
)
542 # fake bookmark from current branch
549 if head
== 'default':
554 print "@refs/heads/%s HEAD" % head
555 g_head
= (head
, node
)
558 global branches
, bmarks
, track_branches
561 for bmark
, node
in bookmarks
.listbookmarks(repo
).iteritems():
562 bmarks
[bmark
] = repo
[node
]
564 cur
= repo
.dirstate
.branch()
569 for branch
in repo
.branchmap():
570 heads
= repo
.branchheads(branch
)
572 branches
[branch
] = heads
574 for branch
in branches
:
575 print "? refs/heads/branches/%s" % gitref(branch
)
578 print "? refs/heads/%s" % gitref(bmark
)
580 for tag
, node
in repo
.tagslist():
583 print "? refs/tags/%s" % gitref(tag
)
587 def do_import(parser
):
590 path
= os
.path
.join(dirname
, 'marks-git')
593 if os
.path
.exists(path
):
594 print "feature import-marks=%s" % path
595 print "feature export-marks=%s" % path
598 tmp
= encoding
.encoding
599 encoding
.encoding
= 'utf-8'
601 # lets get all the import lines
602 while parser
.check('import'):
607 elif ref
.startswith('refs/heads/branches/'):
608 branch
= ref
[len('refs/heads/branches/'):]
609 export_branch(repo
, branch
)
610 elif ref
.startswith('refs/heads/'):
611 bmark
= ref
[len('refs/heads/'):]
612 export_bookmark(repo
, bmark
)
613 elif ref
.startswith('refs/tags/'):
614 tag
= ref
[len('refs/tags/'):]
615 export_tag(repo
, tag
)
619 encoding
.encoding
= tmp
623 def parse_blob(parser
):
627 mark
= parser
.get_mark()
629 data
= parser
.get_data()
630 blob_marks
[mark
] = data
633 def get_merge_files(repo
, p1
, p2
, files
):
634 for e
in repo
[p1
].files():
636 if e
not in repo
[p1
].manifest():
638 f
= { 'ctx' : repo
[p1
][e
] }
641 def parse_commit(parser
):
642 global marks
, blob_marks
, parsed_refs
645 from_mark
= merge_mark
= None
650 commit_mark
= parser
.get_mark()
652 author
= parser
.get_author()
654 committer
= parser
.get_author()
656 data
= parser
.get_data()
658 if parser
.check('from'):
659 from_mark
= parser
.get_mark()
661 if parser
.check('merge'):
662 merge_mark
= parser
.get_mark()
664 if parser
.check('merge'):
665 die('octopus merges are not supported yet')
667 # fast-export adds an extra newline
674 if parser
.check('M'):
675 t
, m
, mark_ref
, path
= line
.split(' ', 3)
676 mark
= int(mark_ref
[1:])
677 f
= { 'mode' : hgmode(m
), 'data' : blob_marks
[mark
] }
678 elif parser
.check('D'):
679 t
, path
= line
.split(' ', 1)
680 f
= { 'deleted' : True }
682 die('Unknown file command: %s' % line
)
685 def getfilectx(repo
, memctx
, f
):
691 is_exec
= of
['mode'] == 'x'
692 is_link
= of
['mode'] == 'l'
693 rename
= of
.get('rename', None)
694 return context
.memfilectx(f
, of
['data'],
695 is_link
, is_exec
, rename
)
699 user
, date
, tz
= author
702 if committer
!= author
:
703 extra
['committer'] = "%s %u %u" % committer
706 p1
= repo
.changelog
.node(mark_to_rev(from_mark
))
711 p2
= repo
.changelog
.node(mark_to_rev(merge_mark
))
716 # If files changed from any of the parents, hg wants to know, but in git if
717 # nothing changed from the first parent, nothing changed.
720 get_merge_files(repo
, p1
, p2
, files
)
722 # Check if the ref is supposed to be a named branch
723 if ref
.startswith('refs/heads/branches/'):
724 branch
= ref
[len('refs/heads/branches/'):]
725 extra
['branch'] = hgref(branch
)
728 i
= data
.find('\n--HG--\n')
730 tmp
= data
[i
+ len('\n--HG--\n'):].strip()
731 for k
, v
in [e
.split(' : ', 1) for e
in tmp
.split('\n')]:
733 old
, new
= v
.split(' => ', 1)
734 files
[new
]['rename'] = old
738 ek
, ev
= v
.split(' : ', 1)
739 extra
[ek
] = urllib
.unquote(ev
)
742 ctx
= context
.memctx(repo
, (p1
, p2
), data
,
743 files
.keys(), getfilectx
,
744 user
, (date
, tz
), extra
)
746 tmp
= encoding
.encoding
747 encoding
.encoding
= 'utf-8'
749 node
= hghex(repo
.commitctx(ctx
))
751 encoding
.encoding
= tmp
753 rev
= repo
[node
].rev()
755 parsed_refs
[ref
] = node
756 marks
.new_mark(rev
, commit_mark
)
758 def parse_reset(parser
):
764 if parser
.check('commit'):
767 if not parser
.check('from'):
769 from_mark
= parser
.get_mark()
772 node
= parser
.repo
.changelog
.node(mark_to_rev(from_mark
))
773 parsed_refs
[ref
] = hghex(node
)
775 def parse_tag(parser
):
778 from_mark
= parser
.get_mark()
780 tagger
= parser
.get_author()
782 data
= parser
.get_data()
785 parsed_tags
[name
] = (tagger
, data
)
787 def write_tag(repo
, tag
, node
, msg
, author
):
788 branch
= repo
[node
].branch()
789 tip
= branch_tip(repo
, branch
)
792 def getfilectx(repo
, memctx
, f
):
794 fctx
= tip
.filectx(f
)
796 except error
.ManifestLookupError
:
798 content
= data
+ "%s %s\n" % (node
, tag
)
799 return context
.memfilectx(f
, content
, False, False, None)
804 author
= (None, 0, 0)
805 user
, date
, tz
= author
807 ctx
= context
.memctx(repo
, (p1
, p2
), msg
,
808 ['.hgtags'], getfilectx
,
809 user
, (date
, tz
), {'branch' : branch
})
811 tmp
= encoding
.encoding
812 encoding
.encoding
= 'utf-8'
814 tagnode
= repo
.commitctx(ctx
)
816 encoding
.encoding
= tmp
820 def do_export(parser
):
821 global parsed_refs
, bmarks
, peer
827 for line
in parser
.each_block('done'):
828 if parser
.check('blob'):
830 elif parser
.check('commit'):
832 elif parser
.check('reset'):
834 elif parser
.check('tag'):
836 elif parser
.check('feature'):
839 die('unhandled export command: %s' % line
)
841 for ref
, node
in parsed_refs
.iteritems():
843 if ref
.startswith('refs/heads/branches'):
844 branch
= ref
[len('refs/heads/branches/'):]
845 if branch
in branches
and bnode
in branches
[branch
]:
849 elif ref
.startswith('refs/heads/'):
850 bmark
= ref
[len('refs/heads/'):]
851 p_bmarks
.append((bmark
, node
))
853 elif ref
.startswith('refs/tags/'):
854 tag
= ref
[len('refs/tags/'):]
856 author
, msg
= parsed_tags
.get(tag
, (None, None))
859 msg
= 'Added tag %s for changeset %s' % (tag
, node
[:12]);
860 write_tag(parser
.repo
, tag
, node
, msg
, author
)
862 fp
= parser
.repo
.opener('localtags', 'a')
863 fp
.write('%s %s\n' % (node
, tag
))
867 # transport-helper/fast-export bugs
871 parser
.repo
.push(peer
, force
=force_push
, newbranch
=True)
872 remote_bmarks
= peer
.listkeys('bookmarks')
875 for bmark
, node
in p_bmarks
:
876 ref
= 'refs/heads/' + bmark
880 old
= bmarks
[bmark
].hex()
887 if bmark
== 'master' and 'master' not in parser
.repo
._bookmarks
:
891 elif bookmarks
.pushbookmark(parser
.repo
, bmark
, old
, new
):
895 print "error %s" % ref
899 old
= remote_bmarks
.get(bmark
, '')
900 if not peer
.pushkey('bookmarks', bmark
, old
, new
):
901 print "error %s" % ref
908 def fix_path(alias
, repo
, orig_url
):
909 url
= urlparse
.urlparse(orig_url
, 'file')
910 if url
.scheme
!= 'file' or os
.path
.isabs(url
.path
):
912 abs_url
= urlparse
.urljoin("%s/" % os
.getcwd(), orig_url
)
913 cmd
= ['git', 'config', 'remote.%s.url' % alias
, "hg::%s" % abs_url
]
917 global prefix
, gitdir
, dirname
, branches
, bmarks
918 global marks
, blob_marks
, parsed_refs
919 global peer
, mode
, bad_mail
, bad_name
920 global track_branches
, force_push
, is_tmp
928 hg_git_compat
= get_config_bool('remote-hg.hg-git-compat')
929 track_branches
= get_config_bool('remote-hg.track-branches', True)
930 force_push
= get_config_bool('remote-hg.force-push')
934 bad_mail
= 'none@none'
943 alias
= hashlib
.sha1(alias
).hexdigest()
947 gitdir
= os
.environ
['GIT_DIR']
948 dirname
= os
.path
.join(gitdir
, 'hg', alias
)
957 repo
= get_repo(url
, alias
)
958 prefix
= 'refs/hg/%s' % alias
961 fix_path(alias
, peer
or repo
, url
)
963 marks_path
= os
.path
.join(dirname
, 'marks-hg')
964 marks
= Marks(marks_path
)
966 if sys
.platform
== 'win32':
968 msvcrt
.setmode(sys
.stdout
.fileno(), os
.O_BINARY
)
970 parser
= Parser(repo
)
972 if parser
.check('capabilities'):
973 do_capabilities(parser
)
974 elif parser
.check('list'):
976 elif parser
.check('import'):
978 elif parser
.check('export'):
981 die('unhandled command: %s' % line
)
990 shutil
.rmtree(dirname
)
993 sys
.exit(main(sys
.argv
))