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+)')
61 sys
.stderr
.write('ERROR: %s\n' % (msg
% args
))
65 sys
.stderr
.write('WARNING: %s\n' % (msg
% args
))
68 return 'l' in flags
and '120000' or 'x' in flags
and '100755' or '100644'
71 return '%+03d%02d' % (-tz
/ 3600, -tz
% 3600 / 60)
74 m
= { '100755': 'x', '120000': 'l' }
75 return m
.get(mode
, '')
78 return hg
.node
.hex(node
)
81 return hg
.node
.bin(node
)
84 return ref
.replace('___', ' ')
87 return ref
.replace(' ', '___')
89 def get_config(config
):
90 cmd
= ['git', 'config', '--get', config
]
91 process
= subprocess
.Popen(cmd
, stdout
=subprocess
.PIPE
)
92 output
, _
= process
.communicate()
95 def get_config_bool(config
, default
=False):
96 value
= get_config(config
).rstrip('\n')
99 elif value
== "false":
106 def __init__(self
, path
):
111 if self
.version
< VERSION
:
113 self
.version
= VERSION
123 if not os
.path
.exists(self
.path
):
126 tmp
= json
.load(open(self
.path
))
128 self
.tips
= tmp
['tips']
129 self
.marks
= tmp
['marks']
130 self
.last_mark
= tmp
['last-mark']
131 self
.version
= tmp
.get('version', 1)
133 for rev
, mark
in self
.marks
.iteritems():
134 self
.rev_marks
[mark
] = int(rev
)
137 return { 'tips': self
.tips
, 'marks': self
.marks
, 'last-mark' : self
.last_mark
, 'version' : self
.version
}
140 json
.dump(self
.dict(), open(self
.path
, 'w'))
143 return str(self
.dict())
145 def from_rev(self
, rev
):
146 return self
.marks
[str(rev
)]
148 def to_rev(self
, mark
):
149 return self
.rev_marks
[mark
]
153 return self
.last_mark
155 def get_mark(self
, rev
):
157 self
.marks
[str(rev
)] = self
.last_mark
158 return self
.last_mark
160 def new_mark(self
, rev
, mark
):
161 self
.marks
[str(rev
)] = mark
162 self
.rev_marks
[mark
] = rev
163 self
.last_mark
= mark
165 def is_marked(self
, rev
):
166 return str(rev
) in self
.marks
168 def get_tip(self
, branch
):
169 return self
.tips
.get(branch
, 0)
171 def set_tip(self
, branch
, tip
):
172 self
.tips
[branch
] = tip
176 def __init__(self
, repo
):
178 self
.line
= self
.get_line()
181 return sys
.stdin
.readline().strip()
183 def __getitem__(self
, i
):
184 return self
.line
.split()[i
]
186 def check(self
, word
):
187 return self
.line
.startswith(word
)
189 def each_block(self
, separator
):
190 while self
.line
!= separator
:
192 self
.line
= self
.get_line()
195 return self
.each_block('')
198 self
.line
= self
.get_line()
199 if self
.line
== 'done':
203 i
= self
.line
.index(':') + 1
204 return int(self
.line
[i
:])
207 if not self
.check('data'):
209 i
= self
.line
.index(' ') + 1
210 size
= int(self
.line
[i
:])
211 return sys
.stdin
.read(size
)
213 def get_author(self
):
217 m
= RAW_AUTHOR_RE
.match(self
.line
)
220 _
, name
, email
, date
, tz
= m
.groups()
221 if name
and 'ext:' in name
:
222 m
= re
.match('^(.+?) ext:\((.+)\)$', name
)
225 ex
= urllib
.unquote(m
.group(2))
227 if email
!= bad_mail
:
229 user
= '%s <%s>' % (name
, email
)
231 user
= '<%s>' % (email
)
239 tz
= ((tz
/ 100) * 3600) + ((tz
% 100) * 60)
240 return (user
, int(date
), -tz
)
242 def fix_file_path(path
):
243 if not os
.path
.isabs(path
):
245 return os
.path
.relpath(path
, '/')
247 def export_files(files
):
248 global marks
, filenodes
252 fid
= node
.hex(f
.filenode())
255 mark
= filenodes
[fid
]
257 mark
= marks
.next_mark()
258 filenodes
[fid
] = mark
262 print "mark :%u" % mark
263 print "data %d" % len(d
)
266 path
= fix_file_path(f
.path())
267 final
.append((gitmode(f
.flags()), mark
, path
))
271 def get_filechanges(repo
, ctx
, parent
):
276 # load earliest manifest first for caching reasons
277 prev
= parent
.manifest().copy()
282 if (cur
.flags(fn
) != prev
.flags(fn
) or cur
[fn
] != prev
[fn
]):
287 removed |
= set(prev
.keys())
289 return added | modified
, removed
291 def fixup_user_git(user
):
293 user
= user
.replace('"', '')
294 m
= AUTHOR_RE
.match(user
)
297 mail
= m
.group(2).strip()
299 m
= EMAIL_RE
.match(user
)
304 m
= NAME_RE
.match(user
)
306 name
= m
.group(1).strip()
309 def fixup_user_hg(user
):
311 # stole this from hg-git
312 return re
.sub('[<>\n]', '?', name
.lstrip('< ').rstrip('> '))
314 m
= AUTHOR_HG_RE
.match(user
)
316 name
= sanitize(m
.group(1))
317 mail
= sanitize(m
.group(2))
320 name
+= ' ext:(' + urllib
.quote(ex
) + ')'
322 name
= sanitize(user
)
330 def fixup_user(user
):
331 global mode
, bad_mail
334 name
, mail
= fixup_user_git(user
)
336 name
, mail
= fixup_user_hg(user
)
343 return '%s <%s>' % (name
, mail
)
345 def get_repo(url
, alias
):
349 myui
.setconfig('ui', 'interactive', 'off')
350 myui
.fout
= sys
.stderr
352 if get_config_bool('remote-hg.insecure'):
353 myui
.setconfig('web', 'cacerts', '')
355 extensions
.loadall(myui
)
358 repo
= hg
.repository(myui
, url
)
359 if not os
.path
.exists(dirname
):
362 shared_path
= os
.path
.join(gitdir
, 'hg')
363 if not os
.path
.exists(shared_path
):
365 hg
.clone(myui
, {}, url
, shared_path
, update
=False, pull
=True)
367 die('Repository error')
369 if not os
.path
.exists(dirname
):
372 local_path
= os
.path
.join(dirname
, 'clone')
373 if not os
.path
.exists(local_path
):
374 hg
.share(myui
, shared_path
, local_path
, update
=False)
376 repo
= hg
.repository(myui
, local_path
)
378 peer
= hg
.peer(myui
, {}, url
)
380 die('Repository error')
381 repo
.pull(peer
, heads
=None, force
=True)
385 def rev_to_mark(rev
):
387 return marks
.from_rev(rev
)
389 def mark_to_rev(mark
):
391 return marks
.to_rev(mark
)
393 def export_ref(repo
, name
, kind
, head
):
394 global prefix
, marks
, mode
396 ename
= '%s/%s' % (kind
, name
)
397 tip
= marks
.get_tip(ename
)
399 revs
= xrange(tip
, head
.rev() + 1)
407 if marks
.is_marked(c
.hex()):
411 (manifest
, user
, (time
, tz
), files
, desc
, extra
) = repo
.changelog
.read(node
)
412 rev_branch
= extra
['branch']
414 author
= "%s %d %s" % (fixup_user(user
), time
, gittz(tz
))
415 if 'committer' in extra
:
416 user
, time
, tz
= extra
['committer'].rsplit(' ', 2)
417 committer
= "%s %s %s" % (user
, time
, gittz(int(tz
)))
421 parents
= [repo
[p
] for p
in repo
.changelog
.parentrevs(rev
) if p
>= 0]
423 if len(parents
) == 0:
424 modified
= c
.manifest().keys()
427 modified
, removed
= get_filechanges(repo
, c
, parents
[0])
434 if rev_branch
!= 'default':
435 extra_msg
+= 'branch : %s\n' % rev_branch
439 if f
not in c
.manifest():
441 rename
= c
.filectx(f
).renamed()
443 renames
.append((rename
[0], f
))
446 extra_msg
+= "rename : %s => %s\n" % e
448 for key
, value
in extra
.iteritems():
449 if key
in ('author', 'committer', 'encoding', 'message', 'branch', 'hg-git'):
452 extra_msg
+= "extra : %s : %s\n" % (key
, urllib
.quote(value
))
455 desc
+= '\n--HG--\n' + extra_msg
457 if len(parents
) == 0 and rev
:
458 print 'reset %s/%s' % (prefix
, ename
)
460 modified_final
= export_files(c
.filectx(f
) for f
in modified
)
462 print "commit %s/%s" % (prefix
, ename
)
463 print "mark :%d" % (marks
.get_mark(rev
))
464 print "author %s" % (author
)
465 print "committer %s" % (committer
)
466 print "data %d" % (len(desc
))
470 print "from :%s" % (rev_to_mark(parents
[0].rev()))
472 print "merge :%s" % (rev_to_mark(parents
[1].rev()))
474 for f
in modified_final
:
475 print "M %s :%u %s" % f
477 print "D %s" % (fix_file_path(f
))
481 if (count
% 100 == 0):
482 print "progress revision %d '%s' (%d/%d)" % (rev
, name
, count
, len(revs
))
484 # make sure the ref is updated
485 print "reset %s/%s" % (prefix
, ename
)
486 print "from :%u" % rev_to_mark(head
.rev())
489 marks
.set_tip(ename
, head
.rev())
491 def export_tag(repo
, tag
):
492 export_ref(repo
, tag
, 'tags', repo
[hgref(tag
)])
494 def export_bookmark(repo
, bmark
):
495 head
= bmarks
[hgref(bmark
)]
496 export_ref(repo
, bmark
, 'bookmarks', head
)
498 def export_branch(repo
, branch
):
499 tip
= get_branch_tip(repo
, branch
)
501 export_ref(repo
, branch
, 'branches', head
)
503 def export_head(repo
):
505 export_ref(repo
, g_head
[0], 'bookmarks', g_head
[1])
507 def do_capabilities(parser
):
508 global prefix
, dirname
512 print "refspec refs/heads/branches/*:%s/branches/*" % prefix
513 print "refspec refs/heads/*:%s/bookmarks/*" % prefix
514 print "refspec refs/tags/*:%s/tags/*" % prefix
516 path
= os
.path
.join(dirname
, 'marks-git')
518 if os
.path
.exists(path
):
519 print "*import-marks %s" % path
520 print "*export-marks %s" % path
524 def branch_tip(repo
, branch
):
525 # older versions of mercurial don't have this
526 if hasattr(repo
, 'branchtip'):
527 return repo
.branchtip(branch
)
529 return repo
.branchtags()[branch
]
531 def get_branch_tip(repo
, branch
):
534 heads
= branches
.get(hgref(branch
), None)
538 # verify there's only one head
540 warn("Branch '%s' has more than one head, consider merging" % branch
)
541 return branch_tip(repo
, hgref(branch
))
545 def list_head(repo
, cur
):
546 global g_head
, bmarks
548 head
= bookmarks
.readcurrent(repo
)
552 # fake bookmark from current branch
559 if head
== 'default':
564 print "@refs/heads/%s HEAD" % head
565 g_head
= (head
, node
)
568 global branches
, bmarks
, track_branches
571 for bmark
, node
in bookmarks
.listbookmarks(repo
).iteritems():
572 bmarks
[bmark
] = repo
[node
]
574 cur
= repo
.dirstate
.branch()
579 for branch
in repo
.branchmap():
580 heads
= repo
.branchheads(branch
)
582 branches
[branch
] = heads
584 for branch
in branches
:
585 print "? refs/heads/branches/%s" % gitref(branch
)
588 print "? refs/heads/%s" % gitref(bmark
)
590 for tag
, node
in repo
.tagslist():
593 print "? refs/tags/%s" % gitref(tag
)
597 def do_import(parser
):
600 path
= os
.path
.join(dirname
, 'marks-git')
603 if os
.path
.exists(path
):
604 print "feature import-marks=%s" % path
605 print "feature export-marks=%s" % path
608 tmp
= encoding
.encoding
609 encoding
.encoding
= 'utf-8'
611 # lets get all the import lines
612 while parser
.check('import'):
617 elif ref
.startswith('refs/heads/branches/'):
618 branch
= ref
[len('refs/heads/branches/'):]
619 export_branch(repo
, branch
)
620 elif ref
.startswith('refs/heads/'):
621 bmark
= ref
[len('refs/heads/'):]
622 export_bookmark(repo
, bmark
)
623 elif ref
.startswith('refs/tags/'):
624 tag
= ref
[len('refs/tags/'):]
625 export_tag(repo
, tag
)
629 encoding
.encoding
= tmp
633 def parse_blob(parser
):
637 mark
= parser
.get_mark()
639 data
= parser
.get_data()
640 blob_marks
[mark
] = data
643 def get_merge_files(repo
, p1
, p2
, files
):
644 for e
in repo
[p1
].files():
646 if e
not in repo
[p1
].manifest():
648 f
= { 'ctx' : repo
[p1
][e
] }
651 def parse_commit(parser
):
652 global marks
, blob_marks
, parsed_refs
655 from_mark
= merge_mark
= None
660 commit_mark
= parser
.get_mark()
662 author
= parser
.get_author()
664 committer
= parser
.get_author()
666 data
= parser
.get_data()
668 if parser
.check('from'):
669 from_mark
= parser
.get_mark()
671 if parser
.check('merge'):
672 merge_mark
= parser
.get_mark()
674 if parser
.check('merge'):
675 die('octopus merges are not supported yet')
677 # fast-export adds an extra newline
684 if parser
.check('M'):
685 t
, m
, mark_ref
, path
= line
.split(' ', 3)
686 mark
= int(mark_ref
[1:])
687 f
= { 'mode' : hgmode(m
), 'data' : blob_marks
[mark
] }
688 elif parser
.check('D'):
689 t
, path
= line
.split(' ', 1)
690 f
= { 'deleted' : True }
692 die('Unknown file command: %s' % line
)
695 def getfilectx(repo
, memctx
, f
):
701 is_exec
= of
['mode'] == 'x'
702 is_link
= of
['mode'] == 'l'
703 rename
= of
.get('rename', None)
704 return context
.memfilectx(f
, of
['data'],
705 is_link
, is_exec
, rename
)
709 user
, date
, tz
= author
712 if committer
!= author
:
713 extra
['committer'] = "%s %u %u" % committer
716 p1
= repo
.changelog
.node(mark_to_rev(from_mark
))
721 p2
= repo
.changelog
.node(mark_to_rev(merge_mark
))
726 # If files changed from any of the parents, hg wants to know, but in git if
727 # nothing changed from the first parent, nothing changed.
730 get_merge_files(repo
, p1
, p2
, files
)
732 # Check if the ref is supposed to be a named branch
733 if ref
.startswith('refs/heads/branches/'):
734 branch
= ref
[len('refs/heads/branches/'):]
735 extra
['branch'] = hgref(branch
)
738 i
= data
.find('\n--HG--\n')
740 tmp
= data
[i
+ len('\n--HG--\n'):].strip()
741 for k
, v
in [e
.split(' : ', 1) for e
in tmp
.split('\n')]:
743 old
, new
= v
.split(' => ', 1)
744 files
[new
]['rename'] = old
748 ek
, ev
= v
.split(' : ', 1)
749 extra
[ek
] = urllib
.unquote(ev
)
752 ctx
= context
.memctx(repo
, (p1
, p2
), data
,
753 files
.keys(), getfilectx
,
754 user
, (date
, tz
), extra
)
756 tmp
= encoding
.encoding
757 encoding
.encoding
= 'utf-8'
759 node
= hghex(repo
.commitctx(ctx
))
761 encoding
.encoding
= tmp
763 rev
= repo
[node
].rev()
765 parsed_refs
[ref
] = node
766 marks
.new_mark(rev
, commit_mark
)
768 def parse_reset(parser
):
774 if parser
.check('commit'):
777 if not parser
.check('from'):
779 from_mark
= parser
.get_mark()
782 node
= parser
.repo
.changelog
.node(mark_to_rev(from_mark
))
783 parsed_refs
[ref
] = hghex(node
)
785 def parse_tag(parser
):
788 from_mark
= parser
.get_mark()
790 tagger
= parser
.get_author()
792 data
= parser
.get_data()
795 parsed_tags
[name
] = (tagger
, data
)
797 def write_tag(repo
, tag
, node
, msg
, author
):
798 branch
= repo
[node
].branch()
799 tip
= branch_tip(repo
, branch
)
802 def getfilectx(repo
, memctx
, f
):
804 fctx
= tip
.filectx(f
)
806 except error
.ManifestLookupError
:
808 content
= data
+ "%s %s\n" % (node
, tag
)
809 return context
.memfilectx(f
, content
, False, False, None)
814 author
= (None, 0, 0)
815 user
, date
, tz
= author
817 ctx
= context
.memctx(repo
, (p1
, p2
), msg
,
818 ['.hgtags'], getfilectx
,
819 user
, (date
, tz
), {'branch' : branch
})
821 tmp
= encoding
.encoding
822 encoding
.encoding
= 'utf-8'
824 tagnode
= repo
.commitctx(ctx
)
826 encoding
.encoding
= tmp
830 def do_export(parser
):
831 global parsed_refs
, bmarks
, peer
837 for line
in parser
.each_block('done'):
838 if parser
.check('blob'):
840 elif parser
.check('commit'):
842 elif parser
.check('reset'):
844 elif parser
.check('tag'):
846 elif parser
.check('feature'):
849 die('unhandled export command: %s' % line
)
851 for ref
, node
in parsed_refs
.iteritems():
853 if ref
.startswith('refs/heads/branches'):
854 branch
= ref
[len('refs/heads/branches/'):]
855 if branch
in branches
and bnode
in branches
[branch
]:
859 elif ref
.startswith('refs/heads/'):
860 bmark
= ref
[len('refs/heads/'):]
861 p_bmarks
.append((bmark
, node
))
863 elif ref
.startswith('refs/tags/'):
864 tag
= ref
[len('refs/tags/'):]
866 author
, msg
= parsed_tags
.get(tag
, (None, None))
869 msg
= 'Added tag %s for changeset %s' % (tag
, node
[:12]);
870 write_tag(parser
.repo
, tag
, node
, msg
, author
)
872 fp
= parser
.repo
.opener('localtags', 'a')
873 fp
.write('%s %s\n' % (node
, tag
))
877 # transport-helper/fast-export bugs
881 parser
.repo
.push(peer
, force
=force_push
, newbranch
=True)
882 remote_bmarks
= peer
.listkeys('bookmarks')
885 for bmark
, node
in p_bmarks
:
886 ref
= 'refs/heads/' + bmark
890 old
= bmarks
[bmark
].hex()
897 if bmark
== 'master' and 'master' not in parser
.repo
._bookmarks
:
901 elif bookmarks
.pushbookmark(parser
.repo
, bmark
, old
, new
):
905 print "error %s" % ref
909 old
= remote_bmarks
.get(bmark
, '')
910 if not peer
.pushkey('bookmarks', bmark
, old
, new
):
911 print "error %s" % ref
918 def fix_path(alias
, repo
, orig_url
):
919 url
= urlparse
.urlparse(orig_url
, 'file')
920 if url
.scheme
!= 'file' or os
.path
.isabs(url
.path
):
922 abs_url
= urlparse
.urljoin("%s/" % os
.getcwd(), orig_url
)
923 cmd
= ['git', 'config', 'remote.%s.url' % alias
, "hg::%s" % abs_url
]
927 global prefix
, gitdir
, dirname
, branches
, bmarks
928 global marks
, blob_marks
, parsed_refs
929 global peer
, mode
, bad_mail
, bad_name
930 global track_branches
, force_push
, is_tmp
938 hg_git_compat
= get_config_bool('remote-hg.hg-git-compat')
939 track_branches
= get_config_bool('remote-hg.track-branches', True)
940 force_push
= get_config_bool('remote-hg.force-push')
944 bad_mail
= 'none@none'
953 alias
= hashlib
.sha1(alias
).hexdigest()
957 gitdir
= os
.environ
['GIT_DIR']
958 dirname
= os
.path
.join(gitdir
, 'hg', alias
)
967 repo
= get_repo(url
, alias
)
968 prefix
= 'refs/hg/%s' % alias
971 fix_path(alias
, peer
or repo
, url
)
973 marks_path
= os
.path
.join(dirname
, 'marks-hg')
974 marks
= Marks(marks_path
)
976 if sys
.platform
== 'win32':
978 msvcrt
.setmode(sys
.stdout
.fileno(), os
.O_BINARY
)
980 parser
= Parser(repo
)
982 if parser
.check('capabilities'):
983 do_capabilities(parser
)
984 elif parser
.check('list'):
986 elif parser
.check('import'):
988 elif parser
.check('export'):
991 die('unhandled command: %s' % line
)
1000 shutil
.rmtree(dirname
)
1002 atexit
.register(bye
)
1003 sys
.exit(main(sys
.argv
))