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
= { '100755': 'x', '120000': '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])
334 if rev_branch
!= 'default':
335 extra_msg
+= 'branch : %s\n' % rev_branch
339 if f
not in c
.manifest():
341 rename
= c
.filectx(f
).renamed()
343 renames
.append((rename
[0], f
))
346 extra_msg
+= "rename : %s => %s\n" % e
348 for key
, value
in extra
.iteritems():
349 if key
in ('author', 'committer', 'encoding', 'message', 'branch', 'hg-git'):
352 extra_msg
+= "extra : %s : %s\n" % (key
, urllib
.quote(value
))
355 desc
+= '\n--HG--\n' + extra_msg
357 if len(parents
) == 0 and rev
:
358 print 'reset %s/%s' % (prefix
, ename
)
360 print "commit %s/%s" % (prefix
, ename
)
361 print "mark :%d" % (marks
.get_mark(rev
))
362 print "author %s" % (author
)
363 print "committer %s" % (committer
)
364 print "data %d" % (len(desc
))
368 print "from :%s" % (rev_to_mark(parents
[0]))
370 print "merge :%s" % (rev_to_mark(parents
[1]))
373 export_file(c
.filectx(f
))
379 if (count
% 100 == 0):
380 print "progress revision %d '%s' (%d/%d)" % (rev
, name
, count
, len(revs
))
381 print "#############################################################"
383 # make sure the ref is updated
384 print "reset %s/%s" % (prefix
, ename
)
385 print "from :%u" % rev_to_mark(rev
)
388 marks
.set_tip(ename
, rev
)
390 def export_tag(repo
, tag
):
391 export_ref(repo
, tag
, 'tags', repo
[tag
])
393 def export_bookmark(repo
, bmark
):
395 export_ref(repo
, bmark
, 'bookmarks', head
)
397 def export_branch(repo
, branch
):
398 tip
= get_branch_tip(repo
, branch
)
400 export_ref(repo
, branch
, 'branches', head
)
402 def export_head(repo
):
404 export_ref(repo
, g_head
[0], 'bookmarks', g_head
[1])
406 def do_capabilities(parser
):
407 global prefix
, dirname
411 print "refspec refs/heads/branches/*:%s/branches/*" % prefix
412 print "refspec refs/heads/*:%s/bookmarks/*" % prefix
413 print "refspec refs/tags/*:%s/tags/*" % prefix
415 path
= os
.path
.join(dirname
, 'marks-git')
417 if os
.path
.exists(path
):
418 print "*import-marks %s" % path
419 print "*export-marks %s" % path
423 def get_branch_tip(repo
, branch
):
426 heads
= branches
.get(branch
, None)
430 # verify there's only one head
432 warn("Branch '%s' has more than one head, consider merging" % branch
)
433 # older versions of mercurial don't have this
434 if hasattr(repo
, "branchtip"):
435 return repo
.branchtip(branch
)
439 def list_head(repo
, cur
):
440 global g_head
, bmarks
442 head
= bookmarks
.readcurrent(repo
)
446 # fake bookmark from current branch
453 if head
== 'default':
457 print "@refs/heads/%s HEAD" % head
458 g_head
= (head
, node
)
461 global branches
, bmarks
, mode
, track_branches
464 for bmark
, node
in bookmarks
.listbookmarks(repo
).iteritems():
465 bmarks
[bmark
] = repo
[node
]
467 cur
= repo
.dirstate
.branch()
472 for branch
in repo
.branchmap():
473 heads
= repo
.branchheads(branch
)
475 branches
[branch
] = heads
477 for branch
in branches
:
478 print "? refs/heads/branches/%s" % branch
481 print "? refs/heads/%s" % bmark
483 for tag
, node
in repo
.tagslist():
486 print "? refs/tags/%s" % tag
490 def do_import(parser
):
493 path
= os
.path
.join(dirname
, 'marks-git')
496 if os
.path
.exists(path
):
497 print "feature import-marks=%s" % path
498 print "feature export-marks=%s" % path
501 tmp
= encoding
.encoding
502 encoding
.encoding
= 'utf-8'
504 # lets get all the import lines
505 while parser
.check('import'):
510 elif ref
.startswith('refs/heads/branches/'):
511 branch
= ref
[len('refs/heads/branches/'):]
512 export_branch(repo
, branch
)
513 elif ref
.startswith('refs/heads/'):
514 bmark
= ref
[len('refs/heads/'):]
515 export_bookmark(repo
, bmark
)
516 elif ref
.startswith('refs/tags/'):
517 tag
= ref
[len('refs/tags/'):]
518 export_tag(repo
, tag
)
522 encoding
.encoding
= tmp
526 def parse_blob(parser
):
530 mark
= parser
.get_mark()
532 data
= parser
.get_data()
533 blob_marks
[mark
] = data
537 def get_merge_files(repo
, p1
, p2
, files
):
538 for e
in repo
[p1
].files():
540 if e
not in repo
[p1
].manifest():
542 f
= { 'ctx' : repo
[p1
][e
] }
545 def parse_commit(parser
):
546 global marks
, blob_marks
, bmarks
, parsed_refs
549 from_mark
= merge_mark
= None
554 commit_mark
= parser
.get_mark()
556 author
= parser
.get_author()
558 committer
= parser
.get_author()
560 data
= parser
.get_data()
562 if parser
.check('from'):
563 from_mark
= parser
.get_mark()
565 if parser
.check('merge'):
566 merge_mark
= parser
.get_mark()
568 if parser
.check('merge'):
569 die('octopus merges are not supported yet')
574 if parser
.check('M'):
575 t
, m
, mark_ref
, path
= line
.split(' ', 3)
576 mark
= int(mark_ref
[1:])
577 f
= { 'mode' : hgmode(m
), 'data' : blob_marks
[mark
] }
578 elif parser
.check('D'):
579 t
, path
= line
.split(' ')
580 f
= { 'deleted' : True }
582 die('Unknown file command: %s' % line
)
585 def getfilectx(repo
, memctx
, f
):
591 is_exec
= of
['mode'] == 'x'
592 is_link
= of
['mode'] == 'l'
593 rename
= of
.get('rename', None)
594 return context
.memfilectx(f
, of
['data'],
595 is_link
, is_exec
, rename
)
599 user
, date
, tz
= author
602 if committer
!= author
:
603 extra
['committer'] = "%s %u %u" % committer
606 p1
= repo
.changelog
.node(mark_to_rev(from_mark
))
611 p2
= repo
.changelog
.node(mark_to_rev(merge_mark
))
616 # If files changed from any of the parents, hg wants to know, but in git if
617 # nothing changed from the first parent, nothing changed.
620 get_merge_files(repo
, p1
, p2
, files
)
623 i
= data
.find('\n--HG--\n')
625 tmp
= data
[i
+ len('\n--HG--\n'):].strip()
626 for k
, v
in [e
.split(' : ') for e
in tmp
.split('\n')]:
628 old
, new
= v
.split(' => ', 1)
629 files
[new
]['rename'] = old
633 ek
, ev
= v
.split(' : ', 1)
634 extra
[ek
] = urllib
.unquote(ev
)
637 ctx
= context
.memctx(repo
, (p1
, p2
), data
,
638 files
.keys(), getfilectx
,
639 user
, (date
, tz
), extra
)
641 tmp
= encoding
.encoding
642 encoding
.encoding
= 'utf-8'
644 node
= repo
.commitctx(ctx
)
646 encoding
.encoding
= tmp
648 rev
= repo
[node
].rev()
650 parsed_refs
[ref
] = node
652 marks
.new_mark(rev
, commit_mark
)
654 def parse_reset(parser
):
658 if parser
.check('commit'):
661 if not parser
.check('from'):
663 from_mark
= parser
.get_mark()
666 node
= parser
.repo
.changelog
.node(mark_to_rev(from_mark
))
667 parsed_refs
[ref
] = node
669 def parse_tag(parser
):
672 from_mark
= parser
.get_mark()
674 tagger
= parser
.get_author()
676 data
= parser
.get_data()
681 def do_export(parser
):
682 global parsed_refs
, bmarks
, peer
686 for line
in parser
.each_block('done'):
687 if parser
.check('blob'):
689 elif parser
.check('commit'):
691 elif parser
.check('reset'):
693 elif parser
.check('tag'):
695 elif parser
.check('feature'):
698 die('unhandled export command: %s' % line
)
700 for ref
, node
in parsed_refs
.iteritems():
701 if ref
.startswith('refs/heads/branches'):
703 elif ref
.startswith('refs/heads/'):
704 bmark
= ref
[len('refs/heads/'):]
706 old
= bmarks
[bmark
].hex()
709 if not bookmarks
.pushbookmark(parser
.repo
, bmark
, old
, node
):
711 elif ref
.startswith('refs/tags/'):
712 tag
= ref
[len('refs/tags/'):]
713 parser
.repo
.tag([tag
], node
, None, True, None, {})
715 # transport-helper/fast-export bugs
722 parser
.repo
.push(peer
, force
=False)
724 def fix_path(alias
, repo
, orig_url
):
725 repo_url
= util
.url(repo
.url())
726 url
= util
.url(orig_url
)
727 if str(url
) == str(repo_url
):
729 cmd
= ['git', 'config', 'remote.%s.url' % alias
, "hg::%s" % repo_url
]
733 global prefix
, dirname
, branches
, bmarks
734 global marks
, blob_marks
, parsed_refs
735 global peer
, mode
, bad_mail
, bad_name
736 global track_branches
742 hg_git_compat
= False
743 track_branches
= True
745 if get_config('remote-hg.hg-git-compat') == 'true\n':
747 track_branches
= False
748 if get_config('remote-hg.track-branches') == 'false\n':
749 track_branches
= False
750 except subprocess
.CalledProcessError
:
755 bad_mail
= 'none@none'
764 alias
= util
.sha1(alias
).hexdigest()
768 gitdir
= os
.environ
['GIT_DIR']
769 dirname
= os
.path
.join(gitdir
, 'hg', alias
)
775 repo
= get_repo(url
, alias
)
776 prefix
= 'refs/hg/%s' % alias
779 fix_path(alias
, peer
or repo
, url
)
781 if not os
.path
.exists(dirname
):
784 marks_path
= os
.path
.join(dirname
, 'marks-hg')
785 marks
= Marks(marks_path
)
787 parser
= Parser(repo
)
789 if parser
.check('capabilities'):
790 do_capabilities(parser
)
791 elif parser
.check('list'):
793 elif parser
.check('import'):
795 elif parser
.check('export'):
798 die('unhandled command: %s' % line
)
804 shutil
.rmtree(dirname
)
806 sys
.exit(main(sys
.argv
))