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
23 # If you want to switch to hg-git compatibility mode:
24 # git config --global remote-hg.hg-git-compat true
27 # Sensible defaults for git.
28 # hg bookmarks are exported as git branches, hg branches are prefixed
29 # with 'branches/', HEAD is a special case.
33 # Only hg bookmarks are exported as git branches.
34 # Commits are modified to preserve hg information and allow bidirectionality.
37 NAME_RE
= re
.compile('^([^<>]+)')
38 AUTHOR_RE
= re
.compile('^([^<>]+?)? ?<([^<>]*)>$')
39 AUTHOR_HG_RE
= re
.compile('^(.*?) ?<(.*?)(?:>(.+)?)?$')
40 RAW_AUTHOR_RE
= re
.compile('^(\w+) (?:(.+)? )?<(.*)> (\d+) ([+-]\d+)')
43 sys
.stderr
.write('ERROR: %s\n' % (msg
% args
))
47 sys
.stderr
.write('WARNING: %s\n' % (msg
% args
))
50 return 'l' in flags
and '120000' or 'x' in flags
and '100755' or '100644'
53 return '%+03d%02d' % (-tz
/ 3600, -tz
% 3600 / 60)
56 m
= { '0100755': 'x', '0120000': 'l' }
57 return m
.get(mode
, '')
59 def get_config(config
):
60 cmd
= ['git', 'config', '--get', config
]
61 process
= subprocess
.Popen(cmd
, stdout
=subprocess
.PIPE
)
62 output
, _
= process
.communicate()
67 def __init__(self
, path
):
77 if not os
.path
.exists(self
.path
):
80 tmp
= json
.load(open(self
.path
))
82 self
.tips
= tmp
['tips']
83 self
.marks
= tmp
['marks']
84 self
.last_mark
= tmp
['last-mark']
86 for rev
, mark
in self
.marks
.iteritems():
87 self
.rev_marks
[mark
] = int(rev
)
90 return { 'tips': self
.tips
, 'marks': self
.marks
, 'last-mark' : self
.last_mark
}
93 json
.dump(self
.dict(), open(self
.path
, 'w'))
96 return str(self
.dict())
98 def from_rev(self
, rev
):
99 return self
.marks
[str(rev
)]
101 def to_rev(self
, mark
):
102 return self
.rev_marks
[mark
]
104 def get_mark(self
, rev
):
106 self
.marks
[str(rev
)] = self
.last_mark
107 return self
.last_mark
109 def new_mark(self
, rev
, mark
):
110 self
.marks
[str(rev
)] = mark
111 self
.rev_marks
[mark
] = rev
112 self
.last_mark
= mark
114 def is_marked(self
, rev
):
115 return self
.marks
.has_key(str(rev
))
117 def get_tip(self
, branch
):
118 return self
.tips
.get(branch
, 0)
120 def set_tip(self
, branch
, tip
):
121 self
.tips
[branch
] = tip
125 def __init__(self
, repo
):
127 self
.line
= self
.get_line()
130 return sys
.stdin
.readline().strip()
132 def __getitem__(self
, i
):
133 return self
.line
.split()[i
]
135 def check(self
, word
):
136 return self
.line
.startswith(word
)
138 def each_block(self
, separator
):
139 while self
.line
!= separator
:
141 self
.line
= self
.get_line()
144 return self
.each_block('')
147 self
.line
= self
.get_line()
148 if self
.line
== 'done':
152 i
= self
.line
.index(':') + 1
153 return int(self
.line
[i
:])
156 if not self
.check('data'):
158 i
= self
.line
.index(' ') + 1
159 size
= int(self
.line
[i
:])
160 return sys
.stdin
.read(size
)
162 def get_author(self
):
166 m
= RAW_AUTHOR_RE
.match(self
.line
)
169 _
, name
, email
, date
, tz
= m
.groups()
170 if name
and 'ext:' in name
:
171 m
= re
.match('^(.+?) ext:\((.+)\)$', name
)
174 ex
= urllib
.unquote(m
.group(2))
176 if email
!= bad_mail
:
178 user
= '%s <%s>' % (name
, email
)
180 user
= '<%s>' % (email
)
188 tz
= ((tz
/ 100) * 3600) + ((tz
% 100) * 60)
189 return (user
, int(date
), -tz
)
193 print "M %s inline %s" % (gitmode(fc
.flags()), fc
.path())
194 print "data %d" % len(d
)
197 def get_filechanges(repo
, ctx
, parent
):
203 prev
= repo
[parent
].manifest().copy()
207 if (cur
.flags(fn
) != prev
.flags(fn
) or cur
[fn
] != prev
[fn
]):
212 removed |
= set(prev
.keys())
214 return added | modified
, removed
216 def fixup_user_git(user
):
218 user
= user
.replace('"', '')
219 m
= AUTHOR_RE
.match(user
)
222 mail
= m
.group(2).strip()
224 m
= NAME_RE
.match(user
)
226 name
= m
.group(1).strip()
229 def fixup_user_hg(user
):
231 # stole this from hg-git
232 return re
.sub('[<>\n]', '?', name
.lstrip('< ').rstrip('> '))
234 m
= AUTHOR_HG_RE
.match(user
)
236 name
= sanitize(m
.group(1))
237 mail
= sanitize(m
.group(2))
240 name
+= ' ext:(' + urllib
.quote(ex
) + ')'
242 name
= sanitize(user
)
250 def fixup_user(user
):
251 global mode
, bad_mail
254 name
, mail
= fixup_user_git(user
)
256 name
, mail
= fixup_user_hg(user
)
263 return '%s <%s>' % (name
, mail
)
265 def get_repo(url
, alias
):
269 myui
.setconfig('ui', 'interactive', 'off')
272 repo
= hg
.repository(myui
, url
)
274 local_path
= os
.path
.join(dirname
, 'clone')
275 if not os
.path
.exists(local_path
):
276 peer
, dstpeer
= hg
.clone(myui
, {}, url
, local_path
, update
=False, pull
=True)
277 repo
= dstpeer
.local()
279 repo
= hg
.repository(myui
, local_path
)
280 peer
= hg
.peer(myui
, {}, url
)
281 repo
.pull(peer
, heads
=None, force
=True)
285 def rev_to_mark(rev
):
287 return marks
.from_rev(rev
)
289 def mark_to_rev(mark
):
291 return marks
.to_rev(mark
)
293 def export_ref(repo
, name
, kind
, head
):
294 global prefix
, marks
, mode
296 ename
= '%s/%s' % (kind
, name
)
297 tip
= marks
.get_tip(ename
)
299 # mercurial takes too much time checking this
300 if tip
and tip
== head
.rev():
303 revs
= xrange(tip
, head
.rev() + 1)
306 revs
= [rev
for rev
in revs
if not marks
.is_marked(rev
)]
311 (manifest
, user
, (time
, tz
), files
, desc
, extra
) = repo
.changelog
.read(c
.node())
312 rev_branch
= extra
['branch']
314 author
= "%s %d %s" % (fixup_user(user
), time
, gittz(tz
))
315 if 'committer' in extra
:
316 user
, time
, tz
= extra
['committer'].rsplit(' ', 2)
317 committer
= "%s %s %s" % (user
, time
, gittz(int(tz
)))
321 parents
= [p
for p
in repo
.changelog
.parentrevs(rev
) if p
>= 0]
323 if len(parents
) == 0:
324 modified
= c
.manifest().keys()
327 modified
, removed
= get_filechanges(repo
, c
, parents
[0])
332 if rev_branch
!= 'default':
333 extra_msg
+= 'branch : %s\n' % rev_branch
337 if f
not in c
.manifest():
339 rename
= c
.filectx(f
).renamed()
341 renames
.append((rename
[0], f
))
344 extra_msg
+= "rename : %s => %s\n" % e
346 for key
, value
in extra
.iteritems():
347 if key
in ('author', 'committer', 'encoding', 'message', 'branch', 'hg-git'):
350 extra_msg
+= "extra : %s : %s\n" % (key
, urllib
.quote(value
))
354 desc
+= '\n--HG--\n' + extra_msg
356 if len(parents
) == 0 and rev
:
357 print 'reset %s/%s' % (prefix
, ename
)
359 print "commit %s/%s" % (prefix
, ename
)
360 print "mark :%d" % (marks
.get_mark(rev
))
361 print "author %s" % (author
)
362 print "committer %s" % (committer
)
363 print "data %d" % (len(desc
))
367 print "from :%s" % (rev_to_mark(parents
[0]))
369 print "merge :%s" % (rev_to_mark(parents
[1]))
372 export_file(c
.filectx(f
))
378 if (count
% 100 == 0):
379 print "progress revision %d '%s' (%d/%d)" % (rev
, name
, count
, len(revs
))
380 print "#############################################################"
382 # make sure the ref is updated
383 print "reset %s/%s" % (prefix
, ename
)
384 print "from :%u" % rev_to_mark(rev
)
387 marks
.set_tip(ename
, rev
)
389 def export_tag(repo
, tag
):
390 export_ref(repo
, tag
, 'tags', repo
[tag
])
392 def export_bookmark(repo
, bmark
):
394 export_ref(repo
, bmark
, 'bookmarks', head
)
396 def export_branch(repo
, branch
):
397 tip
= get_branch_tip(repo
, branch
)
399 export_ref(repo
, branch
, 'branches', head
)
401 def export_head(repo
):
403 export_ref(repo
, g_head
[0], 'bookmarks', g_head
[1])
405 def do_capabilities(parser
):
406 global prefix
, dirname
410 print "refspec refs/heads/branches/*:%s/branches/*" % prefix
411 print "refspec refs/heads/*:%s/bookmarks/*" % prefix
412 print "refspec refs/tags/*:%s/tags/*" % prefix
414 path
= os
.path
.join(dirname
, 'marks-git')
416 if os
.path
.exists(path
):
417 print "*import-marks %s" % path
418 print "*export-marks %s" % path
422 def get_branch_tip(repo
, branch
):
425 heads
= branches
.get(branch
, None)
429 # verify there's only one head
431 warn("Branch '%s' has more than one head, consider merging" % branch
)
432 # older versions of mercurial don't have this
433 if hasattr(repo
, "branchtip"):
434 return repo
.branchtip(branch
)
438 def list_head(repo
, cur
):
439 global g_head
, bmarks
441 head
= bookmarks
.readcurrent(repo
)
445 # fake bookmark from current branch
452 if head
== 'default':
456 print "@refs/heads/%s HEAD" % head
457 g_head
= (head
, node
)
460 global branches
, bmarks
, mode
, track_branches
463 for bmark
, node
in bookmarks
.listbookmarks(repo
).iteritems():
464 bmarks
[bmark
] = repo
[node
]
466 cur
= repo
.dirstate
.branch()
471 for branch
in repo
.branchmap():
472 heads
= repo
.branchheads(branch
)
474 branches
[branch
] = heads
476 for branch
in branches
:
477 print "? refs/heads/branches/%s" % branch
480 print "? refs/heads/%s" % bmark
482 for tag
, node
in repo
.tagslist():
485 print "? refs/tags/%s" % tag
489 def do_import(parser
):
492 path
= os
.path
.join(dirname
, 'marks-git')
495 if os
.path
.exists(path
):
496 print "feature import-marks=%s" % path
497 print "feature export-marks=%s" % path
500 tmp
= encoding
.encoding
501 encoding
.encoding
= 'utf-8'
503 # lets get all the import lines
504 while parser
.check('import'):
509 elif ref
.startswith('refs/heads/branches/'):
510 branch
= ref
[len('refs/heads/branches/'):]
511 export_branch(repo
, branch
)
512 elif ref
.startswith('refs/heads/'):
513 bmark
= ref
[len('refs/heads/'):]
514 export_bookmark(repo
, bmark
)
515 elif ref
.startswith('refs/tags/'):
516 tag
= ref
[len('refs/tags/'):]
517 export_tag(repo
, tag
)
521 encoding
.encoding
= tmp
525 def parse_blob(parser
):
529 mark
= parser
.get_mark()
531 data
= parser
.get_data()
532 blob_marks
[mark
] = data
536 def get_merge_files(repo
, p1
, p2
, files
):
537 for e
in repo
[p1
].files():
539 if e
not in repo
[p1
].manifest():
541 f
= { 'ctx' : repo
[p1
][e
] }
544 def parse_commit(parser
):
545 global marks
, blob_marks
, bmarks
, parsed_refs
548 from_mark
= merge_mark
= None
553 commit_mark
= parser
.get_mark()
555 author
= parser
.get_author()
557 committer
= parser
.get_author()
559 data
= parser
.get_data()
561 if parser
.check('from'):
562 from_mark
= parser
.get_mark()
564 if parser
.check('merge'):
565 merge_mark
= parser
.get_mark()
567 if parser
.check('merge'):
568 die('octopus merges are not supported yet')
573 if parser
.check('M'):
574 t
, m
, mark_ref
, path
= line
.split(' ', 3)
575 mark
= int(mark_ref
[1:])
576 f
= { 'mode' : hgmode(m
), 'data' : blob_marks
[mark
] }
577 elif parser
.check('D'):
578 t
, path
= line
.split(' ')
579 f
= { 'deleted' : True }
581 die('Unknown file command: %s' % line
)
584 def getfilectx(repo
, memctx
, f
):
590 is_exec
= of
['mode'] == 'x'
591 is_link
= of
['mode'] == 'l'
592 rename
= of
.get('rename', None)
593 return context
.memfilectx(f
, of
['data'],
594 is_link
, is_exec
, rename
)
598 user
, date
, tz
= author
601 if committer
!= author
:
602 extra
['committer'] = "%s %u %u" % committer
605 p1
= repo
.changelog
.node(mark_to_rev(from_mark
))
610 p2
= repo
.changelog
.node(mark_to_rev(merge_mark
))
615 # If files changed from any of the parents, hg wants to know, but in git if
616 # nothing changed from the first parent, nothing changed.
619 get_merge_files(repo
, p1
, p2
, files
)
622 i
= data
.find('\n--HG--\n')
624 tmp
= data
[i
+ len('\n--HG--\n'):].strip()
625 for k
, v
in [e
.split(' : ') for e
in tmp
.split('\n')]:
627 old
, new
= v
.split(' => ', 1)
628 files
[new
]['rename'] = old
632 ek
, ev
= v
.split(' : ', 1)
633 extra
[ek
] = urllib
.unquote(ev
)
636 ctx
= context
.memctx(repo
, (p1
, p2
), data
,
637 files
.keys(), getfilectx
,
638 user
, (date
, tz
), extra
)
640 tmp
= encoding
.encoding
641 encoding
.encoding
= 'utf-8'
643 node
= repo
.commitctx(ctx
)
645 encoding
.encoding
= tmp
647 rev
= repo
[node
].rev()
649 parsed_refs
[ref
] = node
651 marks
.new_mark(rev
, commit_mark
)
653 def parse_reset(parser
):
657 if parser
.check('commit'):
660 if not parser
.check('from'):
662 from_mark
= parser
.get_mark()
665 node
= parser
.repo
.changelog
.node(mark_to_rev(from_mark
))
666 parsed_refs
[ref
] = node
668 def parse_tag(parser
):
671 from_mark
= parser
.get_mark()
673 tagger
= parser
.get_author()
675 data
= parser
.get_data()
680 def do_export(parser
):
681 global parsed_refs
, bmarks
, peer
685 for line
in parser
.each_block('done'):
686 if parser
.check('blob'):
688 elif parser
.check('commit'):
690 elif parser
.check('reset'):
692 elif parser
.check('tag'):
694 elif parser
.check('feature'):
697 die('unhandled export command: %s' % line
)
699 for ref
, node
in parsed_refs
.iteritems():
700 if ref
.startswith('refs/heads/branches'):
702 elif ref
.startswith('refs/heads/'):
703 bmark
= ref
[len('refs/heads/'):]
705 old
= bmarks
[bmark
].hex()
708 if not bookmarks
.pushbookmark(parser
.repo
, bmark
, old
, node
):
710 elif ref
.startswith('refs/tags/'):
711 tag
= ref
[len('refs/tags/'):]
712 parser
.repo
.tag([tag
], node
, None, True, None, {})
714 # transport-helper/fast-export bugs
721 parser
.repo
.push(peer
, force
=False)
724 global prefix
, dirname
, branches
, bmarks
725 global marks
, blob_marks
, parsed_refs
726 global peer
, mode
, bad_mail
, bad_name
727 global track_branches
733 hg_git_compat
= False
734 track_branches
= True
736 if get_config('remote-hg.hg-git-compat') == 'true\n':
738 track_branches
= False
739 if get_config('remote-hg.track-branches') == 'false\n':
740 track_branches
= False
741 except subprocess
.CalledProcessError
:
746 bad_mail
= 'none@none'
755 alias
= util
.sha1(alias
).hexdigest()
759 gitdir
= os
.environ
['GIT_DIR']
760 dirname
= os
.path
.join(gitdir
, 'hg', alias
)
766 repo
= get_repo(url
, alias
)
767 prefix
= 'refs/hg/%s' % alias
769 if not os
.path
.exists(dirname
):
772 marks_path
= os
.path
.join(dirname
, 'marks-hg')
773 marks
= Marks(marks_path
)
775 parser
= Parser(repo
)
777 if parser
.check('capabilities'):
778 do_capabilities(parser
)
779 elif parser
.check('list'):
781 elif parser
.check('import'):
783 elif parser
.check('export'):
786 die('unhandled command: %s' % line
)
792 shutil
.rmtree(dirname
)
794 sys
.exit(main(sys
.argv
))