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
28 sys.stderr.write('WARNING: git-remote-hg is now maintained independently.\n')
29 sys.stderr.write('WARNING: For more information visit https://github.com/felipec/git-remote-hg\n')
32 # If you want to see Mercurial revisions as Git commit notes:
33 # git config core.notesRef refs/notes/hg
35 # If you are not in hg-git-compat mode and want to disable the tracking of
37 # git config --global remote-hg.track-branches false
39 # If you want the equivalent of hg's clone/pull--insecure option:
40 # git config --global remote-hg.insecure true
42 # If you want to switch to hg-git compatibility mode:
43 # git config --global remote-hg.hg-git-compat true
46 # Sensible defaults for git.
47 # hg bookmarks are exported as git branches, hg branches are prefixed
48 # with 'branches/', HEAD is a special case.
52 # Only hg bookmarks are exported as git branches.
53 # Commits are modified to preserve hg information and allow bidirectionality.
56 NAME_RE = re.compile('^([^<>]+)')
57 AUTHOR_RE = re.compile('^([^<>]+?)? ?[<>]([^<>]*)(?:$|>)')
58 EMAIL_RE = re.compile(r'([^ \t<>]+@[^ \t<>]+)')
59 AUTHOR_HG_RE = re.compile('^(.*?) ?<(.*?)(?:>(.+)?)?$')
60 RAW_AUTHOR_RE = re.compile('^(\w+) (?:(.+)? )?<(.*)> (\d+) ([+-]\d+)')
65 sys.stderr.write('ERROR: %s\n' % (msg % args))
69 sys.stderr.write('WARNING: %s\n' % (msg % args))
72 return 'l' in flags and '120000' or 'x' in flags and '100755' or '100644'
75 return '%+03d%02d' % (-tz / 3600, -tz % 3600 / 60)
78 m = { '100755': 'x', '120000': 'l' }
79 return m.get(mode, '')
88 return ref.replace('___', ' ')
91 return ref.replace(' ', '___')
93 def check_version(*check):
96 return hg_version >= check
98 def get_config(config):
99 cmd = ['git', 'config', '--get', config]
100 process = subprocess.Popen(cmd, stdout=subprocess.PIPE)
101 output, _ = process.communicate()
104 def get_config_bool(config, default=False):
105 value = get_config(config).rstrip('\n')
108 elif value == "false":
115 def __init__(self, path, repo):
121 if self.version < VERSION:
122 if self.version == 1:
126 if self.version < VERSION:
128 self.version = VERSION
139 if not os.path.exists(self.path):
142 tmp = json.load(open(self.path))
144 self.tips = tmp['tips']
145 self.marks = tmp['marks']
146 self.last_mark = tmp['last-mark']
147 self.version = tmp.get('version', 1)
148 self.last_note = tmp.get('last-note', 0)
150 for rev, mark in self.marks.iteritems():
151 self.rev_marks[mark] = rev
153 def upgrade_one(self):
155 return hghex(self.repo.changelog.node(int(rev)))
156 self.tips = dict((name, get_id(rev)) for name, rev in self.tips.iteritems())
157 self.marks = dict((get_id(rev), mark) for rev, mark in self.marks.iteritems())
158 self.rev_marks = dict((mark, get_id(rev)) for mark, rev in self.rev_marks.iteritems())
162 return { 'tips': self.tips, 'marks': self.marks, 'last-mark' : self.last_mark, 'version' : self.version, 'last-note' : self.last_note }
165 json.dump(self.dict(), open(self.path, 'w'))
168 return str(self.dict())
170 def from_rev(self, rev):
171 return self.marks[rev]
173 def to_rev(self, mark):
174 return str(self.rev_marks[mark])
178 return self.last_mark
180 def get_mark(self, rev):
182 self.marks[rev] = self.last_mark
183 return self.last_mark
185 def new_mark(self, rev, mark):
186 self.marks[rev] = mark
187 self.rev_marks[mark] = rev
188 self.last_mark = mark
190 def is_marked(self, rev):
191 return rev in self.marks
193 def get_tip(self, branch):
194 return str(self.tips[branch])
196 def set_tip(self, branch, tip):
197 self.tips[branch] = tip
201 def __init__(self, repo):
203 self.line = self.get_line()
206 return sys.stdin.readline().strip()
208 def __getitem__(self, i):
209 return self.line.split()[i]
211 def check(self, word):
212 return self.line.startswith(word)
214 def each_block(self, separator):
215 while self.line != separator:
217 self.line = self.get_line()
220 return self.each_block('')
223 self.line = self.get_line()
224 if self.line == 'done':
228 i = self.line.index(':') + 1
229 return int(self.line[i:])
232 if not self.check('data'):
234 i = self.line.index(' ') + 1
235 size = int(self.line[i:])
236 return sys.stdin.read(size)
238 def get_author(self):
240 m = RAW_AUTHOR_RE.match(self.line)
243 _, name, email, date, tz = m.groups()
244 if name and 'ext:' in name:
245 m = re.match('^(.+?) ext:\((.+)\)$', name)
248 ex = urllib.unquote(m.group(2))
250 if email != bad_mail:
252 user = '%s <%s>' % (name, email)
254 user = '<%s>' % (email)
262 tz = ((tz / 100) * 3600) + ((tz % 100) * 60)
263 return (user, int(date), -tz)
265 def fix_file_path(path):
266 path = os.path.normpath(path)
267 if not os.path.isabs(path):
269 return os.path.relpath(path, '/')
271 def export_files(files):
274 fid = node.hex(f.filenode())
277 mark = filenodes[fid]
279 mark = marks.next_mark()
280 filenodes[fid] = mark
284 print "mark :%u" % mark
285 print "data %d" % len(d)
288 path = fix_file_path(f.path())
289 final.append((gitmode(f.flags()), mark, path))
293 def get_filechanges(repo, ctx, parent):
298 # load earliest manifest first for caching reasons
299 prev = parent.manifest().copy()
304 if (cur.flags(fn) != prev.flags(fn) or cur[fn] != prev[fn]):
309 removed |= set(prev.keys())
311 return added | modified, removed
313 def fixup_user_git(user):
315 user = user.replace('"', '')
316 m = AUTHOR_RE.match(user)
319 mail = m.group(2).strip()
321 m = EMAIL_RE.match(user)
325 m = NAME_RE.match(user)
327 name = m.group(1).strip()
330 def fixup_user_hg(user):
332 # stole this from hg-git
333 return re.sub('[<>\n]', '?', name.lstrip('< ').rstrip('> '))
335 m = AUTHOR_HG_RE.match(user)
337 name = sanitize(m.group(1))
338 mail = sanitize(m.group(2))
341 name += ' ext:(' + urllib.quote(ex) + ')'
343 name = sanitize(user)
351 def fixup_user(user):
353 name, mail = fixup_user_git(user)
355 name, mail = fixup_user_hg(user)
362 return '%s <%s>' % (name, mail)
364 def updatebookmarks(repo, peer):
365 remotemarks = peer.listkeys('bookmarks')
366 localmarks = repo._bookmarks
371 for k, v in remotemarks.iteritems():
372 localmarks[k] = hgbin(v)
374 if hasattr(localmarks, 'write'):
377 bookmarks.write(repo)
379 def get_repo(url, alias):
383 myui.setconfig('ui', 'interactive', 'off')
384 myui.fout = sys.stderr
386 if get_config_bool('remote-hg.insecure'):
387 myui.setconfig('web', 'cacerts', '')
389 extensions.loadall(myui)
391 if hg.islocal(url) and not os.environ.get('GIT_REMOTE_HG_TEST_REMOTE'):
392 repo = hg.repository(myui, url)
393 if not os.path.exists(dirname):
396 shared_path = os.path.join(gitdir, 'hg')
398 # check and upgrade old organization
399 hg_path = os.path.join(shared_path, '.hg')
400 if os.path.exists(shared_path) and not os.path.exists(hg_path):
401 repos = os.listdir(shared_path)
403 local_hg = os.path.join(shared_path, x, 'clone', '.hg')
404 if not os.path.exists(local_hg):
406 if not os.path.exists(hg_path):
407 shutil.move(local_hg, hg_path)
408 shutil.rmtree(os.path.join(shared_path, x, 'clone'))
410 # setup shared repo (if not there)
412 hg.peer(myui, {}, shared_path, create=True)
413 except error.RepoError:
416 if not os.path.exists(dirname):
419 local_path = os.path.join(dirname, 'clone')
420 if not os.path.exists(local_path):
421 hg.share(myui, shared_path, local_path, update=False)
423 # make sure the shared path is always up-to-date
424 util.writefile(os.path.join(local_path, '.hg', 'sharedpath'), hg_path)
426 repo = hg.repository(myui, local_path)
428 peer = hg.peer(myui, {}, url)
430 die('Repository error')
431 repo.pull(peer, heads=None, force=True)
433 updatebookmarks(repo, peer)
437 def rev_to_mark(rev):
438 return marks.from_rev(rev.hex())
440 def mark_to_rev(mark):
441 return marks.to_rev(mark)
443 def export_ref(repo, name, kind, head):
444 ename = '%s/%s' % (kind, name)
446 tip = marks.get_tip(ename)
447 tip = repo[tip].rev()
451 revs = xrange(tip, head.rev() + 1)
459 if marks.is_marked(c.hex()):
462 (manifest, user, (time, tz), files, desc, extra) = repo.changelog.read(node)
463 rev_branch = extra['branch']
465 author = "%s %d %s" % (fixup_user(user), time, gittz(tz))
466 if 'committer' in extra:
467 user, time, tz = extra['committer'].rsplit(' ', 2)
468 committer = "%s %s %s" % (user, time, gittz(int(tz)))
472 parents = [repo[p] for p in repo.changelog.parentrevs(rev) if p >= 0]
474 if len(parents) == 0:
475 modified = c.manifest().keys()
478 modified, removed = get_filechanges(repo, c, parents[0])
485 if rev_branch != 'default':
486 extra_msg += 'branch : %s\n' % rev_branch
490 if f not in c.manifest():
492 rename = c.filectx(f).renamed()
494 renames.append((rename[0], f))
497 extra_msg += "rename : %s => %s\n" % e
499 for key, value in extra.iteritems():
500 if key in ('author', 'committer', 'encoding', 'message', 'branch', 'hg-git'):
503 extra_msg += "extra : %s : %s\n" % (key, urllib.quote(value))
506 desc += '\n--HG--\n' + extra_msg
508 if len(parents) == 0 and rev:
509 print 'reset %s/%s' % (prefix, ename)
511 modified_final = export_files(c.filectx(f) for f in modified)
513 print "commit %s/%s" % (prefix, ename)
514 print "mark :%d" % (marks.get_mark(c.hex()))
515 print "author %s" % (author)
516 print "committer %s" % (committer)
517 print "data %d" % (len(desc))
521 print "from :%s" % (rev_to_mark(parents[0]))
523 print "merge :%s" % (rev_to_mark(parents[1]))
526 print "D %s" % (fix_file_path(f))
527 for f in modified_final:
528 print "M %s :%u %s" % f
531 progress = (rev - tip)
532 if (progress % 100 == 0):
533 print "progress revision %d '%s' (%d/%d)" % (rev, name, progress, total)
535 # make sure the ref is updated
536 print "reset %s/%s" % (prefix, ename)
537 print "from :%u" % rev_to_mark(head)
540 pending_revs = set(revs) - notes
542 note_mark = marks.next_mark()
543 ref = "refs/notes/hg"
545 print "commit %s" % ref
546 print "mark :%d" % (note_mark)
547 print "committer remote-hg <> %d %s" % (ptime.time(), gittz(ptime.timezone))
548 desc = "Notes for %s\n" % (name)
549 print "data %d" % (len(desc))
552 print "from :%u" % marks.last_note
554 for rev in pending_revs:
557 print "N inline :%u" % rev_to_mark(c)
559 print "data %d" % (len(msg))
563 marks.last_note = note_mark
565 marks.set_tip(ename, head.hex())
567 def export_tag(repo, tag):
568 export_ref(repo, tag, 'tags', repo[hgref(tag)])
570 def export_bookmark(repo, bmark):
571 head = bmarks[hgref(bmark)]
572 export_ref(repo, bmark, 'bookmarks', head)
574 def export_branch(repo, branch):
575 tip = get_branch_tip(repo, branch)
577 export_ref(repo, branch, 'branches', head)
579 def export_head(repo):
580 export_ref(repo, g_head[0], 'bookmarks', g_head[1])
582 def do_capabilities(parser):
585 print "refspec refs/heads/branches/*:%s/branches/*" % prefix
586 print "refspec refs/heads/*:%s/bookmarks/*" % prefix
587 print "refspec refs/tags/*:%s/tags/*" % prefix
589 path = os.path.join(dirname, 'marks-git')
591 if os.path.exists(path):
592 print "*import-marks %s" % path
593 print "*export-marks %s" % path
598 def branch_tip(branch):
599 return branches[branch][-1]
601 def get_branch_tip(repo, branch):
602 heads = branches.get(hgref(branch), None)
606 # verify there's only one head
608 warn("Branch '%s' has more than one head, consider merging" % branch)
609 return branch_tip(hgref(branch))
613 def list_head(repo, cur):
614 global g_head, fake_bmark
616 if 'default' not in branches:
620 node = repo[branch_tip('default')]
621 head = 'master' if not 'master' in bmarks else 'default'
626 print "@refs/heads/%s HEAD" % head
627 g_head = (head, node)
631 for bmark, node in bookmarks.listbookmarks(repo).iteritems():
632 bmarks[bmark] = repo[node]
634 cur = repo.dirstate.branch()
635 orig = peer if peer else repo
637 for branch, heads in orig.branchmap().iteritems():
639 heads = [h for h in heads if 'close' not in repo.changelog.read(h)[5]]
641 branches[branch] = heads
646 for branch in branches:
647 print "? refs/heads/branches/%s" % gitref(branch)
650 if bmarks[bmark].hex() == '0000000000000000000000000000000000000000':
651 warn("Ignoring invalid bookmark '%s'", bmark)
653 print "? refs/heads/%s" % gitref(bmark)
655 for tag, node in repo.tagslist():
658 print "? refs/tags/%s" % gitref(tag)
662 def do_import(parser):
665 path = os.path.join(dirname, 'marks-git')
668 if os.path.exists(path):
669 print "feature import-marks=%s" % path
670 print "feature export-marks=%s" % path
671 print "feature force"
674 tmp = encoding.encoding
675 encoding.encoding = 'utf-8'
677 # lets get all the import lines
678 while parser.check('import'):
683 elif ref.startswith('refs/heads/branches/'):
684 branch = ref[len('refs/heads/branches/'):]
685 export_branch(repo, branch)
686 elif ref.startswith('refs/heads/'):
687 bmark = ref[len('refs/heads/'):]
688 export_bookmark(repo, bmark)
689 elif ref.startswith('refs/tags/'):
690 tag = ref[len('refs/tags/'):]
691 export_tag(repo, tag)
695 encoding.encoding = tmp
699 def parse_blob(parser):
701 mark = parser.get_mark()
703 data = parser.get_data()
704 blob_marks[mark] = data
707 def get_merge_files(repo, p1, p2, files):
708 for e in repo[p1].files():
710 if e not in repo[p1].manifest():
712 f = { 'ctx' : repo[p1][e] }
715 def c_style_unescape(string):
716 if string[0] == string[-1] == '"':
717 return string.decode('string-escape')[1:-1]
720 def parse_commit(parser):
721 from_mark = merge_mark = None
726 commit_mark = parser.get_mark()
728 author = parser.get_author()
730 committer = parser.get_author()
732 data = parser.get_data()
734 if parser.check('from'):
735 from_mark = parser.get_mark()
737 if parser.check('merge'):
738 merge_mark = parser.get_mark()
740 if parser.check('merge'):
741 die('octopus merges are not supported yet')
743 # fast-export adds an extra newline
750 if parser.check('M'):
751 t, m, mark_ref, path = line.split(' ', 3)
752 mark = int(mark_ref[1:])
753 f = { 'mode' : hgmode(m), 'data' : blob_marks[mark] }
754 elif parser.check('D'):
755 t, path = line.split(' ', 1)
756 f = { 'deleted' : True }
758 die('Unknown file command: %s' % line)
759 path = c_style_unescape(path)
762 # only export the commits if we are on an internal proxy repo
763 if dry_run and not peer:
764 parsed_refs[ref] = None
767 def getfilectx(repo, memctx, f):
773 is_exec = of['mode'] == 'x'
774 is_link = of['mode'] == 'l'
775 rename = of.get('rename', None)
776 return context.memfilectx(f, of['data'],
777 is_link, is_exec, rename)
781 user, date, tz = author
784 if committer != author:
785 extra['committer'] = "%s %u %u" % committer
788 p1 = mark_to_rev(from_mark)
793 p2 = mark_to_rev(merge_mark)
798 # If files changed from any of the parents, hg wants to know, but in git if
799 # nothing changed from the first parent, nothing changed.
802 get_merge_files(repo, p1, p2, files)
804 # Check if the ref is supposed to be a named branch
805 if ref.startswith('refs/heads/branches/'):
806 branch = ref[len('refs/heads/branches/'):]
807 extra['branch'] = hgref(branch)
810 i = data.find('\n--HG--\n')
812 tmp = data[i + len('\n--HG--\n'):].strip()
813 for k, v in [e.split(' : ', 1) for e in tmp.split('\n')]:
815 old, new = v.split(' => ', 1)
816 files[new]['rename'] = old
820 ek, ev = v.split(' : ', 1)
821 extra[ek] = urllib.unquote(ev)
824 ctx = context.memctx(repo, (p1, p2), data,
825 files.keys(), getfilectx,
826 user, (date, tz), extra)
828 tmp = encoding.encoding
829 encoding.encoding = 'utf-8'
831 node = hghex(repo.commitctx(ctx))
833 encoding.encoding = tmp
835 parsed_refs[ref] = node
836 marks.new_mark(node, commit_mark)
838 def parse_reset(parser):
842 if parser.check('commit'):
845 if not parser.check('from'):
847 from_mark = parser.get_mark()
851 rev = mark_to_rev(from_mark)
854 parsed_refs[ref] = rev
856 def parse_tag(parser):
859 from_mark = parser.get_mark()
861 tagger = parser.get_author()
863 data = parser.get_data()
866 parsed_tags[name] = (tagger, data)
868 def write_tag(repo, tag, node, msg, author):
869 branch = repo[node].branch()
870 tip = branch_tip(branch)
873 def getfilectx(repo, memctx, f):
875 fctx = tip.filectx(f)
877 except error.ManifestLookupError:
879 content = data + "%s %s\n" % (node, tag)
880 return context.memfilectx(f, content, False, False, None)
885 user, date, tz = author
888 cmd = ['git', 'var', 'GIT_COMMITTER_IDENT']
889 process = subprocess.Popen(cmd, stdout=subprocess.PIPE)
890 output, _ = process.communicate()
891 m = re.match('^.* <.*>', output)
895 user = repo.ui.username()
898 ctx = context.memctx(repo, (p1, p2), msg,
899 ['.hgtags'], getfilectx,
900 user, date_tz, {'branch' : branch})
902 tmp = encoding.encoding
903 encoding.encoding = 'utf-8'
905 tagnode = repo.commitctx(ctx)
907 encoding.encoding = tmp
909 return (tagnode, branch)
911 def checkheads_bmark(repo, ref, ctx):
912 bmark = ref[len('refs/heads/'):]
913 if not bmark in bmarks:
917 ctx_old = bmarks[bmark]
919 if not repo.changelog.descendant(ctx_old.rev(), ctx_new.rev()):
921 print "ok %s forced update" % ref
923 print "error %s non-fast forward" % ref
928 def checkheads(repo, remote, p_revs):
930 remotemap = remote.branchmap()
938 for node, ref in p_revs.iteritems():
940 branch = ctx.branch()
941 if not branch in remotemap:
944 if not ref.startswith('refs/heads/branches'):
945 if ref.startswith('refs/heads/'):
946 if not checkheads_bmark(repo, ref, ctx):
949 # only check branches
951 new.setdefault(branch, []).append(ctx.rev())
953 for branch, heads in new.iteritems():
954 old = [repo.changelog.rev(x) for x in remotemap[branch]]
956 if check_version(2, 3):
957 ancestors = repo.changelog.ancestors([rev], stoprev=min(old))
959 ancestors = repo.changelog.ancestors(rev)
970 node = repo.changelog.node(rev)
973 print "ok %s forced update" % ref
975 print "error %s non-fast forward" % ref
980 def push_unsafe(repo, remote, parsed_refs, p_revs):
984 fci = discovery.findcommonincoming
985 commoninc = fci(repo, remote, force=force)
986 common, _, remoteheads = commoninc
988 if not checkheads(repo, remote, p_revs):
991 cg = repo.getbundle('push', heads=list(p_revs), common=common)
993 unbundle = remote.capable('unbundle')
996 remoteheads = ['force']
997 return remote.unbundle(cg, remoteheads, 'push')
999 return remote.addchangegroup(cg, 'push', repo.url())
1001 def push(repo, remote, parsed_refs, p_revs):
1002 if hasattr(remote, 'canpush') and not remote.canpush():
1003 print "error cannot push"
1010 unbundle = remote.capable('unbundle')
1012 lock = remote.lock()
1014 ret = push_unsafe(repo, remote, parsed_refs, p_revs)
1016 if lock is not None:
1021 def check_tip(ref, kind, name, heads):
1023 ename = '%s/%s' % (kind, name)
1024 tip = marks.get_tip(ename)
1030 def do_export(parser):
1036 for line in parser.each_block('done'):
1037 if parser.check('blob'):
1039 elif parser.check('commit'):
1040 parse_commit(parser)
1041 elif parser.check('reset'):
1043 elif parser.check('tag'):
1045 elif parser.check('feature'):
1048 die('unhandled export command: %s' % line)
1052 for ref, node in parsed_refs.iteritems():
1053 bnode = hgbin(node) if node else None
1054 if ref.startswith('refs/heads/branches'):
1055 branch = ref[len('refs/heads/branches/'):]
1056 if branch in branches and bnode in branches[branch]:
1061 remotemap = peer.branchmap()
1062 if remotemap and branch in remotemap:
1063 heads = [hghex(e) for e in remotemap[branch]]
1064 if not check_tip(ref, 'branches', branch, heads):
1065 print "error %s fetch first" % ref
1071 elif ref.startswith('refs/heads/'):
1072 bmark = ref[len('refs/heads/'):]
1074 old = bmarks[bmark].hex() if bmark in bmarks else ''
1080 if bmark != fake_bmark and \
1081 not (bmark == 'master' and bmark not in parser.repo._bookmarks):
1082 p_bmarks.append((ref, bmark, old, new))
1085 remote_old = peer.listkeys('bookmarks').get(bmark)
1087 if not check_tip(ref, 'bookmarks', bmark, remote_old):
1088 print "error %s fetch first" % ref
1093 elif ref.startswith('refs/tags/'):
1097 tag = ref[len('refs/tags/'):]
1099 author, msg = parsed_tags.get(tag, (None, None))
1102 msg = 'Added tag %s for changeset %s' % (tag, node[:12])
1103 tagnode, branch = write_tag(parser.repo, tag, node, msg, author)
1104 p_revs[tagnode] = 'refs/heads/branches/' + gitref(branch)
1106 fp = parser.repo.opener('localtags', 'a')
1107 fp.write('%s %s\n' % (node, tag))
1112 # transport-helper/fast-export bugs
1120 if peer and not force_push:
1121 checkheads(parser.repo, peer, p_revs)
1126 if not push(parser.repo, peer, parsed_refs, p_revs):
1127 # do not update bookmarks
1131 # update remote bookmarks
1132 remote_bmarks = peer.listkeys('bookmarks')
1133 for ref, bmark, old, new in p_bmarks:
1135 old = remote_bmarks.get(bmark, '')
1136 if not peer.pushkey('bookmarks', bmark, old, new):
1137 print "error %s" % ref
1139 # update local bookmarks
1140 for ref, bmark, old, new in p_bmarks:
1141 if not bookmarks.pushbookmark(parser.repo, bmark, old, new):
1142 print "error %s" % ref
1146 def do_option(parser):
1147 global dry_run, force_push
1148 _, key, value = parser.line.split(' ')
1149 if key == 'dry-run':
1150 dry_run = (value == 'true')
1152 elif key == 'force':
1153 force_push = (value == 'true')
1158 def fix_path(alias, repo, orig_url):
1159 url = urlparse.urlparse(orig_url, 'file')
1160 if url.scheme != 'file' or os.path.isabs(os.path.expanduser(url.path)):
1162 abs_url = urlparse.urljoin("%s/" % os.getcwd(), orig_url)
1163 cmd = ['git', 'config', 'remote.%s.url' % alias, "hg::%s" % abs_url]
1164 subprocess.call(cmd)
1167 global prefix, gitdir, dirname, branches, bmarks
1168 global marks, blob_marks, parsed_refs
1169 global peer, mode, bad_mail, bad_name
1170 global track_branches, force_push, is_tmp
1173 global fake_bmark, hg_version
1179 gitdir = os.environ.get('GIT_DIR', None)
1182 die('Not enough arguments.')
1185 die('GIT_DIR not set')
1191 hg_git_compat = get_config_bool('remote-hg.hg-git-compat')
1192 track_branches = get_config_bool('remote-hg.track-branches', True)
1197 bad_mail = 'none@none'
1201 bad_mail = 'unknown'
1202 bad_name = 'Unknown'
1204 if alias[4:] == url:
1206 alias = hashlib.sha1(alias).hexdigest()
1208 dirname = os.path.join(gitdir, 'hg', alias)
1217 hg_version = tuple(int(e) for e in util.version().split('.'))
1223 repo = get_repo(url, alias)
1224 prefix = 'refs/hg/%s' % alias
1227 fix_path(alias, peer or repo, url)
1229 marks_path = os.path.join(dirname, 'marks-hg')
1230 marks = Marks(marks_path, repo)
1232 if sys.platform == 'win32':
1234 msvcrt.setmode(sys.stdout.fileno(), os.O_BINARY)
1236 parser = Parser(repo)
1238 if parser.check('capabilities'):
1239 do_capabilities(parser)
1240 elif parser.check('list'):
1242 elif parser.check('import'):
1244 elif parser.check('export'):
1246 elif parser.check('option'):
1249 die('unhandled command: %s' % line)
1258 shutil.rmtree(dirname)
1260 atexit.register(bye)
1261 sys.exit(main(sys.argv))