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
16 from mercurial import changegroup
26 import urlparse, hashlib
30 # If you want to see Mercurial revisions as Git commit notes:
31 # git config core.notesRef refs/notes/hg
33 # If you are not in hg-git-compat mode and want to disable the tracking of
35 # git config --global remote-hg.track-branches false
37 # If you want the equivalent of hg's clone/pull--insecure option:
38 # git config --global remote-hg.insecure true
40 # If you want to switch to hg-git compatibility mode:
41 # git config --global remote-hg.hg-git-compat true
44 # Sensible defaults for git.
45 # hg bookmarks are exported as git branches, hg branches are prefixed
46 # with 'branches/', HEAD is a special case.
50 # Only hg bookmarks are exported as git branches.
51 # Commits are modified to preserve hg information and allow bidirectionality.
54 NAME_RE = re.compile('^([^<>]+)')
55 AUTHOR_RE = re.compile('^([^<>]+?)? ?[<>]([^<>]*)(?:$|>)')
56 EMAIL_RE = re.compile(r'([^ \t<>]+@[^ \t<>]+)')
57 AUTHOR_HG_RE = re.compile('^(.*?) ?<(.*?)(?:>(.*))?$')
58 RAW_AUTHOR_RE = re.compile('^(\w+) (?:(.+)? )?<(.*)> (\d+) ([+-]\d+)')
63 sys.stderr.write('ERROR: %s\n' % (msg % args))
67 sys.stderr.write('WARNING: %s\n' % (msg % args))
70 return 'l' in flags and '120000' or 'x' in flags and '100755' or '100644'
73 return '%+03d%02d' % (-tz / 3600, -tz % 3600 / 60)
76 m = { '100755': 'x', '120000': 'l' }
77 return m.get(mode, '')
86 return ref.replace('___', ' ')
89 return ref.replace(' ', '___')
91 def check_version(*check):
94 return hg_version >= check
96 def get_config(config):
97 cmd = ['git', 'config', '--get', config]
98 process = subprocess.Popen(cmd, stdout=subprocess.PIPE)
99 output, _ = process.communicate()
102 def get_config_bool(config, default=False):
103 value = get_config(config).rstrip('\n')
106 elif value == "false":
113 def __init__(self, path, repo):
119 if self.version < VERSION:
120 if self.version == 1:
124 if self.version < VERSION:
126 self.version = VERSION
137 if not os.path.exists(self.path):
140 tmp = json.load(open(self.path))
142 self.tips = tmp['tips']
143 self.marks = tmp['marks']
144 self.last_mark = tmp['last-mark']
145 self.version = tmp.get('version', 1)
146 self.last_note = tmp.get('last-note', 0)
148 for rev, mark in self.marks.iteritems():
149 self.rev_marks[mark] = rev
151 def upgrade_one(self):
153 return hghex(self.repo.changelog.node(int(rev)))
154 self.tips = dict((name, get_id(rev)) for name, rev in self.tips.iteritems())
155 self.marks = dict((get_id(rev), mark) for rev, mark in self.marks.iteritems())
156 self.rev_marks = dict((mark, get_id(rev)) for mark, rev in self.rev_marks.iteritems())
160 return { 'tips': self.tips, 'marks': self.marks, 'last-mark' : self.last_mark, 'version' : self.version, 'last-note' : self.last_note }
163 json.dump(self.dict(), open(self.path, 'w'))
166 return str(self.dict())
168 def from_rev(self, rev):
169 return self.marks[rev]
171 def to_rev(self, mark):
172 return str(self.rev_marks[mark])
176 return self.last_mark
178 def get_mark(self, rev):
180 self.marks[rev] = self.last_mark
181 return self.last_mark
183 def new_mark(self, rev, mark):
184 self.marks[rev] = mark
185 self.rev_marks[mark] = rev
186 self.last_mark = mark
188 def is_marked(self, rev):
189 return rev in self.marks
191 def get_tip(self, branch):
192 return str(self.tips[branch])
194 def set_tip(self, branch, tip):
195 self.tips[branch] = tip
199 def __init__(self, repo):
201 self.line = self.get_line()
204 return sys.stdin.readline().strip()
206 def __getitem__(self, i):
207 return self.line.split()[i]
209 def check(self, word):
210 return self.line.startswith(word)
212 def each_block(self, separator):
213 while self.line != separator:
215 self.line = self.get_line()
218 return self.each_block('')
221 self.line = self.get_line()
222 if self.line == 'done':
226 i = self.line.index(':') + 1
227 return int(self.line[i:])
230 if not self.check('data'):
232 i = self.line.index(' ') + 1
233 size = int(self.line[i:])
234 return sys.stdin.read(size)
236 def get_author(self):
238 m = RAW_AUTHOR_RE.match(self.line)
241 _, name, email, date, tz = m.groups()
242 if name and 'ext:' in name:
243 m = re.match('^(.+?) ext:\((.+)\)$', name)
246 ex = urllib.unquote(m.group(2))
248 if email != bad_mail:
250 user = '%s <%s>' % (name, email)
252 user = '<%s>' % (email)
260 tz = ((tz / 100) * 3600) + ((tz % 100) * 60)
261 return (user, int(date), -tz)
263 def fix_file_path(path):
264 path = os.path.normpath(path)
265 if not os.path.isabs(path):
267 return os.path.relpath(path, '/')
269 def export_files(files):
272 fid = node.hex(f.filenode())
275 mark = filenodes[fid]
277 mark = marks.next_mark()
278 filenodes[fid] = mark
282 print "mark :%u" % mark
283 print "data %d" % len(d)
286 path = fix_file_path(f.path())
287 final.append((gitmode(f.flags()), mark, path))
291 def get_filechanges(repo, ctx, parent):
296 # load earliest manifest first for caching reasons
297 prev = parent.manifest().copy()
302 if (cur.flags(fn) != prev.flags(fn) or cur[fn] != prev[fn]):
307 removed |= set(prev.keys())
309 return added | modified, removed
311 def fixup_user_git(user):
313 user = user.replace('"', '')
314 m = AUTHOR_RE.match(user)
317 mail = m.group(2).strip()
319 m = EMAIL_RE.match(user)
323 m = NAME_RE.match(user)
325 name = m.group(1).strip()
328 def fixup_user_hg(user):
330 # stole this from hg-git
331 return re.sub('[<>\n]', '?', name.lstrip('< ').rstrip('> '))
333 m = AUTHOR_HG_RE.match(user)
335 name = sanitize(m.group(1))
336 mail = sanitize(m.group(2))
339 name += ' ext:(' + urllib.quote(ex) + ')'
341 name = sanitize(user)
349 def fixup_user(user):
351 name, mail = fixup_user_git(user)
353 name, mail = fixup_user_hg(user)
360 return '%s <%s>' % (name, mail)
362 def updatebookmarks(repo, peer):
363 remotemarks = peer.listkeys('bookmarks')
364 localmarks = repo._bookmarks
369 for k, v in remotemarks.iteritems():
370 localmarks[k] = hgbin(v)
372 if hasattr(localmarks, 'write'):
375 bookmarks.write(repo)
377 def get_repo(url, alias):
381 myui.setconfig('ui', 'interactive', 'off')
382 myui.fout = sys.stderr
384 if get_config_bool('remote-hg.insecure'):
385 myui.setconfig('web', 'cacerts', '')
387 extensions.loadall(myui)
389 if hg.islocal(url) and not os.environ.get('GIT_REMOTE_HG_TEST_REMOTE'):
390 repo = hg.repository(myui, url)
391 if not os.path.exists(dirname):
394 shared_path = os.path.join(gitdir, 'hg')
396 # check and upgrade old organization
397 hg_path = os.path.join(shared_path, '.hg')
398 if os.path.exists(shared_path) and not os.path.exists(hg_path):
399 repos = os.listdir(shared_path)
401 local_hg = os.path.join(shared_path, x, 'clone', '.hg')
402 if not os.path.exists(local_hg):
404 if not os.path.exists(hg_path):
405 shutil.move(local_hg, hg_path)
406 shutil.rmtree(os.path.join(shared_path, x, 'clone'))
408 # setup shared repo (if not there)
410 hg.peer(myui, {}, shared_path, create=True)
411 except error.RepoError:
414 if not os.path.exists(dirname):
417 local_path = os.path.join(dirname, 'clone')
418 if not os.path.exists(local_path):
419 hg.share(myui, shared_path, local_path, update=False)
421 # make sure the shared path is always up-to-date
422 util.writefile(os.path.join(local_path, '.hg', 'sharedpath'), hg_path)
424 repo = hg.repository(myui, local_path)
426 peer = hg.peer(repo.ui, {}, url)
428 die('Repository error')
429 repo.pull(peer, heads=None, force=True)
431 updatebookmarks(repo, peer)
435 def rev_to_mark(rev):
436 return marks.from_rev(rev.hex())
438 def mark_to_rev(mark):
439 return marks.to_rev(mark)
441 # Get a range of revisions in the form of a..b (git committish)
442 def gitrange(repo, a, b):
444 pending = set([int(b)])
445 negative = set([int(a)])
446 for cur in xrange(b, -1, -1):
450 parents = [p for p in repo.changelog.parentrevs(cur) if p >= 0]
456 if not p in negative:
458 elif cur in negative:
469 def export_ref(repo, name, kind, head):
470 ename = '%s/%s' % (kind, name)
472 tip = marks.get_tip(ename)
477 revs = gitrange(repo, tip, head)
487 if marks.is_marked(c.hex()):
490 (manifest, user, (time, tz), files, desc, extra) = repo.changelog.read(node)
491 rev_branch = extra['branch']
493 author = "%s %d %s" % (fixup_user(user), time, gittz(tz))
494 if 'committer' in extra:
496 cuser, ctime, ctz = extra['committer'].rsplit(' ', 2)
497 committer = "%s %s %s" % (cuser, ctime, gittz(int(ctz)))
499 cuser = extra['committer']
500 committer = "%s %d %s" % (fixup_user(cuser), time, gittz(tz))
504 parents = [repo[p] for p in repo.changelog.parentrevs(rev) if p >= 0]
506 if len(parents) == 0:
507 modified = c.manifest().keys()
510 modified, removed = get_filechanges(repo, c, parents[0])
517 if rev_branch != 'default':
518 extra_msg += 'branch : %s\n' % rev_branch
522 if f not in c.manifest():
524 rename = c.filectx(f).renamed()
526 renames.append((rename[0], f))
529 extra_msg += "rename : %s => %s\n" % e
531 for key, value in extra.iteritems():
532 if key in ('author', 'committer', 'encoding', 'message', 'branch', 'hg-git'):
535 extra_msg += "extra : %s : %s\n" % (key, urllib.quote(value))
538 desc += '\n--HG--\n' + extra_msg
540 if len(parents) == 0 and rev:
541 print 'reset %s/%s' % (prefix, ename)
543 modified_final = export_files(c.filectx(f) for f in modified)
545 print "commit %s/%s" % (prefix, ename)
546 print "mark :%d" % (marks.get_mark(c.hex()))
547 print "author %s" % (author)
548 print "committer %s" % (committer)
549 print "data %d" % (len(desc))
553 print "from :%s" % (rev_to_mark(parents[0]))
555 print "merge :%s" % (rev_to_mark(parents[1]))
558 print "D %s" % (fix_file_path(f))
559 for f in modified_final:
560 print "M %s :%u %s" % f
563 progress = (rev - tip)
564 if (progress % 100 == 0):
565 print "progress revision %d '%s' (%d/%d)" % (rev, name, progress, total)
567 # make sure the ref is updated
568 print "reset %s/%s" % (prefix, ename)
569 print "from :%u" % rev_to_mark(head)
572 pending_revs = set(revs) - notes
574 note_mark = marks.next_mark()
575 ref = "refs/notes/hg"
577 print "commit %s" % ref
578 print "mark :%d" % (note_mark)
579 print "committer remote-hg <> %d %s" % (ptime.time(), gittz(ptime.timezone))
580 desc = "Notes for %s\n" % (name)
581 print "data %d" % (len(desc))
584 print "from :%u" % marks.last_note
586 for rev in pending_revs:
589 print "N inline :%u" % rev_to_mark(c)
591 print "data %d" % (len(msg))
595 marks.last_note = note_mark
597 marks.set_tip(ename, head.hex())
599 def export_tag(repo, tag):
600 export_ref(repo, tag, 'tags', repo[hgref(tag)])
602 def export_bookmark(repo, bmark):
603 head = bmarks[hgref(bmark)]
604 export_ref(repo, bmark, 'bookmarks', head)
606 def export_branch(repo, branch):
607 tip = get_branch_tip(repo, branch)
609 export_ref(repo, branch, 'branches', head)
611 def export_head(repo):
612 export_ref(repo, g_head[0], 'bookmarks', g_head[1])
614 def do_capabilities(parser):
617 print "refspec refs/heads/branches/*:%s/branches/*" % prefix
618 print "refspec refs/heads/*:%s/bookmarks/*" % prefix
619 print "refspec refs/tags/*:%s/tags/*" % prefix
621 path = os.path.join(dirname, 'marks-git')
623 if os.path.exists(path):
624 print "*import-marks %s" % path
625 print "*export-marks %s" % path
630 def branch_tip(branch):
631 return branches[branch][-1]
633 def get_branch_tip(repo, branch):
634 heads = branches.get(hgref(branch), None)
638 # verify there's only one head
640 warn("Branch '%s' has more than one head, consider merging" % branch)
641 return branch_tip(hgref(branch))
645 def list_head(repo, cur):
646 global g_head, fake_bmark
648 if 'default' not in branches:
652 node = repo[branch_tip('default')]
653 head = 'master' if not 'master' in bmarks else 'default'
658 print "@refs/heads/%s HEAD" % head
659 g_head = (head, node)
663 for bmark, node in bookmarks.listbookmarks(repo).iteritems():
664 bmarks[bmark] = repo[node]
666 cur = repo.dirstate.branch()
667 orig = peer if peer else repo
669 for branch, heads in orig.branchmap().iteritems():
671 heads = [h for h in heads if 'close' not in repo.changelog.read(h)[5]]
673 branches[branch] = heads
678 for branch in branches:
679 print "? refs/heads/branches/%s" % gitref(branch)
682 if bmarks[bmark].hex() == '0' * 40:
683 warn("Ignoring invalid bookmark '%s'", bmark)
685 print "? refs/heads/%s" % gitref(bmark)
687 for tag, node in repo.tagslist():
690 print "? refs/tags/%s" % gitref(tag)
694 def do_import(parser):
697 path = os.path.join(dirname, 'marks-git')
700 if os.path.exists(path):
701 print "feature import-marks=%s" % path
702 print "feature export-marks=%s" % path
703 print "feature force"
706 tmp = encoding.encoding
707 encoding.encoding = 'utf-8'
709 # lets get all the import lines
710 while parser.check('import'):
715 elif ref.startswith('refs/heads/branches/'):
716 branch = ref[len('refs/heads/branches/'):]
717 export_branch(repo, branch)
718 elif ref.startswith('refs/heads/'):
719 bmark = ref[len('refs/heads/'):]
720 export_bookmark(repo, bmark)
721 elif ref.startswith('refs/tags/'):
722 tag = ref[len('refs/tags/'):]
723 export_tag(repo, tag)
727 encoding.encoding = tmp
731 def parse_blob(parser):
733 mark = parser.get_mark()
735 data = parser.get_data()
736 blob_marks[mark] = data
739 def get_merge_files(repo, p1, p2, files):
740 for e in repo[p1].files():
742 if e not in repo[p1].manifest():
744 f = { 'ctx' : repo[p1][e] }
747 def c_style_unescape(string):
748 if string[0] == string[-1] == '"':
749 return string.decode('string-escape')[1:-1]
752 def parse_commit(parser):
753 from_mark = merge_mark = None
758 commit_mark = parser.get_mark()
760 author = parser.get_author()
762 committer = parser.get_author()
764 data = parser.get_data()
766 if parser.check('from'):
767 from_mark = parser.get_mark()
769 if parser.check('merge'):
770 merge_mark = parser.get_mark()
772 if parser.check('merge'):
773 die('octopus merges are not supported yet')
775 # fast-export adds an extra newline
782 if parser.check('M'):
783 t, m, mark_ref, path = line.split(' ', 3)
784 mark = int(mark_ref[1:])
785 f = { 'mode' : hgmode(m), 'data' : blob_marks[mark] }
786 elif parser.check('D'):
787 t, path = line.split(' ', 1)
788 f = { 'deleted' : True }
790 die('Unknown file command: %s' % line)
791 path = c_style_unescape(path)
794 # only export the commits if we are on an internal proxy repo
795 if dry_run and not peer:
796 parsed_refs[ref] = None
799 def getfilectx(repo, memctx, f):
805 is_exec = of['mode'] == 'x'
806 is_link = of['mode'] == 'l'
807 rename = of.get('rename', None)
808 return context.memfilectx(f, of['data'],
809 is_link, is_exec, rename)
813 user, date, tz = author
816 if committer != author:
817 extra['committer'] = "%s %u %u" % committer
820 p1 = mark_to_rev(from_mark)
825 p2 = mark_to_rev(merge_mark)
830 # If files changed from any of the parents, hg wants to know, but in git if
831 # nothing changed from the first parent, nothing changed.
834 get_merge_files(repo, p1, p2, files)
836 # Check if the ref is supposed to be a named branch
837 if ref.startswith('refs/heads/branches/'):
838 branch = ref[len('refs/heads/branches/'):]
839 extra['branch'] = hgref(branch)
842 i = data.find('\n--HG--\n')
844 tmp = data[i + len('\n--HG--\n'):].strip()
845 for k, v in [e.split(' : ', 1) for e in tmp.split('\n')]:
847 old, new = v.split(' => ', 1)
848 files[new]['rename'] = old
852 ek, ev = v.split(' : ', 1)
853 extra[ek] = urllib.unquote(ev)
856 ctx = context.memctx(repo, (p1, p2), data,
857 files.keys(), getfilectx,
858 user, (date, tz), extra)
860 tmp = encoding.encoding
861 encoding.encoding = 'utf-8'
863 node = hghex(repo.commitctx(ctx))
865 encoding.encoding = tmp
867 parsed_refs[ref] = node
868 marks.new_mark(node, commit_mark)
870 def parse_reset(parser):
874 if parser.check('commit'):
877 if not parser.check('from'):
879 from_mark = parser.get_mark()
883 rev = mark_to_rev(from_mark)
886 parsed_refs[ref] = rev
888 def parse_tag(parser):
891 from_mark = parser.get_mark()
893 tagger = parser.get_author()
895 data = parser.get_data()
898 parsed_tags[name] = (tagger, data)
900 def write_tag(repo, tag, node, msg, author):
901 branch = repo[node].branch()
902 tip = branch_tip(branch)
905 def getfilectx(repo, memctx, f):
907 fctx = tip.filectx(f)
909 except error.ManifestLookupError:
911 content = data + "%s %s\n" % (node, tag)
912 return context.memfilectx(f, content, False, False, None)
917 user, date, tz = author
920 cmd = ['git', 'var', 'GIT_COMMITTER_IDENT']
921 process = subprocess.Popen(cmd, stdout=subprocess.PIPE)
922 output, _ = process.communicate()
923 m = re.match('^.* <.*>', output)
927 user = repo.ui.username()
930 ctx = context.memctx(repo, (p1, p2), msg,
931 ['.hgtags'], getfilectx,
932 user, date_tz, {'branch' : branch})
934 tmp = encoding.encoding
935 encoding.encoding = 'utf-8'
937 tagnode = repo.commitctx(ctx)
939 encoding.encoding = tmp
941 return (tagnode, branch)
943 def checkheads_bmark(repo, ref, ctx):
944 bmark = ref[len('refs/heads/'):]
945 if not bmark in bmarks:
949 ctx_old = bmarks[bmark]
953 print "error %s unknown" % ref
956 if not repo.changelog.descendant(ctx_old.rev(), ctx_new.rev()):
958 print "ok %s forced update" % ref
960 print "error %s non-fast forward" % ref
965 def checkheads(repo, remote, p_revs):
967 remotemap = remote.branchmap()
975 for node, ref in p_revs.iteritems():
977 branch = ctx.branch()
978 if not branch in remotemap:
981 if not ref.startswith('refs/heads/branches'):
982 if ref.startswith('refs/heads/'):
983 if not checkheads_bmark(repo, ref, ctx):
986 # only check branches
988 new.setdefault(branch, []).append(ctx.rev())
990 for branch, heads in new.iteritems():
991 old = [repo.changelog.rev(x) for x in remotemap[branch]]
993 if check_version(2, 3):
994 ancestors = repo.changelog.ancestors([rev], stoprev=min(old))
996 ancestors = repo.changelog.ancestors(rev)
1007 node = repo.changelog.node(rev)
1010 print "ok %s forced update" % ref
1012 print "error %s non-fast forward" % ref
1017 def push_unsafe(repo, remote, parsed_refs, p_revs):
1021 fci = discovery.findcommonincoming
1022 commoninc = fci(repo, remote, force=force)
1023 common, _, remoteheads = commoninc
1025 if not checkheads(repo, remote, p_revs):
1028 if check_version(3, 0):
1029 cg = changegroup.getbundle(repo, 'push', heads=list(p_revs), common=common)
1031 cg = repo.getbundle('push', heads=list(p_revs), common=common)
1033 unbundle = remote.capable('unbundle')
1036 remoteheads = ['force']
1037 ret = remote.unbundle(cg, remoteheads, 'push')
1039 ret = remote.addchangegroup(cg, 'push', repo.url())
1041 phases = remote.listkeys('phases')
1045 remote.pushkey('phases', hghex(head), '1', '0')
1049 def push(repo, remote, parsed_refs, p_revs):
1050 if hasattr(remote, 'canpush') and not remote.canpush():
1051 print "error cannot push"
1058 unbundle = remote.capable('unbundle')
1060 lock = remote.lock()
1062 ret = push_unsafe(repo, remote, parsed_refs, p_revs)
1064 if lock is not None:
1069 def check_tip(ref, kind, name, heads):
1071 ename = '%s/%s' % (kind, name)
1072 tip = marks.get_tip(ename)
1078 def do_export(parser):
1084 for line in parser.each_block('done'):
1085 if parser.check('blob'):
1087 elif parser.check('commit'):
1088 parse_commit(parser)
1089 elif parser.check('reset'):
1091 elif parser.check('tag'):
1093 elif parser.check('feature'):
1096 die('unhandled export command: %s' % line)
1100 for ref, node in parsed_refs.iteritems():
1101 bnode = hgbin(node) if node else None
1102 if ref.startswith('refs/heads/branches'):
1103 branch = ref[len('refs/heads/branches/'):]
1104 if branch in branches and bnode in branches[branch]:
1109 remotemap = peer.branchmap()
1110 if remotemap and branch in remotemap:
1111 heads = [hghex(e) for e in remotemap[branch]]
1112 if not check_tip(ref, 'branches', branch, heads):
1113 print "error %s fetch first" % ref
1119 elif ref.startswith('refs/heads/'):
1120 bmark = ref[len('refs/heads/'):]
1122 old = bmarks[bmark].hex() if bmark in bmarks else ''
1128 if bmark != fake_bmark and \
1129 not (bmark == 'master' and bmark not in parser.repo._bookmarks):
1130 p_bmarks.append((ref, bmark, old, new))
1133 remote_old = peer.listkeys('bookmarks').get(bmark)
1135 if not check_tip(ref, 'bookmarks', bmark, remote_old):
1136 print "error %s fetch first" % ref
1141 elif ref.startswith('refs/tags/'):
1145 tag = ref[len('refs/tags/'):]
1147 author, msg = parsed_tags.get(tag, (None, None))
1150 msg = 'Added tag %s for changeset %s' % (tag, node[:12])
1151 tagnode, branch = write_tag(parser.repo, tag, node, msg, author)
1152 p_revs[tagnode] = 'refs/heads/branches/' + gitref(branch)
1154 fp = parser.repo.opener('localtags', 'a')
1155 fp.write('%s %s\n' % (node, tag))
1160 # transport-helper/fast-export bugs
1168 if peer and not force_push:
1169 checkheads(parser.repo, peer, p_revs)
1174 if not push(parser.repo, peer, parsed_refs, p_revs):
1175 # do not update bookmarks
1179 # update remote bookmarks
1180 remote_bmarks = peer.listkeys('bookmarks')
1181 for ref, bmark, old, new in p_bmarks:
1183 old = remote_bmarks.get(bmark, '')
1184 if not peer.pushkey('bookmarks', bmark, old, new):
1185 print "error %s" % ref
1187 # update local bookmarks
1188 for ref, bmark, old, new in p_bmarks:
1189 if not bookmarks.pushbookmark(parser.repo, bmark, old, new):
1190 print "error %s" % ref
1194 def do_option(parser):
1195 global dry_run, force_push
1196 _, key, value = parser.line.split(' ')
1197 if key == 'dry-run':
1198 dry_run = (value == 'true')
1200 elif key == 'force':
1201 force_push = (value == 'true')
1206 def fix_path(alias, repo, orig_url):
1207 url = urlparse.urlparse(orig_url, 'file')
1208 if url.scheme != 'file' or os.path.isabs(os.path.expanduser(url.path)):
1210 abs_url = urlparse.urljoin("%s/" % os.getcwd(), orig_url)
1211 cmd = ['git', 'config', 'remote.%s.url' % alias, "hg::%s" % abs_url]
1212 subprocess.call(cmd)
1215 global prefix, gitdir, dirname, branches, bmarks
1216 global marks, blob_marks, parsed_refs
1217 global peer, mode, bad_mail, bad_name
1218 global track_branches, force_push, is_tmp
1221 global fake_bmark, hg_version
1227 gitdir = os.environ.get('GIT_DIR', None)
1230 die('Not enough arguments.')
1233 die('GIT_DIR not set')
1239 hg_git_compat = get_config_bool('remote-hg.hg-git-compat')
1240 track_branches = get_config_bool('remote-hg.track-branches', True)
1245 bad_mail = 'none@none'
1249 bad_mail = 'unknown'
1250 bad_name = 'Unknown'
1252 if alias[4:] == url:
1254 alias = hashlib.sha1(alias).hexdigest()
1256 dirname = os.path.join(gitdir, 'hg', alias)
1265 hg_version = tuple(int(e) for e in util.version().split('.'))
1271 repo = get_repo(url, alias)
1272 prefix = 'refs/hg/%s' % alias
1275 fix_path(alias, peer or repo, url)
1277 marks_path = os.path.join(dirname, 'marks-hg')
1278 marks = Marks(marks_path, repo)
1280 if sys.platform == 'win32':
1282 msvcrt.setmode(sys.stdout.fileno(), os.O_BINARY)
1284 parser = Parser(repo)
1286 if parser.check('capabilities'):
1287 do_capabilities(parser)
1288 elif parser.check('list'):
1290 elif parser.check('import'):
1292 elif parser.check('export'):
1294 elif parser.check('option'):
1297 die('unhandled command: %s' % line)
1304 shutil.rmtree(dirname)
1306 atexit.register(bye)
1307 sys.exit(main(sys.argv))