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
, '')
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
, repo
):
112 if self
.version
< VERSION
:
113 if self
.version
== 1:
117 if self
.version
< VERSION
:
119 self
.version
= VERSION
129 if not os
.path
.exists(self
.path
):
132 tmp
= json
.load(open(self
.path
))
134 self
.tips
= tmp
['tips']
135 self
.marks
= tmp
['marks']
136 self
.last_mark
= tmp
['last-mark']
137 self
.version
= tmp
.get('version', 1)
139 for rev
, mark
in self
.marks
.iteritems():
140 self
.rev_marks
[mark
] = rev
142 def upgrade_one(self
):
144 return hghex(self
.repo
.changelog
.node(int(rev
)))
145 self
.tips
= dict((name
, get_id(rev
)) for name
, rev
in self
.tips
.iteritems())
146 self
.marks
= dict((get_id(rev
), mark
) for rev
, mark
in self
.marks
.iteritems())
147 self
.rev_marks
= dict((mark
, get_id(rev
)) for mark
, rev
in self
.rev_marks
.iteritems())
151 return { 'tips': self
.tips
, 'marks': self
.marks
, 'last-mark' : self
.last_mark
, 'version' : self
.version
}
154 json
.dump(self
.dict(), open(self
.path
, 'w'))
157 return str(self
.dict())
159 def from_rev(self
, rev
):
160 return self
.marks
[rev
]
162 def to_rev(self
, mark
):
163 return self
.rev_marks
[mark
]
167 return self
.last_mark
169 def get_mark(self
, rev
):
171 self
.marks
[rev
] = self
.last_mark
172 return self
.last_mark
174 def new_mark(self
, rev
, mark
):
175 self
.marks
[rev
] = mark
176 self
.rev_marks
[mark
] = rev
177 self
.last_mark
= mark
179 def is_marked(self
, rev
):
180 return rev
in self
.marks
182 def get_tip(self
, branch
):
183 return self
.tips
.get(branch
, None)
185 def set_tip(self
, branch
, tip
):
186 self
.tips
[branch
] = tip
190 def __init__(self
, repo
):
192 self
.line
= self
.get_line()
195 return sys
.stdin
.readline().strip()
197 def __getitem__(self
, i
):
198 return self
.line
.split()[i
]
200 def check(self
, word
):
201 return self
.line
.startswith(word
)
203 def each_block(self
, separator
):
204 while self
.line
!= separator
:
206 self
.line
= self
.get_line()
209 return self
.each_block('')
212 self
.line
= self
.get_line()
213 if self
.line
== 'done':
217 i
= self
.line
.index(':') + 1
218 return int(self
.line
[i
:])
221 if not self
.check('data'):
223 i
= self
.line
.index(' ') + 1
224 size
= int(self
.line
[i
:])
225 return sys
.stdin
.read(size
)
227 def get_author(self
):
231 m
= RAW_AUTHOR_RE
.match(self
.line
)
234 _
, name
, email
, date
, tz
= m
.groups()
235 if name
and 'ext:' in name
:
236 m
= re
.match('^(.+?) ext:\((.+)\)$', name
)
239 ex
= urllib
.unquote(m
.group(2))
241 if email
!= bad_mail
:
243 user
= '%s <%s>' % (name
, email
)
245 user
= '<%s>' % (email
)
253 tz
= ((tz
/ 100) * 3600) + ((tz
% 100) * 60)
254 return (user
, int(date
), -tz
)
256 def fix_file_path(path
):
257 if not os
.path
.isabs(path
):
259 return os
.path
.relpath(path
, '/')
261 def export_files(files
):
262 global marks
, filenodes
266 fid
= node
.hex(f
.filenode())
269 mark
= filenodes
[fid
]
271 mark
= marks
.next_mark()
272 filenodes
[fid
] = mark
276 print "mark :%u" % mark
277 print "data %d" % len(d
)
280 path
= fix_file_path(f
.path())
281 final
.append((gitmode(f
.flags()), mark
, path
))
285 def get_filechanges(repo
, ctx
, parent
):
290 # load earliest manifest first for caching reasons
291 prev
= parent
.manifest().copy()
296 if (cur
.flags(fn
) != prev
.flags(fn
) or cur
[fn
] != prev
[fn
]):
301 removed |
= set(prev
.keys())
303 return added | modified
, removed
305 def fixup_user_git(user
):
307 user
= user
.replace('"', '')
308 m
= AUTHOR_RE
.match(user
)
311 mail
= m
.group(2).strip()
313 m
= EMAIL_RE
.match(user
)
318 m
= NAME_RE
.match(user
)
320 name
= m
.group(1).strip()
323 def fixup_user_hg(user
):
325 # stole this from hg-git
326 return re
.sub('[<>\n]', '?', name
.lstrip('< ').rstrip('> '))
328 m
= AUTHOR_HG_RE
.match(user
)
330 name
= sanitize(m
.group(1))
331 mail
= sanitize(m
.group(2))
334 name
+= ' ext:(' + urllib
.quote(ex
) + ')'
336 name
= sanitize(user
)
344 def fixup_user(user
):
345 global mode
, bad_mail
348 name
, mail
= fixup_user_git(user
)
350 name
, mail
= fixup_user_hg(user
)
357 return '%s <%s>' % (name
, mail
)
359 def updatebookmarks(repo
, peer
):
360 remotemarks
= peer
.listkeys('bookmarks')
361 localmarks
= repo
._bookmarks
366 for k
, v
in remotemarks
.iteritems():
367 localmarks
[k
] = hgbin(v
)
369 if hasattr(localmarks
, 'write'):
372 bookmarks
.write(repo
)
374 def get_repo(url
, alias
):
378 myui
.setconfig('ui', 'interactive', 'off')
379 myui
.fout
= sys
.stderr
381 if get_config_bool('remote-hg.insecure'):
382 myui
.setconfig('web', 'cacerts', '')
384 extensions
.loadall(myui
)
386 if hg
.islocal(url
) and not os
.environ
.get('GIT_REMOTE_HG_TEST_REMOTE'):
387 repo
= hg
.repository(myui
, url
)
388 if not os
.path
.exists(dirname
):
391 shared_path
= os
.path
.join(gitdir
, 'hg')
392 if not os
.path
.exists(shared_path
):
394 hg
.clone(myui
, {}, url
, shared_path
, update
=False, pull
=True)
396 die('Repository error')
398 if not os
.path
.exists(dirname
):
401 local_path
= os
.path
.join(dirname
, 'clone')
402 if not os
.path
.exists(local_path
):
403 hg
.share(myui
, shared_path
, local_path
, update
=False)
405 repo
= hg
.repository(myui
, local_path
)
407 peer
= hg
.peer(myui
, {}, url
)
409 die('Repository error')
410 repo
.pull(peer
, heads
=None, force
=True)
412 updatebookmarks(repo
, peer
)
416 def rev_to_mark(rev
):
418 return marks
.from_rev(rev
.hex())
420 def mark_to_rev(mark
):
422 return marks
.to_rev(mark
)
424 def export_ref(repo
, name
, kind
, head
):
425 global prefix
, marks
, mode
427 ename
= '%s/%s' % (kind
, name
)
428 tip
= marks
.get_tip(ename
)
429 if tip
and tip
in repo
:
430 tip
= repo
[tip
].rev()
434 revs
= xrange(tip
, head
.rev() + 1)
442 if marks
.is_marked(c
.hex()):
445 (manifest
, user
, (time
, tz
), files
, desc
, extra
) = repo
.changelog
.read(node
)
446 rev_branch
= extra
['branch']
448 author
= "%s %d %s" % (fixup_user(user
), time
, gittz(tz
))
449 if 'committer' in extra
:
450 user
, time
, tz
= extra
['committer'].rsplit(' ', 2)
451 committer
= "%s %s %s" % (user
, time
, gittz(int(tz
)))
455 parents
= [repo
[p
] for p
in repo
.changelog
.parentrevs(rev
) if p
>= 0]
457 if len(parents
) == 0:
458 modified
= c
.manifest().keys()
461 modified
, removed
= get_filechanges(repo
, c
, parents
[0])
468 if rev_branch
!= 'default':
469 extra_msg
+= 'branch : %s\n' % rev_branch
473 if f
not in c
.manifest():
475 rename
= c
.filectx(f
).renamed()
477 renames
.append((rename
[0], f
))
480 extra_msg
+= "rename : %s => %s\n" % e
482 for key
, value
in extra
.iteritems():
483 if key
in ('author', 'committer', 'encoding', 'message', 'branch', 'hg-git'):
486 extra_msg
+= "extra : %s : %s\n" % (key
, urllib
.quote(value
))
489 desc
+= '\n--HG--\n' + extra_msg
491 if len(parents
) == 0 and rev
:
492 print 'reset %s/%s' % (prefix
, ename
)
494 modified_final
= export_files(c
.filectx(f
) for f
in modified
)
496 print "commit %s/%s" % (prefix
, ename
)
497 print "mark :%d" % (marks
.get_mark(c
.hex()))
498 print "author %s" % (author
)
499 print "committer %s" % (committer
)
500 print "data %d" % (len(desc
))
504 print "from :%s" % (rev_to_mark(parents
[0]))
506 print "merge :%s" % (rev_to_mark(parents
[1]))
508 for f
in modified_final
:
509 print "M %s :%u %s" % f
511 print "D %s" % (fix_file_path(f
))
514 progress
= (rev
- tip
)
515 if (progress
% 100 == 0):
516 print "progress revision %d '%s' (%d/%d)" % (rev
, name
, progress
, total
)
518 # make sure the ref is updated
519 print "reset %s/%s" % (prefix
, ename
)
520 print "from :%u" % rev_to_mark(head
)
523 marks
.set_tip(ename
, head
.hex())
525 def export_tag(repo
, tag
):
526 export_ref(repo
, tag
, 'tags', repo
[hgref(tag
)])
528 def export_bookmark(repo
, bmark
):
529 head
= bmarks
[hgref(bmark
)]
530 export_ref(repo
, bmark
, 'bookmarks', head
)
532 def export_branch(repo
, branch
):
533 tip
= get_branch_tip(repo
, branch
)
535 export_ref(repo
, branch
, 'branches', head
)
537 def export_head(repo
):
539 export_ref(repo
, g_head
[0], 'bookmarks', g_head
[1])
541 def do_capabilities(parser
):
542 global prefix
, dirname
546 print "refspec refs/heads/branches/*:%s/branches/*" % prefix
547 print "refspec refs/heads/*:%s/bookmarks/*" % prefix
548 print "refspec refs/tags/*:%s/tags/*" % prefix
550 path
= os
.path
.join(dirname
, 'marks-git')
552 if os
.path
.exists(path
):
553 print "*import-marks %s" % path
554 print "*export-marks %s" % path
558 def branch_tip(repo
, branch
):
559 # older versions of mercurial don't have this
560 if hasattr(repo
, 'branchtip'):
561 return repo
.branchtip(branch
)
563 return repo
.branchtags()[branch
]
565 def get_branch_tip(repo
, branch
):
568 heads
= branches
.get(hgref(branch
), None)
572 # verify there's only one head
574 warn("Branch '%s' has more than one head, consider merging" % branch
)
575 return branch_tip(repo
, hgref(branch
))
579 def list_head(repo
, cur
):
580 global g_head
, bmarks
, fake_bmark
582 if 'default' not in repo
:
586 node
= repo
['default']
587 head
= 'master' if not 'master' in bmarks
else 'default'
592 print "@refs/heads/%s HEAD" % head
593 g_head
= (head
, node
)
596 global branches
, bmarks
, track_branches
599 for bmark
, node
in bookmarks
.listbookmarks(repo
).iteritems():
600 bmarks
[bmark
] = repo
[node
]
602 cur
= repo
.dirstate
.branch()
607 for branch
in repo
.branchmap():
608 heads
= repo
.branchheads(branch
)
610 branches
[branch
] = heads
612 for branch
in branches
:
613 print "? refs/heads/branches/%s" % gitref(branch
)
616 print "? refs/heads/%s" % gitref(bmark
)
618 for tag
, node
in repo
.tagslist():
621 print "? refs/tags/%s" % gitref(tag
)
625 def do_import(parser
):
628 path
= os
.path
.join(dirname
, 'marks-git')
631 if os
.path
.exists(path
):
632 print "feature import-marks=%s" % path
633 print "feature export-marks=%s" % path
634 print "feature force"
637 tmp
= encoding
.encoding
638 encoding
.encoding
= 'utf-8'
640 # lets get all the import lines
641 while parser
.check('import'):
646 elif ref
.startswith('refs/heads/branches/'):
647 branch
= ref
[len('refs/heads/branches/'):]
648 export_branch(repo
, branch
)
649 elif ref
.startswith('refs/heads/'):
650 bmark
= ref
[len('refs/heads/'):]
651 export_bookmark(repo
, bmark
)
652 elif ref
.startswith('refs/tags/'):
653 tag
= ref
[len('refs/tags/'):]
654 export_tag(repo
, tag
)
658 encoding
.encoding
= tmp
662 def parse_blob(parser
):
666 mark
= parser
.get_mark()
668 data
= parser
.get_data()
669 blob_marks
[mark
] = data
672 def get_merge_files(repo
, p1
, p2
, files
):
673 for e
in repo
[p1
].files():
675 if e
not in repo
[p1
].manifest():
677 f
= { 'ctx' : repo
[p1
][e
] }
680 def parse_commit(parser
):
681 global marks
, blob_marks
, parsed_refs
684 from_mark
= merge_mark
= None
689 commit_mark
= parser
.get_mark()
691 author
= parser
.get_author()
693 committer
= parser
.get_author()
695 data
= parser
.get_data()
697 if parser
.check('from'):
698 from_mark
= parser
.get_mark()
700 if parser
.check('merge'):
701 merge_mark
= parser
.get_mark()
703 if parser
.check('merge'):
704 die('octopus merges are not supported yet')
706 # fast-export adds an extra newline
713 if parser
.check('M'):
714 t
, m
, mark_ref
, path
= line
.split(' ', 3)
715 mark
= int(mark_ref
[1:])
716 f
= { 'mode' : hgmode(m
), 'data' : blob_marks
[mark
] }
717 elif parser
.check('D'):
718 t
, path
= line
.split(' ', 1)
719 f
= { 'deleted' : True }
721 die('Unknown file command: %s' % line
)
724 def getfilectx(repo
, memctx
, f
):
730 is_exec
= of
['mode'] == 'x'
731 is_link
= of
['mode'] == 'l'
732 rename
= of
.get('rename', None)
733 return context
.memfilectx(f
, of
['data'],
734 is_link
, is_exec
, rename
)
738 user
, date
, tz
= author
741 if committer
!= author
:
742 extra
['committer'] = "%s %u %u" % committer
745 p1
= mark_to_rev(from_mark
)
750 p2
= mark_to_rev(merge_mark
)
755 # If files changed from any of the parents, hg wants to know, but in git if
756 # nothing changed from the first parent, nothing changed.
759 get_merge_files(repo
, p1
, p2
, files
)
761 # Check if the ref is supposed to be a named branch
762 if ref
.startswith('refs/heads/branches/'):
763 branch
= ref
[len('refs/heads/branches/'):]
764 extra
['branch'] = hgref(branch
)
767 i
= data
.find('\n--HG--\n')
769 tmp
= data
[i
+ len('\n--HG--\n'):].strip()
770 for k
, v
in [e
.split(' : ', 1) for e
in tmp
.split('\n')]:
772 old
, new
= v
.split(' => ', 1)
773 files
[new
]['rename'] = old
777 ek
, ev
= v
.split(' : ', 1)
778 extra
[ek
] = urllib
.unquote(ev
)
781 ctx
= context
.memctx(repo
, (p1
, p2
), data
,
782 files
.keys(), getfilectx
,
783 user
, (date
, tz
), extra
)
785 tmp
= encoding
.encoding
786 encoding
.encoding
= 'utf-8'
788 node
= hghex(repo
.commitctx(ctx
))
790 encoding
.encoding
= tmp
792 parsed_refs
[ref
] = node
793 marks
.new_mark(node
, commit_mark
)
795 def parse_reset(parser
):
801 if parser
.check('commit'):
804 if not parser
.check('from'):
806 from_mark
= parser
.get_mark()
809 rev
= mark_to_rev(from_mark
)
810 parsed_refs
[ref
] = rev
812 def parse_tag(parser
):
815 from_mark
= parser
.get_mark()
817 tagger
= parser
.get_author()
819 data
= parser
.get_data()
822 parsed_tags
[name
] = (tagger
, data
)
824 def write_tag(repo
, tag
, node
, msg
, author
):
825 branch
= repo
[node
].branch()
826 tip
= branch_tip(repo
, branch
)
829 def getfilectx(repo
, memctx
, f
):
831 fctx
= tip
.filectx(f
)
833 except error
.ManifestLookupError
:
835 content
= data
+ "%s %s\n" % (node
, tag
)
836 return context
.memfilectx(f
, content
, False, False, None)
841 author
= (None, 0, 0)
842 user
, date
, tz
= author
844 ctx
= context
.memctx(repo
, (p1
, p2
), msg
,
845 ['.hgtags'], getfilectx
,
846 user
, (date
, tz
), {'branch' : branch
})
848 tmp
= encoding
.encoding
849 encoding
.encoding
= 'utf-8'
851 tagnode
= repo
.commitctx(ctx
)
853 encoding
.encoding
= tmp
857 def do_export(parser
):
858 global parsed_refs
, bmarks
, peer
865 for line
in parser
.each_block('done'):
866 if parser
.check('blob'):
868 elif parser
.check('commit'):
870 elif parser
.check('reset'):
872 elif parser
.check('tag'):
874 elif parser
.check('feature'):
877 die('unhandled export command: %s' % line
)
879 for ref
, node
in parsed_refs
.iteritems():
881 if ref
.startswith('refs/heads/branches'):
882 branch
= ref
[len('refs/heads/branches/'):]
883 if branch
in branches
and bnode
in branches
[branch
]:
888 elif ref
.startswith('refs/heads/'):
889 bmark
= ref
[len('refs/heads/'):]
891 old
= bmarks
[bmark
].hex() if bmark
in bmarks
else ''
897 if bmark
!= fake_bmark
and \
898 not (bmark
== 'master' and bmark
not in parser
.repo
._bookmarks
):
899 p_bmarks
.append((ref
, bmark
, old
, new
))
902 elif ref
.startswith('refs/tags/'):
903 tag
= ref
[len('refs/tags/'):]
905 author
, msg
= parsed_tags
.get(tag
, (None, None))
908 msg
= 'Added tag %s for changeset %s' % (tag
, node
[:12]);
909 tagnode
= write_tag(parser
.repo
, tag
, node
, msg
, author
)
912 fp
= parser
.repo
.opener('localtags', 'a')
913 fp
.write('%s %s\n' % (node
, tag
))
918 # transport-helper/fast-export bugs
922 parser
.repo
.push(peer
, force
=force_push
, newbranch
=True, revs
=list(p_revs
))
924 # update remote bookmarks
925 remote_bmarks
= peer
.listkeys('bookmarks')
926 for ref
, bmark
, old
, new
in p_bmarks
:
928 old
= remote_bmarks
.get(bmark
, '')
929 if not peer
.pushkey('bookmarks', bmark
, old
, new
):
930 print "error %s" % ref
932 # update local bookmarks
933 for ref
, bmark
, old
, new
in p_bmarks
:
934 if not bookmarks
.pushbookmark(parser
.repo
, bmark
, old
, new
):
935 print "error %s" % ref
939 def fix_path(alias
, repo
, orig_url
):
940 url
= urlparse
.urlparse(orig_url
, 'file')
941 if url
.scheme
!= 'file' or os
.path
.isabs(url
.path
):
943 abs_url
= urlparse
.urljoin("%s/" % os
.getcwd(), orig_url
)
944 cmd
= ['git', 'config', 'remote.%s.url' % alias
, "hg::%s" % abs_url
]
948 global prefix
, gitdir
, dirname
, branches
, bmarks
949 global marks
, blob_marks
, parsed_refs
950 global peer
, mode
, bad_mail
, bad_name
951 global track_branches
, force_push
, is_tmp
960 hg_git_compat
= get_config_bool('remote-hg.hg-git-compat')
961 track_branches
= get_config_bool('remote-hg.track-branches', True)
962 force_push
= get_config_bool('remote-hg.force-push')
966 bad_mail
= 'none@none'
975 alias
= hashlib
.sha1(alias
).hexdigest()
979 gitdir
= os
.environ
['GIT_DIR']
980 dirname
= os
.path
.join(gitdir
, 'hg', alias
)
990 repo
= get_repo(url
, alias
)
991 prefix
= 'refs/hg/%s' % alias
994 fix_path(alias
, peer
or repo
, url
)
996 marks_path
= os
.path
.join(dirname
, 'marks-hg')
997 marks
= Marks(marks_path
, repo
)
999 if sys
.platform
== 'win32':
1001 msvcrt
.setmode(sys
.stdout
.fileno(), os
.O_BINARY
)
1003 parser
= Parser(repo
)
1005 if parser
.check('capabilities'):
1006 do_capabilities(parser
)
1007 elif parser
.check('list'):
1009 elif parser
.check('import'):
1011 elif parser
.check('export'):
1014 die('unhandled command: %s' % line
)
1023 shutil
.rmtree(dirname
)
1025 atexit
.register(bye
)
1026 sys
.exit(main(sys
.argv
))