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 # For remote repositories a local clone is stored in
13 # "$GIT_DIR/hg/origin/clone/.hg/".
15 from mercurial
import hg
, ui
, bookmarks
, context
, encoding
, node
, error
, extensions
, discovery
, util
25 import urlparse
, hashlib
29 # If you want to see Mercurial revisions as Git commit notes:
30 # git config core.notesRef refs/notes/hg
32 # If you are not in hg-git-compat mode and want to disable the tracking of
34 # git config --global remote-hg.track-branches false
36 # If you want the equivalent of hg's clone/pull--insecure option:
37 # git config --global remote-hg.insecure true
39 # If you want to switch to hg-git compatibility mode:
40 # git config --global remote-hg.hg-git-compat true
43 # Sensible defaults for git.
44 # hg bookmarks are exported as git branches, hg branches are prefixed
45 # with 'branches/', HEAD is a special case.
49 # Only hg bookmarks are exported as git branches.
50 # Commits are modified to preserve hg information and allow bidirectionality.
53 NAME_RE
= re
.compile('^([^<>]+)')
54 AUTHOR_RE
= re
.compile('^([^<>]+?)? ?[<>]([^<>]*)(?:$|>)')
55 EMAIL_RE
= re
.compile(r
'([^ \t<>]+@[^ \t<>]+)')
56 AUTHOR_HG_RE
= re
.compile('^(.*?) ?<(.*?)(?:>(.+)?)?$')
57 RAW_AUTHOR_RE
= re
.compile('^(\w+) (?:(.+)? )?<(.*)> (\d+) ([+-]\d+)')
62 sys
.stderr
.write('ERROR: %s\n' % (msg
% args
))
66 sys
.stderr
.write('WARNING: %s\n' % (msg
% args
))
69 return 'l' in flags
and '120000' or 'x' in flags
and '100755' or '100644'
72 return '%+03d%02d' % (-tz
/ 3600, -tz
% 3600 / 60)
75 m
= { '100755': 'x', '120000': 'l' }
76 return m
.get(mode
, '')
85 return ref
.replace('___', ' ')
88 return ref
.replace(' ', '___')
90 def check_version(*check
):
93 return hg_version
>= check
95 def get_config(config
):
96 cmd
= ['git', 'config', '--get', config
]
97 process
= subprocess
.Popen(cmd
, stdout
=subprocess
.PIPE
)
98 output
, _
= process
.communicate()
101 def get_config_bool(config
, default
=False):
102 value
= get_config(config
).rstrip('\n')
105 elif value
== "false":
112 def __init__(self
, path
, repo
):
118 if self
.version
< VERSION
:
119 if self
.version
== 1:
123 if self
.version
< VERSION
:
125 self
.version
= VERSION
136 if not os
.path
.exists(self
.path
):
139 tmp
= json
.load(open(self
.path
))
141 self
.tips
= tmp
['tips']
142 self
.marks
= tmp
['marks']
143 self
.last_mark
= tmp
['last-mark']
144 self
.version
= tmp
.get('version', 1)
145 self
.last_note
= tmp
.get('last-note', 0)
147 for rev
, mark
in self
.marks
.iteritems():
148 self
.rev_marks
[mark
] = rev
150 def upgrade_one(self
):
152 return hghex(self
.repo
.changelog
.node(int(rev
)))
153 self
.tips
= dict((name
, get_id(rev
)) for name
, rev
in self
.tips
.iteritems())
154 self
.marks
= dict((get_id(rev
), mark
) for rev
, mark
in self
.marks
.iteritems())
155 self
.rev_marks
= dict((mark
, get_id(rev
)) for mark
, rev
in self
.rev_marks
.iteritems())
159 return { 'tips': self
.tips
, 'marks': self
.marks
, 'last-mark' : self
.last_mark
, 'version' : self
.version
, 'last-note' : self
.last_note
}
162 json
.dump(self
.dict(), open(self
.path
, 'w'))
165 return str(self
.dict())
167 def from_rev(self
, rev
):
168 return self
.marks
[rev
]
170 def to_rev(self
, mark
):
171 return str(self
.rev_marks
[mark
])
175 return self
.last_mark
177 def get_mark(self
, rev
):
179 self
.marks
[rev
] = self
.last_mark
180 return self
.last_mark
182 def new_mark(self
, rev
, mark
):
183 self
.marks
[rev
] = mark
184 self
.rev_marks
[mark
] = rev
185 self
.last_mark
= mark
187 def is_marked(self
, rev
):
188 return rev
in self
.marks
190 def get_tip(self
, branch
):
191 return str(self
.tips
[branch
])
193 def set_tip(self
, branch
, tip
):
194 self
.tips
[branch
] = tip
198 def __init__(self
, repo
):
200 self
.line
= self
.get_line()
203 return sys
.stdin
.readline().strip()
205 def __getitem__(self
, i
):
206 return self
.line
.split()[i
]
208 def check(self
, word
):
209 return self
.line
.startswith(word
)
211 def each_block(self
, separator
):
212 while self
.line
!= separator
:
214 self
.line
= self
.get_line()
217 return self
.each_block('')
220 self
.line
= self
.get_line()
221 if self
.line
== 'done':
225 i
= self
.line
.index(':') + 1
226 return int(self
.line
[i
:])
229 if not self
.check('data'):
231 i
= self
.line
.index(' ') + 1
232 size
= int(self
.line
[i
:])
233 return sys
.stdin
.read(size
)
235 def get_author(self
):
237 m
= RAW_AUTHOR_RE
.match(self
.line
)
240 _
, name
, email
, date
, tz
= m
.groups()
241 if name
and 'ext:' in name
:
242 m
= re
.match('^(.+?) ext:\((.+)\)$', name
)
245 ex
= urllib
.unquote(m
.group(2))
247 if email
!= bad_mail
:
249 user
= '%s <%s>' % (name
, email
)
251 user
= '<%s>' % (email
)
259 tz
= ((tz
/ 100) * 3600) + ((tz
% 100) * 60)
260 return (user
, int(date
), -tz
)
262 def fix_file_path(path
):
263 if not os
.path
.isabs(path
):
265 return os
.path
.relpath(path
, '/')
267 def export_files(files
):
270 fid
= node
.hex(f
.filenode())
273 mark
= filenodes
[fid
]
275 mark
= marks
.next_mark()
276 filenodes
[fid
] = mark
280 print "mark :%u" % mark
281 print "data %d" % len(d
)
284 path
= fix_file_path(f
.path())
285 final
.append((gitmode(f
.flags()), mark
, path
))
289 def get_filechanges(repo
, ctx
, parent
):
294 # load earliest manifest first for caching reasons
295 prev
= parent
.manifest().copy()
300 if (cur
.flags(fn
) != prev
.flags(fn
) or cur
[fn
] != prev
[fn
]):
305 removed |
= set(prev
.keys())
307 return added | modified
, removed
309 def fixup_user_git(user
):
311 user
= user
.replace('"', '')
312 m
= AUTHOR_RE
.match(user
)
315 mail
= m
.group(2).strip()
317 m
= EMAIL_RE
.match(user
)
321 m
= NAME_RE
.match(user
)
323 name
= m
.group(1).strip()
326 def fixup_user_hg(user
):
328 # stole this from hg-git
329 return re
.sub('[<>\n]', '?', name
.lstrip('< ').rstrip('> '))
331 m
= AUTHOR_HG_RE
.match(user
)
333 name
= sanitize(m
.group(1))
334 mail
= sanitize(m
.group(2))
337 name
+= ' ext:(' + urllib
.quote(ex
) + ')'
339 name
= sanitize(user
)
347 def fixup_user(user
):
349 name
, mail
= fixup_user_git(user
)
351 name
, mail
= fixup_user_hg(user
)
358 return '%s <%s>' % (name
, mail
)
360 def updatebookmarks(repo
, peer
):
361 remotemarks
= peer
.listkeys('bookmarks')
362 localmarks
= repo
._bookmarks
367 for k
, v
in remotemarks
.iteritems():
368 localmarks
[k
] = hgbin(v
)
370 if hasattr(localmarks
, 'write'):
373 bookmarks
.write(repo
)
375 def get_repo(url
, alias
):
379 myui
.setconfig('ui', 'interactive', 'off')
380 myui
.fout
= sys
.stderr
382 if get_config_bool('remote-hg.insecure'):
383 myui
.setconfig('web', 'cacerts', '')
385 extensions
.loadall(myui
)
387 if hg
.islocal(url
) and not os
.environ
.get('GIT_REMOTE_HG_TEST_REMOTE'):
388 repo
= hg
.repository(myui
, url
)
389 if not os
.path
.exists(dirname
):
392 shared_path
= os
.path
.join(gitdir
, 'hg')
394 # check and upgrade old organization
395 hg_path
= os
.path
.join(shared_path
, '.hg')
396 if os
.path
.exists(shared_path
) and not os
.path
.exists(hg_path
):
397 repos
= os
.listdir(shared_path
)
399 local_hg
= os
.path
.join(shared_path
, x
, 'clone', '.hg')
400 if not os
.path
.exists(local_hg
):
402 if not os
.path
.exists(hg_path
):
403 shutil
.move(local_hg
, hg_path
)
404 shutil
.rmtree(os
.path
.join(shared_path
, x
, 'clone'))
406 # setup shared repo (if not there)
408 hg
.peer(myui
, {}, shared_path
, create
=True)
409 except error
.RepoError
:
412 if not os
.path
.exists(dirname
):
415 local_path
= os
.path
.join(dirname
, 'clone')
416 if not os
.path
.exists(local_path
):
417 hg
.share(myui
, shared_path
, local_path
, update
=False)
419 # make sure the shared path is always up-to-date
420 util
.writefile(os
.path
.join(local_path
, '.hg', 'sharedpath'), hg_path
)
422 repo
= hg
.repository(myui
, local_path
)
424 peer
= hg
.peer(myui
, {}, url
)
426 die('Repository error')
427 repo
.pull(peer
, heads
=None, force
=True)
429 updatebookmarks(repo
, peer
)
433 def rev_to_mark(rev
):
434 return marks
.from_rev(rev
.hex())
436 def mark_to_rev(mark
):
437 return marks
.to_rev(mark
)
439 def export_ref(repo
, name
, kind
, head
):
440 ename
= '%s/%s' % (kind
, name
)
442 tip
= marks
.get_tip(ename
)
443 tip
= repo
[tip
].rev()
447 revs
= xrange(tip
, head
.rev() + 1)
455 if marks
.is_marked(c
.hex()):
458 (manifest
, user
, (time
, tz
), files
, desc
, extra
) = repo
.changelog
.read(node
)
459 rev_branch
= extra
['branch']
461 author
= "%s %d %s" % (fixup_user(user
), time
, gittz(tz
))
462 if 'committer' in extra
:
463 user
, time
, tz
= extra
['committer'].rsplit(' ', 2)
464 committer
= "%s %s %s" % (user
, time
, gittz(int(tz
)))
468 parents
= [repo
[p
] for p
in repo
.changelog
.parentrevs(rev
) if p
>= 0]
470 if len(parents
) == 0:
471 modified
= c
.manifest().keys()
474 modified
, removed
= get_filechanges(repo
, c
, parents
[0])
481 if rev_branch
!= 'default':
482 extra_msg
+= 'branch : %s\n' % rev_branch
486 if f
not in c
.manifest():
488 rename
= c
.filectx(f
).renamed()
490 renames
.append((rename
[0], f
))
493 extra_msg
+= "rename : %s => %s\n" % e
495 for key
, value
in extra
.iteritems():
496 if key
in ('author', 'committer', 'encoding', 'message', 'branch', 'hg-git'):
499 extra_msg
+= "extra : %s : %s\n" % (key
, urllib
.quote(value
))
502 desc
+= '\n--HG--\n' + extra_msg
504 if len(parents
) == 0 and rev
:
505 print 'reset %s/%s' % (prefix
, ename
)
507 modified_final
= export_files(c
.filectx(f
) for f
in modified
)
509 print "commit %s/%s" % (prefix
, ename
)
510 print "mark :%d" % (marks
.get_mark(c
.hex()))
511 print "author %s" % (author
)
512 print "committer %s" % (committer
)
513 print "data %d" % (len(desc
))
517 print "from :%s" % (rev_to_mark(parents
[0]))
519 print "merge :%s" % (rev_to_mark(parents
[1]))
522 print "D %s" % (fix_file_path(f
))
523 for f
in modified_final
:
524 print "M %s :%u %s" % f
527 progress
= (rev
- tip
)
528 if (progress
% 100 == 0):
529 print "progress revision %d '%s' (%d/%d)" % (rev
, name
, progress
, total
)
531 # make sure the ref is updated
532 print "reset %s/%s" % (prefix
, ename
)
533 print "from :%u" % rev_to_mark(head
)
536 pending_revs
= set(revs
) - notes
538 note_mark
= marks
.next_mark()
539 ref
= "refs/notes/hg"
541 print "commit %s" % ref
542 print "mark :%d" % (note_mark
)
543 print "committer remote-hg <> %d %s" % (ptime
.time(), gittz(ptime
.timezone
))
544 desc
= "Notes for %s\n" % (name
)
545 print "data %d" % (len(desc
))
548 print "from :%u" % marks
.last_note
550 for rev
in pending_revs
:
553 print "N inline :%u" % rev_to_mark(c
)
555 print "data %d" % (len(msg
))
559 marks
.last_note
= note_mark
561 marks
.set_tip(ename
, head
.hex())
563 def export_tag(repo
, tag
):
564 export_ref(repo
, tag
, 'tags', repo
[hgref(tag
)])
566 def export_bookmark(repo
, bmark
):
567 head
= bmarks
[hgref(bmark
)]
568 export_ref(repo
, bmark
, 'bookmarks', head
)
570 def export_branch(repo
, branch
):
571 tip
= get_branch_tip(repo
, branch
)
573 export_ref(repo
, branch
, 'branches', head
)
575 def export_head(repo
):
576 export_ref(repo
, g_head
[0], 'bookmarks', g_head
[1])
578 def do_capabilities(parser
):
581 print "refspec refs/heads/branches/*:%s/branches/*" % prefix
582 print "refspec refs/heads/*:%s/bookmarks/*" % prefix
583 print "refspec refs/tags/*:%s/tags/*" % prefix
585 path
= os
.path
.join(dirname
, 'marks-git')
587 if os
.path
.exists(path
):
588 print "*import-marks %s" % path
589 print "*export-marks %s" % path
594 def branch_tip(branch
):
595 return branches
[branch
][-1]
597 def get_branch_tip(repo
, branch
):
598 heads
= branches
.get(hgref(branch
), None)
602 # verify there's only one head
604 warn("Branch '%s' has more than one head, consider merging" % branch
)
605 return branch_tip(hgref(branch
))
609 def list_head(repo
, cur
):
610 global g_head
, fake_bmark
612 if 'default' not in branches
:
616 node
= repo
[branch_tip('default')]
617 head
= 'master' if not 'master' in bmarks
else 'default'
622 print "@refs/heads/%s HEAD" % head
623 g_head
= (head
, node
)
627 for bmark
, node
in bookmarks
.listbookmarks(repo
).iteritems():
628 bmarks
[bmark
] = repo
[node
]
630 cur
= repo
.dirstate
.branch()
631 orig
= peer
if peer
else repo
633 for branch
, heads
in orig
.branchmap().iteritems():
635 heads
= [h
for h
in heads
if 'close' not in repo
.changelog
.read(h
)[5]]
637 branches
[branch
] = heads
642 for branch
in branches
:
643 print "? refs/heads/branches/%s" % gitref(branch
)
646 print "? refs/heads/%s" % gitref(bmark
)
648 for tag
, node
in repo
.tagslist():
651 print "? refs/tags/%s" % gitref(tag
)
655 def do_import(parser
):
658 path
= os
.path
.join(dirname
, 'marks-git')
661 if os
.path
.exists(path
):
662 print "feature import-marks=%s" % path
663 print "feature export-marks=%s" % path
664 print "feature force"
667 tmp
= encoding
.encoding
668 encoding
.encoding
= 'utf-8'
670 # lets get all the import lines
671 while parser
.check('import'):
676 elif ref
.startswith('refs/heads/branches/'):
677 branch
= ref
[len('refs/heads/branches/'):]
678 export_branch(repo
, branch
)
679 elif ref
.startswith('refs/heads/'):
680 bmark
= ref
[len('refs/heads/'):]
681 export_bookmark(repo
, bmark
)
682 elif ref
.startswith('refs/tags/'):
683 tag
= ref
[len('refs/tags/'):]
684 export_tag(repo
, tag
)
688 encoding
.encoding
= tmp
692 def parse_blob(parser
):
694 mark
= parser
.get_mark()
696 data
= parser
.get_data()
697 blob_marks
[mark
] = data
700 def get_merge_files(repo
, p1
, p2
, files
):
701 for e
in repo
[p1
].files():
703 if e
not in repo
[p1
].manifest():
705 f
= { 'ctx' : repo
[p1
][e
] }
708 def c_style_unescape(string
):
709 if string
[0] == string
[-1] == '"':
710 return string
.decode('string-escape')[1:-1]
713 def parse_commit(parser
):
714 from_mark
= merge_mark
= None
719 commit_mark
= parser
.get_mark()
721 author
= parser
.get_author()
723 committer
= parser
.get_author()
725 data
= parser
.get_data()
727 if parser
.check('from'):
728 from_mark
= parser
.get_mark()
730 if parser
.check('merge'):
731 merge_mark
= parser
.get_mark()
733 if parser
.check('merge'):
734 die('octopus merges are not supported yet')
736 # fast-export adds an extra newline
743 if parser
.check('M'):
744 t
, m
, mark_ref
, path
= line
.split(' ', 3)
745 mark
= int(mark_ref
[1:])
746 f
= { 'mode' : hgmode(m
), 'data' : blob_marks
[mark
] }
747 elif parser
.check('D'):
748 t
, path
= line
.split(' ', 1)
749 f
= { 'deleted' : True }
751 die('Unknown file command: %s' % line
)
752 path
= c_style_unescape(path
)
755 # only export the commits if we are on an internal proxy repo
756 if dry_run
and not peer
:
757 parsed_refs
[ref
] = None
760 def getfilectx(repo
, memctx
, f
):
766 is_exec
= of
['mode'] == 'x'
767 is_link
= of
['mode'] == 'l'
768 rename
= of
.get('rename', None)
769 return context
.memfilectx(f
, of
['data'],
770 is_link
, is_exec
, rename
)
774 user
, date
, tz
= author
777 if committer
!= author
:
778 extra
['committer'] = "%s %u %u" % committer
781 p1
= mark_to_rev(from_mark
)
786 p2
= mark_to_rev(merge_mark
)
791 # If files changed from any of the parents, hg wants to know, but in git if
792 # nothing changed from the first parent, nothing changed.
795 get_merge_files(repo
, p1
, p2
, files
)
797 # Check if the ref is supposed to be a named branch
798 if ref
.startswith('refs/heads/branches/'):
799 branch
= ref
[len('refs/heads/branches/'):]
800 extra
['branch'] = hgref(branch
)
803 i
= data
.find('\n--HG--\n')
805 tmp
= data
[i
+ len('\n--HG--\n'):].strip()
806 for k
, v
in [e
.split(' : ', 1) for e
in tmp
.split('\n')]:
808 old
, new
= v
.split(' => ', 1)
809 files
[new
]['rename'] = old
813 ek
, ev
= v
.split(' : ', 1)
814 extra
[ek
] = urllib
.unquote(ev
)
817 ctx
= context
.memctx(repo
, (p1
, p2
), data
,
818 files
.keys(), getfilectx
,
819 user
, (date
, tz
), extra
)
821 tmp
= encoding
.encoding
822 encoding
.encoding
= 'utf-8'
824 node
= hghex(repo
.commitctx(ctx
))
826 encoding
.encoding
= tmp
828 parsed_refs
[ref
] = node
829 marks
.new_mark(node
, commit_mark
)
831 def parse_reset(parser
):
835 if parser
.check('commit'):
838 if not parser
.check('from'):
840 from_mark
= parser
.get_mark()
844 rev
= mark_to_rev(from_mark
)
847 parsed_refs
[ref
] = rev
849 def parse_tag(parser
):
852 from_mark
= parser
.get_mark()
854 tagger
= parser
.get_author()
856 data
= parser
.get_data()
859 parsed_tags
[name
] = (tagger
, data
)
861 def write_tag(repo
, tag
, node
, msg
, author
):
862 branch
= repo
[node
].branch()
863 tip
= branch_tip(branch
)
866 def getfilectx(repo
, memctx
, f
):
868 fctx
= tip
.filectx(f
)
870 except error
.ManifestLookupError
:
872 content
= data
+ "%s %s\n" % (node
, tag
)
873 return context
.memfilectx(f
, content
, False, False, None)
878 user
, date
, tz
= author
881 cmd
= ['git', 'var', 'GIT_COMMITTER_IDENT']
882 process
= subprocess
.Popen(cmd
, stdout
=subprocess
.PIPE
)
883 output
, _
= process
.communicate()
884 m
= re
.match('^.* <.*>', output
)
888 user
= repo
.ui
.username()
891 ctx
= context
.memctx(repo
, (p1
, p2
), msg
,
892 ['.hgtags'], getfilectx
,
893 user
, date_tz
, {'branch' : branch
})
895 tmp
= encoding
.encoding
896 encoding
.encoding
= 'utf-8'
898 tagnode
= repo
.commitctx(ctx
)
900 encoding
.encoding
= tmp
902 return (tagnode
, branch
)
904 def checkheads_bmark(repo
, ref
, ctx
):
905 bmark
= ref
[len('refs/heads/'):]
906 if not bmark
in bmarks
:
910 ctx_old
= bmarks
[bmark
]
912 if not repo
.changelog
.descendant(ctx_old
.rev(), ctx_new
.rev()):
914 print "ok %s forced update" % ref
916 print "error %s non-fast forward" % ref
921 def checkheads(repo
, remote
, p_revs
):
923 remotemap
= remote
.branchmap()
931 for node
, ref
in p_revs
.iteritems():
933 branch
= ctx
.branch()
934 if not branch
in remotemap
:
937 if not ref
.startswith('refs/heads/branches'):
938 if ref
.startswith('refs/heads/'):
939 if not checkheads_bmark(repo
, ref
, ctx
):
942 # only check branches
944 new
.setdefault(branch
, []).append(ctx
.rev())
946 for branch
, heads
in new
.iteritems():
947 old
= [repo
.changelog
.rev(x
) for x
in remotemap
[branch
]]
949 if check_version(2, 3):
950 ancestors
= repo
.changelog
.ancestors([rev
], stoprev
=min(old
))
952 ancestors
= repo
.changelog
.ancestors(rev
)
963 node
= repo
.changelog
.node(rev
)
966 print "ok %s forced update" % ref
968 print "error %s non-fast forward" % ref
973 def push_unsafe(repo
, remote
, parsed_refs
, p_revs
):
977 fci
= discovery
.findcommonincoming
978 commoninc
= fci(repo
, remote
, force
=force
)
979 common
, _
, remoteheads
= commoninc
981 if not checkheads(repo
, remote
, p_revs
):
984 cg
= repo
.getbundle('push', heads
=list(p_revs
), common
=common
)
986 unbundle
= remote
.capable('unbundle')
989 remoteheads
= ['force']
990 return remote
.unbundle(cg
, remoteheads
, 'push')
992 return remote
.addchangegroup(cg
, 'push', repo
.url())
994 def push(repo
, remote
, parsed_refs
, p_revs
):
995 if hasattr(remote
, 'canpush') and not remote
.canpush():
996 print "error cannot push"
1003 unbundle
= remote
.capable('unbundle')
1005 lock
= remote
.lock()
1007 ret
= push_unsafe(repo
, remote
, parsed_refs
, p_revs
)
1009 if lock
is not None:
1014 def check_tip(ref
, kind
, name
, heads
):
1016 ename
= '%s/%s' % (kind
, name
)
1017 tip
= marks
.get_tip(ename
)
1023 def do_export(parser
):
1029 for line
in parser
.each_block('done'):
1030 if parser
.check('blob'):
1032 elif parser
.check('commit'):
1033 parse_commit(parser
)
1034 elif parser
.check('reset'):
1036 elif parser
.check('tag'):
1038 elif parser
.check('feature'):
1041 die('unhandled export command: %s' % line
)
1045 for ref
, node
in parsed_refs
.iteritems():
1046 bnode
= hgbin(node
) if node
else None
1047 if ref
.startswith('refs/heads/branches'):
1048 branch
= ref
[len('refs/heads/branches/'):]
1049 if branch
in branches
and bnode
in branches
[branch
]:
1054 remotemap
= peer
.branchmap()
1055 if remotemap
and branch
in remotemap
:
1056 heads
= [hghex(e
) for e
in remotemap
[branch
]]
1057 if not check_tip(ref
, 'branches', branch
, heads
):
1058 print "error %s fetch first" % ref
1064 elif ref
.startswith('refs/heads/'):
1065 bmark
= ref
[len('refs/heads/'):]
1067 old
= bmarks
[bmark
].hex() if bmark
in bmarks
else ''
1073 if bmark
!= fake_bmark
and \
1074 not (bmark
== 'master' and bmark
not in parser
.repo
._bookmarks
):
1075 p_bmarks
.append((ref
, bmark
, old
, new
))
1078 remote_old
= peer
.listkeys('bookmarks').get(bmark
)
1080 if not check_tip(ref
, 'bookmarks', bmark
, remote_old
):
1081 print "error %s fetch first" % ref
1086 elif ref
.startswith('refs/tags/'):
1090 tag
= ref
[len('refs/tags/'):]
1092 author
, msg
= parsed_tags
.get(tag
, (None, None))
1095 msg
= 'Added tag %s for changeset %s' % (tag
, node
[:12])
1096 tagnode
, branch
= write_tag(parser
.repo
, tag
, node
, msg
, author
)
1097 p_revs
[tagnode
] = 'refs/heads/branches/' + gitref(branch
)
1099 fp
= parser
.repo
.opener('localtags', 'a')
1100 fp
.write('%s %s\n' % (node
, tag
))
1105 # transport-helper/fast-export bugs
1113 if peer
and not force_push
:
1114 checkheads(parser
.repo
, peer
, p_revs
)
1119 if not push(parser
.repo
, peer
, parsed_refs
, p_revs
):
1120 # do not update bookmarks
1124 # update remote bookmarks
1125 remote_bmarks
= peer
.listkeys('bookmarks')
1126 for ref
, bmark
, old
, new
in p_bmarks
:
1128 old
= remote_bmarks
.get(bmark
, '')
1129 if not peer
.pushkey('bookmarks', bmark
, old
, new
):
1130 print "error %s" % ref
1132 # update local bookmarks
1133 for ref
, bmark
, old
, new
in p_bmarks
:
1134 if not bookmarks
.pushbookmark(parser
.repo
, bmark
, old
, new
):
1135 print "error %s" % ref
1139 def do_option(parser
):
1140 global dry_run
, force_push
1141 _
, key
, value
= parser
.line
.split(' ')
1142 if key
== 'dry-run':
1143 dry_run
= (value
== 'true')
1145 elif key
== 'force':
1146 force_push
= (value
== 'true')
1151 def fix_path(alias
, repo
, orig_url
):
1152 url
= urlparse
.urlparse(orig_url
, 'file')
1153 if url
.scheme
!= 'file' or os
.path
.isabs(os
.path
.expanduser(url
.path
)):
1155 abs_url
= urlparse
.urljoin("%s/" % os
.getcwd(), orig_url
)
1156 cmd
= ['git', 'config', 'remote.%s.url' % alias
, "hg::%s" % abs_url
]
1157 subprocess
.call(cmd
)
1160 global prefix
, gitdir
, dirname
, branches
, bmarks
1161 global marks
, blob_marks
, parsed_refs
1162 global peer
, mode
, bad_mail
, bad_name
1163 global track_branches
, force_push
, is_tmp
1166 global fake_bmark
, hg_version
1172 gitdir
= os
.environ
.get('GIT_DIR', None)
1175 die('Not enough arguments.')
1178 die('GIT_DIR not set')
1184 hg_git_compat
= get_config_bool('remote-hg.hg-git-compat')
1185 track_branches
= get_config_bool('remote-hg.track-branches', True)
1190 bad_mail
= 'none@none'
1194 bad_mail
= 'unknown'
1195 bad_name
= 'Unknown'
1197 if alias
[4:] == url
:
1199 alias
= hashlib
.sha1(alias
).hexdigest()
1201 dirname
= os
.path
.join(gitdir
, 'hg', alias
)
1210 hg_version
= tuple(int(e
) for e
in util
.version().split('.'))
1216 repo
= get_repo(url
, alias
)
1217 prefix
= 'refs/hg/%s' % alias
1220 fix_path(alias
, peer
or repo
, url
)
1222 marks_path
= os
.path
.join(dirname
, 'marks-hg')
1223 marks
= Marks(marks_path
, repo
)
1225 if sys
.platform
== 'win32':
1227 msvcrt
.setmode(sys
.stdout
.fileno(), os
.O_BINARY
)
1229 parser
= Parser(repo
)
1231 if parser
.check('capabilities'):
1232 do_capabilities(parser
)
1233 elif parser
.check('list'):
1235 elif parser
.check('import'):
1237 elif parser
.check('export'):
1239 elif parser
.check('option'):
1242 die('unhandled command: %s' % line
)
1251 shutil
.rmtree(dirname
)
1253 atexit
.register(bye
)
1254 sys
.exit(main(sys
.argv
))