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
22 # If you want to switch to hg-git compatibility mode:
23 # git config --global remote-hg.hg-git-compat true
26 # Sensible defaults for git.
27 # hg bookmarks are exported as git branches, hg branches are prefixed
32 # Only hg bookmarks are exported as git branches.
33 # Commits are modified to preserve hg information and allow biridectionality.
36 NAME_RE
= re
.compile('^([^<>]+)')
37 AUTHOR_RE
= re
.compile('^([^<>]+?)? ?<([^<>]+)>$')
38 RAW_AUTHOR_RE
= re
.compile('^(\w+) (?:(.+)? )?<(.+)> (\d+) ([+-]\d+)')
41 sys
.stderr
.write('ERROR: %s\n' % (msg
% args
))
45 sys
.stderr
.write('WARNING: %s\n' % (msg
% args
))
48 return 'l' in flags
and '120000' or 'x' in flags
and '100755' or '100644'
51 return '%+03d%02d' % (-tz
/ 3600, -tz
% 3600 / 60)
54 m
= { '0100755': 'x', '0120000': 'l' }
55 return m
.get(mode
, '')
59 def __init__(self
, path
):
69 if not os
.path
.exists(self
.path
):
72 tmp
= json
.load(open(self
.path
))
74 self
.tips
= tmp
['tips']
75 self
.marks
= tmp
['marks']
76 self
.last_mark
= tmp
['last-mark']
78 for rev
, mark
in self
.marks
.iteritems():
79 self
.rev_marks
[mark
] = int(rev
)
82 return { 'tips': self
.tips
, 'marks': self
.marks
, 'last-mark' : self
.last_mark
}
85 json
.dump(self
.dict(), open(self
.path
, 'w'))
88 return str(self
.dict())
90 def from_rev(self
, rev
):
91 return self
.marks
[str(rev
)]
93 def to_rev(self
, mark
):
94 return self
.rev_marks
[mark
]
96 def get_mark(self
, rev
):
98 self
.marks
[str(rev
)] = self
.last_mark
101 def new_mark(self
, rev
, mark
):
102 self
.marks
[str(rev
)] = mark
103 self
.rev_marks
[mark
] = rev
104 self
.last_mark
= mark
106 def is_marked(self
, rev
):
107 return self
.marks
.has_key(str(rev
))
109 def get_tip(self
, branch
):
110 return self
.tips
.get(branch
, 0)
112 def set_tip(self
, branch
, tip
):
113 self
.tips
[branch
] = tip
117 def __init__(self
, repo
):
119 self
.line
= self
.get_line()
122 return sys
.stdin
.readline().strip()
124 def __getitem__(self
, i
):
125 return self
.line
.split()[i
]
127 def check(self
, word
):
128 return self
.line
.startswith(word
)
130 def each_block(self
, separator
):
131 while self
.line
!= separator
:
133 self
.line
= self
.get_line()
136 return self
.each_block('')
139 self
.line
= self
.get_line()
140 if self
.line
== 'done':
144 i
= self
.line
.index(':') + 1
145 return int(self
.line
[i
:])
148 if not self
.check('data'):
150 i
= self
.line
.index(' ') + 1
151 size
= int(self
.line
[i
:])
152 return sys
.stdin
.read(size
)
154 def get_author(self
):
155 m
= RAW_AUTHOR_RE
.match(self
.line
)
158 _
, name
, email
, date
, tz
= m
.groups()
160 if email
!= 'unknown':
162 user
= '%s <%s>' % (name
, email
)
164 user
= '<%s>' % (email
)
169 tz
= ((tz
/ 100) * 3600) + ((tz
% 100) * 60)
170 return (user
, int(date
), -tz
)
174 print "M %s inline %s" % (gitmode(fc
.flags()), fc
.path())
175 print "data %d" % len(d
)
178 def get_filechanges(repo
, ctx
, parent
):
184 prev
= repo
[parent
].manifest().copy()
188 if (cur
.flags(fn
) != prev
.flags(fn
) or cur
[fn
] != prev
[fn
]):
193 removed |
= set(prev
.keys())
195 return added | modified
, removed
197 def fixup_user(user
):
198 user
= user
.replace('"', '')
200 m
= AUTHOR_RE
.match(user
)
203 mail
= m
.group(2).strip()
205 m
= NAME_RE
.match(user
)
207 name
= m
.group(1).strip()
214 return '%s <%s>' % (name
, mail
)
216 def get_repo(url
, alias
):
220 myui
.setconfig('ui', 'interactive', 'off')
223 repo
= hg
.repository(myui
, url
)
225 local_path
= os
.path
.join(dirname
, 'clone')
226 if not os
.path
.exists(local_path
):
227 peer
, dstpeer
= hg
.clone(myui
, {}, url
, local_path
, update
=False, pull
=True)
228 repo
= dstpeer
.local()
230 repo
= hg
.repository(myui
, local_path
)
231 peer
= hg
.peer(myui
, {}, url
)
232 repo
.pull(peer
, heads
=None, force
=True)
236 def rev_to_mark(rev
):
238 return marks
.from_rev(rev
)
240 def mark_to_rev(mark
):
242 return marks
.to_rev(mark
)
244 def export_ref(repo
, name
, kind
, head
):
245 global prefix
, marks
, mode
247 ename
= '%s/%s' % (kind
, name
)
248 tip
= marks
.get_tip(ename
)
250 # mercurial takes too much time checking this
251 if tip
and tip
== head
.rev():
254 revs
= repo
.revs('%u:%u' % (tip
, head
))
257 revs
= [rev
for rev
in revs
if not marks
.is_marked(rev
)]
262 (manifest
, user
, (time
, tz
), files
, desc
, extra
) = repo
.changelog
.read(c
.node())
263 rev_branch
= extra
['branch']
265 author
= "%s %d %s" % (fixup_user(user
), time
, gittz(tz
))
266 if 'committer' in extra
:
267 user
, time
, tz
= extra
['committer'].rsplit(' ', 2)
268 committer
= "%s %s %s" % (user
, time
, gittz(int(tz
)))
272 parents
= [p
for p
in repo
.changelog
.parentrevs(rev
) if p
>= 0]
274 if len(parents
) == 0:
275 modified
= c
.manifest().keys()
278 modified
, removed
= get_filechanges(repo
, c
, parents
[0])
283 if rev_branch
!= 'default':
284 extra_msg
+= 'branch : %s\n' % rev_branch
288 if f
not in c
.manifest():
290 rename
= c
.filectx(f
).renamed()
292 renames
.append((rename
[0], f
))
295 extra_msg
+= "rename : %s => %s\n" % e
297 for key
, value
in extra
.iteritems():
298 if key
in ('author', 'committer', 'encoding', 'message', 'branch', 'hg-git'):
301 extra_msg
+= "extra : %s : %s\n" % (key
, urllib
.quote(value
))
305 desc
+= '\n--HG--\n' + extra_msg
307 if len(parents
) == 0 and rev
:
308 print 'reset %s/%s' % (prefix
, ename
)
310 print "commit %s/%s" % (prefix
, ename
)
311 print "mark :%d" % (marks
.get_mark(rev
))
312 print "author %s" % (author
)
313 print "committer %s" % (committer
)
314 print "data %d" % (len(desc
))
318 print "from :%s" % (rev_to_mark(parents
[0]))
320 print "merge :%s" % (rev_to_mark(parents
[1]))
323 export_file(c
.filectx(f
))
329 if (count
% 100 == 0):
330 print "progress revision %d '%s' (%d/%d)" % (rev
, name
, count
, len(revs
))
331 print "#############################################################"
333 # make sure the ref is updated
334 print "reset %s/%s" % (prefix
, ename
)
335 print "from :%u" % rev_to_mark(rev
)
338 marks
.set_tip(ename
, rev
)
340 def export_tag(repo
, tag
):
341 export_ref(repo
, tag
, 'tags', repo
[tag
])
343 def export_bookmark(repo
, bmark
):
345 export_ref(repo
, bmark
, 'bookmarks', head
)
347 def export_branch(repo
, branch
):
348 tip
= get_branch_tip(repo
, branch
)
350 export_ref(repo
, branch
, 'branches', head
)
352 def export_head(repo
):
354 export_ref(repo
, g_head
[0], 'bookmarks', g_head
[1])
356 def do_capabilities(parser
):
357 global prefix
, dirname
361 print "refspec refs/heads/branches/*:%s/branches/*" % prefix
362 print "refspec refs/heads/*:%s/bookmarks/*" % prefix
363 print "refspec refs/tags/*:%s/tags/*" % prefix
365 path
= os
.path
.join(dirname
, 'marks-git')
367 if os
.path
.exists(path
):
368 print "*import-marks %s" % path
369 print "*export-marks %s" % path
373 def get_branch_tip(repo
, branch
):
376 heads
= branches
.get(branch
, None)
380 # verify there's only one head
382 warn("Branch '%s' has more than one head, consider merging" % branch
)
383 # older versions of mercurial don't have this
384 if hasattr(repo
, "branchtip"):
385 return repo
.branchtip(branch
)
389 def list_head(repo
, cur
):
392 head
= bookmarks
.readcurrent(repo
)
396 print "@refs/heads/%s HEAD" % head
397 g_head
= (head
, node
)
400 global branches
, bmarks
, mode
403 for branch
in repo
.branchmap():
404 heads
= repo
.branchheads(branch
)
406 branches
[branch
] = heads
408 for bmark
, node
in bookmarks
.listbookmarks(repo
).iteritems():
409 bmarks
[bmark
] = repo
[node
]
411 cur
= repo
.dirstate
.branch()
416 for branch
in branches
:
417 print "? refs/heads/branches/%s" % branch
420 print "? refs/heads/%s" % bmark
422 for tag
, node
in repo
.tagslist():
425 print "? refs/tags/%s" % tag
429 def do_import(parser
):
432 path
= os
.path
.join(dirname
, 'marks-git')
435 if os
.path
.exists(path
):
436 print "feature import-marks=%s" % path
437 print "feature export-marks=%s" % path
440 tmp
= encoding
.encoding
441 encoding
.encoding
= 'utf-8'
443 # lets get all the import lines
444 while parser
.check('import'):
449 elif ref
.startswith('refs/heads/branches/'):
450 branch
= ref
[len('refs/heads/branches/'):]
451 export_branch(repo
, branch
)
452 elif ref
.startswith('refs/heads/'):
453 bmark
= ref
[len('refs/heads/'):]
454 export_bookmark(repo
, bmark
)
455 elif ref
.startswith('refs/tags/'):
456 tag
= ref
[len('refs/tags/'):]
457 export_tag(repo
, tag
)
461 encoding
.encoding
= tmp
465 def parse_blob(parser
):
469 mark
= parser
.get_mark()
471 data
= parser
.get_data()
472 blob_marks
[mark
] = data
476 def get_merge_files(repo
, p1
, p2
, files
):
477 for e
in repo
[p1
].files():
479 if e
not in repo
[p1
].manifest():
481 f
= { 'ctx' : repo
[p1
][e
] }
484 def parse_commit(parser
):
485 global marks
, blob_marks
, bmarks
, parsed_refs
488 from_mark
= merge_mark
= None
493 commit_mark
= parser
.get_mark()
495 author
= parser
.get_author()
497 committer
= parser
.get_author()
499 data
= parser
.get_data()
501 if parser
.check('from'):
502 from_mark
= parser
.get_mark()
504 if parser
.check('merge'):
505 merge_mark
= parser
.get_mark()
507 if parser
.check('merge'):
508 die('octopus merges are not supported yet')
513 if parser
.check('M'):
514 t
, m
, mark_ref
, path
= line
.split(' ')
515 mark
= int(mark_ref
[1:])
516 f
= { 'mode' : hgmode(m
), 'data' : blob_marks
[mark
] }
517 elif parser
.check('D'):
518 t
, path
= line
.split(' ')
519 f
= { 'deleted' : True }
521 die('Unknown file command: %s' % line
)
524 def getfilectx(repo
, memctx
, f
):
530 is_exec
= of
['mode'] == 'x'
531 is_link
= of
['mode'] == 'l'
532 rename
= of
.get('rename', None)
533 return context
.memfilectx(f
, of
['data'],
534 is_link
, is_exec
, rename
)
538 user
, date
, tz
= author
541 if committer
!= author
:
542 extra
['committer'] = "%s %u %u" % committer
545 p1
= repo
.changelog
.node(mark_to_rev(from_mark
))
550 p2
= repo
.changelog
.node(mark_to_rev(merge_mark
))
555 # If files changed from any of the parents, hg wants to know, but in git if
556 # nothing changed from the first parent, nothing changed.
559 get_merge_files(repo
, p1
, p2
, files
)
562 i
= data
.find('\n--HG--\n')
564 tmp
= data
[i
+ len('\n--HG--\n'):].strip()
565 for k
, v
in [e
.split(' : ') for e
in tmp
.split('\n')]:
567 old
, new
= v
.split(' => ', 1)
568 files
[new
]['rename'] = old
572 ek
, ev
= v
.split(' : ', 1)
573 extra
[ek
] = urllib
.unquote(ev
)
576 ctx
= context
.memctx(repo
, (p1
, p2
), data
,
577 files
.keys(), getfilectx
,
578 user
, (date
, tz
), extra
)
580 tmp
= encoding
.encoding
581 encoding
.encoding
= 'utf-8'
583 node
= repo
.commitctx(ctx
)
585 encoding
.encoding
= tmp
587 rev
= repo
[node
].rev()
589 parsed_refs
[ref
] = node
591 marks
.new_mark(rev
, commit_mark
)
593 def parse_reset(parser
):
597 if parser
.check('commit'):
600 if not parser
.check('from'):
602 from_mark
= parser
.get_mark()
605 node
= parser
.repo
.changelog
.node(mark_to_rev(from_mark
))
606 parsed_refs
[ref
] = node
608 def parse_tag(parser
):
611 from_mark
= parser
.get_mark()
613 tagger
= parser
.get_author()
615 data
= parser
.get_data()
620 def do_export(parser
):
621 global parsed_refs
, bmarks
, peer
625 for line
in parser
.each_block('done'):
626 if parser
.check('blob'):
628 elif parser
.check('commit'):
630 elif parser
.check('reset'):
632 elif parser
.check('tag'):
634 elif parser
.check('feature'):
637 die('unhandled export command: %s' % line
)
639 for ref
, node
in parsed_refs
.iteritems():
640 if ref
.startswith('refs/heads/branches'):
642 elif ref
.startswith('refs/heads/'):
643 bmark
= ref
[len('refs/heads/'):]
645 old
= bmarks
[bmark
].hex()
648 if not bookmarks
.pushbookmark(parser
.repo
, bmark
, old
, node
):
650 elif ref
.startswith('refs/tags/'):
651 tag
= ref
[len('refs/tags/'):]
652 parser
.repo
.tag([tag
], node
, None, True, None, {})
658 parser
.repo
.push(peer
, force
=False)
661 global prefix
, dirname
, branches
, bmarks
662 global marks
, blob_marks
, parsed_refs
669 cmd
= ['git', 'config', '--get', 'remote-hg.hg-git-compat']
670 hg_git_compat
= False
672 if subprocess
.check_output(cmd
) == 'true\n':
674 except subprocess
.CalledProcessError
:
684 alias
= util
.sha1(alias
).hexdigest()
688 gitdir
= os
.environ
['GIT_DIR']
689 dirname
= os
.path
.join(gitdir
, 'hg', alias
)
695 repo
= get_repo(url
, alias
)
696 prefix
= 'refs/hg/%s' % alias
698 if not os
.path
.exists(dirname
):
701 marks_path
= os
.path
.join(dirname
, 'marks-hg')
702 marks
= Marks(marks_path
)
704 parser
= Parser(repo
)
706 if parser
.check('capabilities'):
707 do_capabilities(parser
)
708 elif parser
.check('list'):
710 elif parser
.check('import'):
712 elif parser
.check('export'):
715 die('unhandled command: %s' % line
)
721 shutil
.rmtree(dirname
)
723 sys
.exit(main(sys
.argv
))