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 from mercurial
import hg
, ui
, bookmarks
, context
, util
, encoding
, node
23 # If you want to switch to hg-git compatibility mode:
24 # git config --global remote-hg.hg-git-compat true
26 # If you are not in hg-git-compat mode and want to disable the tracking of
28 # git config --global remote-hg.track-branches false
31 # Sensible defaults for git.
32 # hg bookmarks are exported as git branches, hg branches are prefixed
33 # with 'branches/', HEAD is a special case.
37 # Only hg bookmarks are exported as git branches.
38 # Commits are modified to preserve hg information and allow bidirectionality.
41 NAME_RE
= re
.compile('^([^<>]+)')
42 AUTHOR_RE
= re
.compile('^([^<>]+?)? ?<([^<>]*)>$')
43 AUTHOR_HG_RE
= re
.compile('^(.*?) ?<(.*?)(?:>(.+)?)?$')
44 RAW_AUTHOR_RE
= re
.compile('^(\w+) (?:(.+)? )?<(.*)> (\d+) ([+-]\d+)')
47 sys
.stderr
.write('ERROR: %s\n' % (msg
% args
))
51 sys
.stderr
.write('WARNING: %s\n' % (msg
% args
))
54 return 'l' in flags
and '120000' or 'x' in flags
and '100755' or '100644'
57 return '%+03d%02d' % (-tz
/ 3600, -tz
% 3600 / 60)
60 m
= { '100755': 'x', '120000': 'l' }
61 return m
.get(mode
, '')
64 return hg
.node
.hex(node
)
66 def get_config(config
):
67 cmd
= ['git', 'config', '--get', config
]
68 process
= subprocess
.Popen(cmd
, stdout
=subprocess
.PIPE
)
69 output
, _
= process
.communicate()
74 def __init__(self
, path
):
84 if not os
.path
.exists(self
.path
):
87 tmp
= json
.load(open(self
.path
))
89 self
.tips
= tmp
['tips']
90 self
.marks
= tmp
['marks']
91 self
.last_mark
= tmp
['last-mark']
93 for rev
, mark
in self
.marks
.iteritems():
94 self
.rev_marks
[mark
] = int(rev
)
97 return { 'tips': self
.tips
, 'marks': self
.marks
, 'last-mark' : self
.last_mark
}
100 json
.dump(self
.dict(), open(self
.path
, 'w'))
103 return str(self
.dict())
105 def from_rev(self
, rev
):
106 return self
.marks
[str(rev
)]
108 def to_rev(self
, mark
):
109 return self
.rev_marks
[mark
]
111 def get_mark(self
, rev
):
113 self
.marks
[str(rev
)] = self
.last_mark
114 return self
.last_mark
116 def new_mark(self
, rev
, mark
):
117 self
.marks
[str(rev
)] = mark
118 self
.rev_marks
[mark
] = rev
119 self
.last_mark
= mark
121 def is_marked(self
, rev
):
122 return self
.marks
.has_key(str(rev
))
124 def get_tip(self
, branch
):
125 return self
.tips
.get(branch
, 0)
127 def set_tip(self
, branch
, tip
):
128 self
.tips
[branch
] = tip
132 def __init__(self
, repo
):
134 self
.line
= self
.get_line()
137 return sys
.stdin
.readline().strip()
139 def __getitem__(self
, i
):
140 return self
.line
.split()[i
]
142 def check(self
, word
):
143 return self
.line
.startswith(word
)
145 def each_block(self
, separator
):
146 while self
.line
!= separator
:
148 self
.line
= self
.get_line()
151 return self
.each_block('')
154 self
.line
= self
.get_line()
155 if self
.line
== 'done':
159 i
= self
.line
.index(':') + 1
160 return int(self
.line
[i
:])
163 if not self
.check('data'):
165 i
= self
.line
.index(' ') + 1
166 size
= int(self
.line
[i
:])
167 return sys
.stdin
.read(size
)
169 def get_author(self
):
173 m
= RAW_AUTHOR_RE
.match(self
.line
)
176 _
, name
, email
, date
, tz
= m
.groups()
177 if name
and 'ext:' in name
:
178 m
= re
.match('^(.+?) ext:\((.+)\)$', name
)
181 ex
= urllib
.unquote(m
.group(2))
183 if email
!= bad_mail
:
185 user
= '%s <%s>' % (name
, email
)
187 user
= '<%s>' % (email
)
195 tz
= ((tz
/ 100) * 3600) + ((tz
% 100) * 60)
196 return (user
, int(date
), -tz
)
200 print "M %s inline %s" % (gitmode(fc
.flags()), fc
.path())
201 print "data %d" % len(d
)
204 def get_filechanges(repo
, ctx
, parent
):
210 prev
= repo
[parent
].manifest().copy()
214 if (cur
.flags(fn
) != prev
.flags(fn
) or cur
[fn
] != prev
[fn
]):
219 removed |
= set(prev
.keys())
221 return added | modified
, removed
223 def fixup_user_git(user
):
225 user
= user
.replace('"', '')
226 m
= AUTHOR_RE
.match(user
)
229 mail
= m
.group(2).strip()
231 m
= NAME_RE
.match(user
)
233 name
= m
.group(1).strip()
236 def fixup_user_hg(user
):
238 # stole this from hg-git
239 return re
.sub('[<>\n]', '?', name
.lstrip('< ').rstrip('> '))
241 m
= AUTHOR_HG_RE
.match(user
)
243 name
= sanitize(m
.group(1))
244 mail
= sanitize(m
.group(2))
247 name
+= ' ext:(' + urllib
.quote(ex
) + ')'
249 name
= sanitize(user
)
257 def fixup_user(user
):
258 global mode
, bad_mail
261 name
, mail
= fixup_user_git(user
)
263 name
, mail
= fixup_user_hg(user
)
270 return '%s <%s>' % (name
, mail
)
272 def get_repo(url
, alias
):
276 myui
.setconfig('ui', 'interactive', 'off')
277 myui
.fout
= sys
.stderr
280 repo
= hg
.repository(myui
, url
)
282 local_path
= os
.path
.join(dirname
, 'clone')
283 if not os
.path
.exists(local_path
):
284 peer
, dstpeer
= hg
.clone(myui
, {}, url
, local_path
, update
=False, pull
=True)
285 repo
= dstpeer
.local()
287 repo
= hg
.repository(myui
, local_path
)
288 peer
= hg
.peer(myui
, {}, url
)
289 repo
.pull(peer
, heads
=None, force
=True)
293 def rev_to_mark(rev
):
295 return marks
.from_rev(rev
)
297 def mark_to_rev(mark
):
299 return marks
.to_rev(mark
)
301 def export_ref(repo
, name
, kind
, head
):
302 global prefix
, marks
, mode
304 ename
= '%s/%s' % (kind
, name
)
305 tip
= marks
.get_tip(ename
)
307 # mercurial takes too much time checking this
308 if tip
and tip
== head
.rev():
311 revs
= xrange(tip
, head
.rev() + 1)
314 revs
= [rev
for rev
in revs
if not marks
.is_marked(rev
)]
319 (manifest
, user
, (time
, tz
), files
, desc
, extra
) = repo
.changelog
.read(c
.node())
320 rev_branch
= extra
['branch']
322 author
= "%s %d %s" % (fixup_user(user
), time
, gittz(tz
))
323 if 'committer' in extra
:
324 user
, time
, tz
= extra
['committer'].rsplit(' ', 2)
325 committer
= "%s %s %s" % (user
, time
, gittz(int(tz
)))
329 parents
= [p
for p
in repo
.changelog
.parentrevs(rev
) if p
>= 0]
331 if len(parents
) == 0:
332 modified
= c
.manifest().keys()
335 modified
, removed
= get_filechanges(repo
, c
, parents
[0])
340 if rev_branch
!= 'default':
341 extra_msg
+= 'branch : %s\n' % rev_branch
345 if f
not in c
.manifest():
347 rename
= c
.filectx(f
).renamed()
349 renames
.append((rename
[0], f
))
352 extra_msg
+= "rename : %s => %s\n" % e
354 for key
, value
in extra
.iteritems():
355 if key
in ('author', 'committer', 'encoding', 'message', 'branch', 'hg-git'):
358 extra_msg
+= "extra : %s : %s\n" % (key
, urllib
.quote(value
))
362 desc
+= '\n--HG--\n' + extra_msg
364 if len(parents
) == 0 and rev
:
365 print 'reset %s/%s' % (prefix
, ename
)
367 print "commit %s/%s" % (prefix
, ename
)
368 print "mark :%d" % (marks
.get_mark(rev
))
369 print "author %s" % (author
)
370 print "committer %s" % (committer
)
371 print "data %d" % (len(desc
))
375 print "from :%s" % (rev_to_mark(parents
[0]))
377 print "merge :%s" % (rev_to_mark(parents
[1]))
380 export_file(c
.filectx(f
))
386 if (count
% 100 == 0):
387 print "progress revision %d '%s' (%d/%d)" % (rev
, name
, count
, len(revs
))
388 print "#############################################################"
390 # make sure the ref is updated
391 print "reset %s/%s" % (prefix
, ename
)
392 print "from :%u" % rev_to_mark(rev
)
395 marks
.set_tip(ename
, rev
)
397 def export_tag(repo
, tag
):
398 export_ref(repo
, tag
, 'tags', repo
[tag
])
400 def export_bookmark(repo
, bmark
):
402 export_ref(repo
, bmark
, 'bookmarks', head
)
404 def export_branch(repo
, branch
):
405 tip
= get_branch_tip(repo
, branch
)
407 export_ref(repo
, branch
, 'branches', head
)
409 def export_head(repo
):
411 export_ref(repo
, g_head
[0], 'bookmarks', g_head
[1])
413 def do_capabilities(parser
):
414 global prefix
, dirname
418 print "refspec refs/heads/branches/*:%s/branches/*" % prefix
419 print "refspec refs/heads/*:%s/bookmarks/*" % prefix
420 print "refspec refs/tags/*:%s/tags/*" % prefix
422 path
= os
.path
.join(dirname
, 'marks-git')
424 if os
.path
.exists(path
):
425 print "*import-marks %s" % path
426 print "*export-marks %s" % path
430 def get_branch_tip(repo
, branch
):
433 heads
= branches
.get(branch
, None)
437 # verify there's only one head
439 warn("Branch '%s' has more than one head, consider merging" % branch
)
440 # older versions of mercurial don't have this
441 if hasattr(repo
, "branchtip"):
442 return repo
.branchtip(branch
)
446 def list_head(repo
, cur
):
447 global g_head
, bmarks
449 head
= bookmarks
.readcurrent(repo
)
453 # fake bookmark from current branch
460 if head
== 'default':
464 print "@refs/heads/%s HEAD" % head
465 g_head
= (head
, node
)
468 global branches
, bmarks
, mode
, track_branches
471 for bmark
, node
in bookmarks
.listbookmarks(repo
).iteritems():
472 bmarks
[bmark
] = repo
[node
]
474 cur
= repo
.dirstate
.branch()
479 for branch
in repo
.branchmap():
480 heads
= repo
.branchheads(branch
)
482 branches
[branch
] = heads
484 for branch
in branches
:
485 print "? refs/heads/branches/%s" % branch
488 print "? refs/heads/%s" % bmark
490 for tag
, node
in repo
.tagslist():
493 print "? refs/tags/%s" % tag
497 def do_import(parser
):
500 path
= os
.path
.join(dirname
, 'marks-git')
503 if os
.path
.exists(path
):
504 print "feature import-marks=%s" % path
505 print "feature export-marks=%s" % path
508 tmp
= encoding
.encoding
509 encoding
.encoding
= 'utf-8'
511 # lets get all the import lines
512 while parser
.check('import'):
517 elif ref
.startswith('refs/heads/branches/'):
518 branch
= ref
[len('refs/heads/branches/'):]
519 export_branch(repo
, branch
)
520 elif ref
.startswith('refs/heads/'):
521 bmark
= ref
[len('refs/heads/'):]
522 export_bookmark(repo
, bmark
)
523 elif ref
.startswith('refs/tags/'):
524 tag
= ref
[len('refs/tags/'):]
525 export_tag(repo
, tag
)
529 encoding
.encoding
= tmp
533 def parse_blob(parser
):
537 mark
= parser
.get_mark()
539 data
= parser
.get_data()
540 blob_marks
[mark
] = data
543 def get_merge_files(repo
, p1
, p2
, files
):
544 for e
in repo
[p1
].files():
546 if e
not in repo
[p1
].manifest():
548 f
= { 'ctx' : repo
[p1
][e
] }
551 def parse_commit(parser
):
552 global marks
, blob_marks
, parsed_refs
555 from_mark
= merge_mark
= None
560 commit_mark
= parser
.get_mark()
562 author
= parser
.get_author()
564 committer
= parser
.get_author()
566 data
= parser
.get_data()
568 if parser
.check('from'):
569 from_mark
= parser
.get_mark()
571 if parser
.check('merge'):
572 merge_mark
= parser
.get_mark()
574 if parser
.check('merge'):
575 die('octopus merges are not supported yet')
580 if parser
.check('M'):
581 t
, m
, mark_ref
, path
= line
.split(' ', 3)
582 mark
= int(mark_ref
[1:])
583 f
= { 'mode' : hgmode(m
), 'data' : blob_marks
[mark
] }
584 elif parser
.check('D'):
585 t
, path
= line
.split(' ', 1)
586 f
= { 'deleted' : True }
588 die('Unknown file command: %s' % line
)
591 def getfilectx(repo
, memctx
, f
):
597 is_exec
= of
['mode'] == 'x'
598 is_link
= of
['mode'] == 'l'
599 rename
= of
.get('rename', None)
600 return context
.memfilectx(f
, of
['data'],
601 is_link
, is_exec
, rename
)
605 user
, date
, tz
= author
608 if committer
!= author
:
609 extra
['committer'] = "%s %u %u" % committer
612 p1
= repo
.changelog
.node(mark_to_rev(from_mark
))
617 p2
= repo
.changelog
.node(mark_to_rev(merge_mark
))
622 # If files changed from any of the parents, hg wants to know, but in git if
623 # nothing changed from the first parent, nothing changed.
626 get_merge_files(repo
, p1
, p2
, files
)
629 i
= data
.find('\n--HG--\n')
631 tmp
= data
[i
+ len('\n--HG--\n'):].strip()
632 for k
, v
in [e
.split(' : ', 1) for e
in tmp
.split('\n')]:
634 old
, new
= v
.split(' => ', 1)
635 files
[new
]['rename'] = old
639 ek
, ev
= v
.split(' : ', 1)
640 extra
[ek
] = urllib
.unquote(ev
)
643 ctx
= context
.memctx(repo
, (p1
, p2
), data
,
644 files
.keys(), getfilectx
,
645 user
, (date
, tz
), extra
)
647 tmp
= encoding
.encoding
648 encoding
.encoding
= 'utf-8'
650 node
= repo
.commitctx(ctx
)
652 encoding
.encoding
= tmp
654 rev
= repo
[node
].rev()
656 parsed_refs
[ref
] = node
657 marks
.new_mark(rev
, commit_mark
)
659 def parse_reset(parser
):
665 if parser
.check('commit'):
668 if not parser
.check('from'):
670 from_mark
= parser
.get_mark()
673 node
= parser
.repo
.changelog
.node(mark_to_rev(from_mark
))
674 parsed_refs
[ref
] = node
676 def parse_tag(parser
):
679 from_mark
= parser
.get_mark()
681 tagger
= parser
.get_author()
683 data
= parser
.get_data()
688 def do_export(parser
):
689 global parsed_refs
, bmarks
, peer
695 for line
in parser
.each_block('done'):
696 if parser
.check('blob'):
698 elif parser
.check('commit'):
700 elif parser
.check('reset'):
702 elif parser
.check('tag'):
704 elif parser
.check('feature'):
707 die('unhandled export command: %s' % line
)
709 for ref
, node
in parsed_refs
.iteritems():
710 if ref
.startswith('refs/heads/branches'):
712 elif ref
.startswith('refs/heads/'):
713 bmark
= ref
[len('refs/heads/'):]
714 p_bmarks
.append((bmark
, node
))
716 elif ref
.startswith('refs/tags/'):
717 tag
= ref
[len('refs/tags/'):]
718 parser
.repo
.tag([tag
], node
, None, True, None, {})
721 # transport-helper/fast-export bugs
725 parser
.repo
.push(peer
, force
=False)
728 for bmark
, node
in p_bmarks
:
729 ref
= 'refs/heads/' + bmark
733 old
= bmarks
[bmark
].hex()
737 if bmark
== 'master' and 'master' not in parser
.repo
._bookmarks
:
740 elif bookmarks
.pushbookmark(parser
.repo
, bmark
, old
, new
):
744 print "error %s" % ref
751 def fix_path(alias
, repo
, orig_url
):
752 repo_url
= util
.url(repo
.url())
753 url
= util
.url(orig_url
)
754 if str(url
) == str(repo_url
):
756 cmd
= ['git', 'config', 'remote.%s.url' % alias
, "hg::%s" % repo_url
]
760 global prefix
, dirname
, branches
, bmarks
761 global marks
, blob_marks
, parsed_refs
762 global peer
, mode
, bad_mail
, bad_name
763 global track_branches
769 hg_git_compat
= False
770 track_branches
= True
772 if get_config('remote-hg.hg-git-compat') == 'true\n':
774 track_branches
= False
775 if get_config('remote-hg.track-branches') == 'false\n':
776 track_branches
= False
777 except subprocess
.CalledProcessError
:
782 bad_mail
= 'none@none'
791 alias
= util
.sha1(alias
).hexdigest()
795 gitdir
= os
.environ
['GIT_DIR']
796 dirname
= os
.path
.join(gitdir
, 'hg', alias
)
802 repo
= get_repo(url
, alias
)
803 prefix
= 'refs/hg/%s' % alias
806 fix_path(alias
, peer
or repo
, url
)
808 if not os
.path
.exists(dirname
):
811 marks_path
= os
.path
.join(dirname
, 'marks-hg')
812 marks
= Marks(marks_path
)
814 parser
= Parser(repo
)
816 if parser
.check('capabilities'):
817 do_capabilities(parser
)
818 elif parser
.check('list'):
820 elif parser
.check('import'):
822 elif parser
.check('export'):
825 die('unhandled command: %s' % line
)
831 shutil
.rmtree(dirname
)
833 sys
.exit(main(sys
.argv
))