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
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
, '')
63 def get_config(config
):
64 cmd
= ['git', 'config', '--get', config
]
65 process
= subprocess
.Popen(cmd
, stdout
=subprocess
.PIPE
)
66 output
, _
= process
.communicate()
71 def __init__(self
, path
):
81 if not os
.path
.exists(self
.path
):
84 tmp
= json
.load(open(self
.path
))
86 self
.tips
= tmp
['tips']
87 self
.marks
= tmp
['marks']
88 self
.last_mark
= tmp
['last-mark']
90 for rev
, mark
in self
.marks
.iteritems():
91 self
.rev_marks
[mark
] = int(rev
)
94 return { 'tips': self
.tips
, 'marks': self
.marks
, 'last-mark' : self
.last_mark
}
97 json
.dump(self
.dict(), open(self
.path
, 'w'))
100 return str(self
.dict())
102 def from_rev(self
, rev
):
103 return self
.marks
[str(rev
)]
105 def to_rev(self
, mark
):
106 return self
.rev_marks
[mark
]
108 def get_mark(self
, rev
):
110 self
.marks
[str(rev
)] = self
.last_mark
111 return self
.last_mark
113 def new_mark(self
, rev
, mark
):
114 self
.marks
[str(rev
)] = mark
115 self
.rev_marks
[mark
] = rev
116 self
.last_mark
= mark
118 def is_marked(self
, rev
):
119 return self
.marks
.has_key(str(rev
))
121 def get_tip(self
, branch
):
122 return self
.tips
.get(branch
, 0)
124 def set_tip(self
, branch
, tip
):
125 self
.tips
[branch
] = tip
129 def __init__(self
, repo
):
131 self
.line
= self
.get_line()
134 return sys
.stdin
.readline().strip()
136 def __getitem__(self
, i
):
137 return self
.line
.split()[i
]
139 def check(self
, word
):
140 return self
.line
.startswith(word
)
142 def each_block(self
, separator
):
143 while self
.line
!= separator
:
145 self
.line
= self
.get_line()
148 return self
.each_block('')
151 self
.line
= self
.get_line()
152 if self
.line
== 'done':
156 i
= self
.line
.index(':') + 1
157 return int(self
.line
[i
:])
160 if not self
.check('data'):
162 i
= self
.line
.index(' ') + 1
163 size
= int(self
.line
[i
:])
164 return sys
.stdin
.read(size
)
166 def get_author(self
):
170 m
= RAW_AUTHOR_RE
.match(self
.line
)
173 _
, name
, email
, date
, tz
= m
.groups()
174 if name
and 'ext:' in name
:
175 m
= re
.match('^(.+?) ext:\((.+)\)$', name
)
178 ex
= urllib
.unquote(m
.group(2))
180 if email
!= bad_mail
:
182 user
= '%s <%s>' % (name
, email
)
184 user
= '<%s>' % (email
)
192 tz
= ((tz
/ 100) * 3600) + ((tz
% 100) * 60)
193 return (user
, int(date
), -tz
)
197 print "M %s inline %s" % (gitmode(fc
.flags()), fc
.path())
198 print "data %d" % len(d
)
201 def get_filechanges(repo
, ctx
, parent
):
207 prev
= repo
[parent
].manifest().copy()
211 if (cur
.flags(fn
) != prev
.flags(fn
) or cur
[fn
] != prev
[fn
]):
216 removed |
= set(prev
.keys())
218 return added | modified
, removed
220 def fixup_user_git(user
):
222 user
= user
.replace('"', '')
223 m
= AUTHOR_RE
.match(user
)
226 mail
= m
.group(2).strip()
228 m
= NAME_RE
.match(user
)
230 name
= m
.group(1).strip()
233 def fixup_user_hg(user
):
235 # stole this from hg-git
236 return re
.sub('[<>\n]', '?', name
.lstrip('< ').rstrip('> '))
238 m
= AUTHOR_HG_RE
.match(user
)
240 name
= sanitize(m
.group(1))
241 mail
= sanitize(m
.group(2))
244 name
+= ' ext:(' + urllib
.quote(ex
) + ')'
246 name
= sanitize(user
)
254 def fixup_user(user
):
255 global mode
, bad_mail
258 name
, mail
= fixup_user_git(user
)
260 name
, mail
= fixup_user_hg(user
)
267 return '%s <%s>' % (name
, mail
)
269 def get_repo(url
, alias
):
273 myui
.setconfig('ui', 'interactive', 'off')
276 repo
= hg
.repository(myui
, url
)
278 local_path
= os
.path
.join(dirname
, 'clone')
279 if not os
.path
.exists(local_path
):
280 peer
, dstpeer
= hg
.clone(myui
, {}, url
, local_path
, update
=False, pull
=True)
281 repo
= dstpeer
.local()
283 repo
= hg
.repository(myui
, local_path
)
284 peer
= hg
.peer(myui
, {}, url
)
285 repo
.pull(peer
, heads
=None, force
=True)
289 def rev_to_mark(rev
):
291 return marks
.from_rev(rev
)
293 def mark_to_rev(mark
):
295 return marks
.to_rev(mark
)
297 def export_ref(repo
, name
, kind
, head
):
298 global prefix
, marks
, mode
300 ename
= '%s/%s' % (kind
, name
)
301 tip
= marks
.get_tip(ename
)
303 # mercurial takes too much time checking this
304 if tip
and tip
== head
.rev():
307 revs
= xrange(tip
, head
.rev() + 1)
310 revs
= [rev
for rev
in revs
if not marks
.is_marked(rev
)]
315 (manifest
, user
, (time
, tz
), files
, desc
, extra
) = repo
.changelog
.read(c
.node())
316 rev_branch
= extra
['branch']
318 author
= "%s %d %s" % (fixup_user(user
), time
, gittz(tz
))
319 if 'committer' in extra
:
320 user
, time
, tz
= extra
['committer'].rsplit(' ', 2)
321 committer
= "%s %s %s" % (user
, time
, gittz(int(tz
)))
325 parents
= [p
for p
in repo
.changelog
.parentrevs(rev
) if p
>= 0]
327 if len(parents
) == 0:
328 modified
= c
.manifest().keys()
331 modified
, removed
= get_filechanges(repo
, c
, parents
[0])
336 if rev_branch
!= 'default':
337 extra_msg
+= 'branch : %s\n' % rev_branch
341 if f
not in c
.manifest():
343 rename
= c
.filectx(f
).renamed()
345 renames
.append((rename
[0], f
))
348 extra_msg
+= "rename : %s => %s\n" % e
350 for key
, value
in extra
.iteritems():
351 if key
in ('author', 'committer', 'encoding', 'message', 'branch', 'hg-git'):
354 extra_msg
+= "extra : %s : %s\n" % (key
, urllib
.quote(value
))
358 desc
+= '\n--HG--\n' + extra_msg
360 if len(parents
) == 0 and rev
:
361 print 'reset %s/%s' % (prefix
, ename
)
363 print "commit %s/%s" % (prefix
, ename
)
364 print "mark :%d" % (marks
.get_mark(rev
))
365 print "author %s" % (author
)
366 print "committer %s" % (committer
)
367 print "data %d" % (len(desc
))
371 print "from :%s" % (rev_to_mark(parents
[0]))
373 print "merge :%s" % (rev_to_mark(parents
[1]))
376 export_file(c
.filectx(f
))
382 if (count
% 100 == 0):
383 print "progress revision %d '%s' (%d/%d)" % (rev
, name
, count
, len(revs
))
384 print "#############################################################"
386 # make sure the ref is updated
387 print "reset %s/%s" % (prefix
, ename
)
388 print "from :%u" % rev_to_mark(rev
)
391 marks
.set_tip(ename
, rev
)
393 def export_tag(repo
, tag
):
394 export_ref(repo
, tag
, 'tags', repo
[tag
])
396 def export_bookmark(repo
, bmark
):
398 export_ref(repo
, bmark
, 'bookmarks', head
)
400 def export_branch(repo
, branch
):
401 tip
= get_branch_tip(repo
, branch
)
403 export_ref(repo
, branch
, 'branches', head
)
405 def export_head(repo
):
407 export_ref(repo
, g_head
[0], 'bookmarks', g_head
[1])
409 def do_capabilities(parser
):
410 global prefix
, dirname
414 print "refspec refs/heads/branches/*:%s/branches/*" % prefix
415 print "refspec refs/heads/*:%s/bookmarks/*" % prefix
416 print "refspec refs/tags/*:%s/tags/*" % prefix
418 path
= os
.path
.join(dirname
, 'marks-git')
420 if os
.path
.exists(path
):
421 print "*import-marks %s" % path
422 print "*export-marks %s" % path
426 def get_branch_tip(repo
, branch
):
429 heads
= branches
.get(branch
, None)
433 # verify there's only one head
435 warn("Branch '%s' has more than one head, consider merging" % branch
)
436 # older versions of mercurial don't have this
437 if hasattr(repo
, "branchtip"):
438 return repo
.branchtip(branch
)
442 def list_head(repo
, cur
):
443 global g_head
, bmarks
445 head
= bookmarks
.readcurrent(repo
)
449 # fake bookmark from current branch
456 if head
== 'default':
460 print "@refs/heads/%s HEAD" % head
461 g_head
= (head
, node
)
464 global branches
, bmarks
, mode
, track_branches
467 for bmark
, node
in bookmarks
.listbookmarks(repo
).iteritems():
468 bmarks
[bmark
] = repo
[node
]
470 cur
= repo
.dirstate
.branch()
475 for branch
in repo
.branchmap():
476 heads
= repo
.branchheads(branch
)
478 branches
[branch
] = heads
480 for branch
in branches
:
481 print "? refs/heads/branches/%s" % branch
484 print "? refs/heads/%s" % bmark
486 for tag
, node
in repo
.tagslist():
489 print "? refs/tags/%s" % tag
493 def do_import(parser
):
496 path
= os
.path
.join(dirname
, 'marks-git')
499 if os
.path
.exists(path
):
500 print "feature import-marks=%s" % path
501 print "feature export-marks=%s" % path
504 tmp
= encoding
.encoding
505 encoding
.encoding
= 'utf-8'
507 # lets get all the import lines
508 while parser
.check('import'):
513 elif ref
.startswith('refs/heads/branches/'):
514 branch
= ref
[len('refs/heads/branches/'):]
515 export_branch(repo
, branch
)
516 elif ref
.startswith('refs/heads/'):
517 bmark
= ref
[len('refs/heads/'):]
518 export_bookmark(repo
, bmark
)
519 elif ref
.startswith('refs/tags/'):
520 tag
= ref
[len('refs/tags/'):]
521 export_tag(repo
, tag
)
525 encoding
.encoding
= tmp
529 def parse_blob(parser
):
533 mark
= parser
.get_mark()
535 data
= parser
.get_data()
536 blob_marks
[mark
] = data
539 def get_merge_files(repo
, p1
, p2
, files
):
540 for e
in repo
[p1
].files():
542 if e
not in repo
[p1
].manifest():
544 f
= { 'ctx' : repo
[p1
][e
] }
547 def parse_commit(parser
):
548 global marks
, blob_marks
, parsed_refs
551 from_mark
= merge_mark
= None
556 commit_mark
= parser
.get_mark()
558 author
= parser
.get_author()
560 committer
= parser
.get_author()
562 data
= parser
.get_data()
564 if parser
.check('from'):
565 from_mark
= parser
.get_mark()
567 if parser
.check('merge'):
568 merge_mark
= parser
.get_mark()
570 if parser
.check('merge'):
571 die('octopus merges are not supported yet')
576 if parser
.check('M'):
577 t
, m
, mark_ref
, path
= line
.split(' ', 3)
578 mark
= int(mark_ref
[1:])
579 f
= { 'mode' : hgmode(m
), 'data' : blob_marks
[mark
] }
580 elif parser
.check('D'):
581 t
, path
= line
.split(' ', 1)
582 f
= { 'deleted' : True }
584 die('Unknown file command: %s' % line
)
587 def getfilectx(repo
, memctx
, f
):
593 is_exec
= of
['mode'] == 'x'
594 is_link
= of
['mode'] == 'l'
595 rename
= of
.get('rename', None)
596 return context
.memfilectx(f
, of
['data'],
597 is_link
, is_exec
, rename
)
601 user
, date
, tz
= author
604 if committer
!= author
:
605 extra
['committer'] = "%s %u %u" % committer
608 p1
= repo
.changelog
.node(mark_to_rev(from_mark
))
613 p2
= repo
.changelog
.node(mark_to_rev(merge_mark
))
618 # If files changed from any of the parents, hg wants to know, but in git if
619 # nothing changed from the first parent, nothing changed.
622 get_merge_files(repo
, p1
, p2
, files
)
625 i
= data
.find('\n--HG--\n')
627 tmp
= data
[i
+ len('\n--HG--\n'):].strip()
628 for k
, v
in [e
.split(' : ', 1) for e
in tmp
.split('\n')]:
630 old
, new
= v
.split(' => ', 1)
631 files
[new
]['rename'] = old
635 ek
, ev
= v
.split(' : ', 1)
636 extra
[ek
] = urllib
.unquote(ev
)
639 ctx
= context
.memctx(repo
, (p1
, p2
), data
,
640 files
.keys(), getfilectx
,
641 user
, (date
, tz
), extra
)
643 tmp
= encoding
.encoding
644 encoding
.encoding
= 'utf-8'
646 node
= repo
.commitctx(ctx
)
648 encoding
.encoding
= tmp
650 rev
= repo
[node
].rev()
652 parsed_refs
[ref
] = node
653 marks
.new_mark(rev
, commit_mark
)
655 def parse_reset(parser
):
661 if parser
.check('commit'):
664 if not parser
.check('from'):
666 from_mark
= parser
.get_mark()
669 node
= parser
.repo
.changelog
.node(mark_to_rev(from_mark
))
670 parsed_refs
[ref
] = node
672 def parse_tag(parser
):
675 from_mark
= parser
.get_mark()
677 tagger
= parser
.get_author()
679 data
= parser
.get_data()
684 def do_export(parser
):
685 global parsed_refs
, bmarks
, peer
689 for line
in parser
.each_block('done'):
690 if parser
.check('blob'):
692 elif parser
.check('commit'):
694 elif parser
.check('reset'):
696 elif parser
.check('tag'):
698 elif parser
.check('feature'):
701 die('unhandled export command: %s' % line
)
703 for ref
, node
in parsed_refs
.iteritems():
704 if ref
.startswith('refs/heads/branches'):
706 elif ref
.startswith('refs/heads/'):
707 bmark
= ref
[len('refs/heads/'):]
709 old
= bmarks
[bmark
].hex()
712 if not bookmarks
.pushbookmark(parser
.repo
, bmark
, old
, node
):
713 print "error %s" % ref
715 elif ref
.startswith('refs/tags/'):
716 tag
= ref
[len('refs/tags/'):]
717 parser
.repo
.tag([tag
], node
, None, True, None, {})
719 # transport-helper/fast-export bugs
724 parser
.repo
.push(peer
, force
=False)
728 def fix_path(alias
, repo
, orig_url
):
729 repo_url
= util
.url(repo
.url())
730 url
= util
.url(orig_url
)
731 if str(url
) == str(repo_url
):
733 cmd
= ['git', 'config', 'remote.%s.url' % alias
, "hg::%s" % repo_url
]
737 global prefix
, dirname
, branches
, bmarks
738 global marks
, blob_marks
, parsed_refs
739 global peer
, mode
, bad_mail
, bad_name
740 global track_branches
746 hg_git_compat
= False
747 track_branches
= True
749 if get_config('remote-hg.hg-git-compat') == 'true\n':
751 track_branches
= False
752 if get_config('remote-hg.track-branches') == 'false\n':
753 track_branches
= False
754 except subprocess
.CalledProcessError
:
759 bad_mail
= 'none@none'
768 alias
= util
.sha1(alias
).hexdigest()
772 gitdir
= os
.environ
['GIT_DIR']
773 dirname
= os
.path
.join(gitdir
, 'hg', alias
)
779 repo
= get_repo(url
, alias
)
780 prefix
= 'refs/hg/%s' % alias
783 fix_path(alias
, peer
or repo
, url
)
785 if not os
.path
.exists(dirname
):
788 marks_path
= os
.path
.join(dirname
, 'marks-hg')
789 marks
= Marks(marks_path
)
791 parser
= Parser(repo
)
793 if parser
.check('capabilities'):
794 do_capabilities(parser
)
795 elif parser
.check('list'):
797 elif parser
.check('import'):
799 elif parser
.check('export'):
802 die('unhandled command: %s' % line
)
808 shutil
.rmtree(dirname
)
810 sys
.exit(main(sys
.argv
))