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
16 from mercurial import node, error, extensions, discovery, util
17 from mercurial import changegroup
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,
163 'last-mark': self.last_mark, 'version': self.version,
164 'last-note': self.last_note }
167 json.dump(self.dict(), open(self.path, 'w'))
170 return str(self.dict())
172 def from_rev(self, rev):
173 return self.marks[rev]
175 def to_rev(self, mark):
176 return str(self.rev_marks[mark])
180 return self.last_mark
182 def get_mark(self, rev):
184 self.marks[rev] = self.last_mark
185 return self.last_mark
187 def new_mark(self, rev, mark):
188 self.marks[rev] = mark
189 self.rev_marks[mark] = rev
190 self.last_mark = mark
192 def is_marked(self, rev):
193 return rev in self.marks
195 def get_tip(self, branch):
196 return str(self.tips[branch])
198 def set_tip(self, branch, tip):
199 self.tips[branch] = tip
203 def __init__(self, repo):
205 self.line = self.get_line()
208 return sys.stdin.readline().strip()
210 def __getitem__(self, i):
211 return self.line.split()[i]
213 def check(self, word):
214 return self.line.startswith(word)
216 def each_block(self, separator):
217 while self.line != separator:
219 self.line = self.get_line()
222 return self.each_block('')
225 self.line = self.get_line()
226 if self.line == 'done':
230 i = self.line.index(':') + 1
231 return int(self.line[i:])
234 if not self.check('data'):
236 i = self.line.index(' ') + 1
237 size = int(self.line[i:])
238 return sys.stdin.read(size)
240 def get_author(self):
242 m = RAW_AUTHOR_RE.match(self.line)
245 _, name, email, date, tz = m.groups()
246 if name and 'ext:' in name:
247 m = re.match('^(.+?) ext:\((.+)\)$', name)
250 ex = urllib.unquote(m.group(2))
252 if email != bad_mail:
254 user = '%s <%s>' % (name, email)
256 user = '<%s>' % (email)
264 tz = ((tz / 100) * 3600) + ((tz % 100) * 60)
265 return (user, int(date), -tz)
267 def fix_file_path(path):
268 path = os.path.normpath(path)
269 if not os.path.isabs(path):
271 return os.path.relpath(path, '/')
273 def export_files(files):
276 fid = node.hex(f.filenode())
279 mark = filenodes[fid]
281 mark = marks.next_mark()
282 filenodes[fid] = mark
286 print "mark :%u" % mark
287 print "data %d" % len(d)
290 path = fix_file_path(f.path())
291 final.append((gitmode(f.flags()), mark, path))
295 def get_filechanges(repo, ctx, parent):
300 # load earliest manifest first for caching reasons
301 prev = parent.manifest().copy()
306 if (cur.flags(fn) != prev.flags(fn) or cur[fn] != prev[fn]):
311 removed |= set(prev.keys())
313 return added | modified, removed
315 def fixup_user_git(user):
317 user = user.replace('"', '')
318 m = AUTHOR_RE.match(user)
321 mail = m.group(2).strip()
323 m = EMAIL_RE.match(user)
327 m = NAME_RE.match(user)
329 name = m.group(1).strip()
332 def fixup_user_hg(user):
334 # stole this from hg-git
335 return re.sub('[<>\n]', '?', name.lstrip('< ').rstrip('> '))
337 m = AUTHOR_HG_RE.match(user)
339 name = sanitize(m.group(1))
340 mail = sanitize(m.group(2))
343 name += ' ext:(' + urllib.quote(ex) + ')'
345 name = sanitize(user)
353 def fixup_user(user):
355 name, mail = fixup_user_git(user)
357 name, mail = fixup_user_hg(user)
364 return '%s <%s>' % (name, mail)
366 def updatebookmarks(repo, peer):
367 remotemarks = peer.listkeys('bookmarks')
368 localmarks = repo._bookmarks
373 for k, v in remotemarks.iteritems():
374 localmarks[k] = hgbin(v)
376 if hasattr(localmarks, 'write'):
379 bookmarks.write(repo)
381 def get_repo(url, alias):
385 myui.setconfig('ui', 'interactive', 'off')
386 myui.fout = sys.stderr
388 if get_config_bool('remote-hg.insecure'):
389 myui.setconfig('web', 'cacerts', '')
391 extensions.loadall(myui)
393 if hg.islocal(url) and not os.environ.get('GIT_REMOTE_HG_TEST_REMOTE'):
394 repo = hg.repository(myui, url)
395 if not os.path.exists(dirname):
398 shared_path = os.path.join(gitdir, 'hg')
400 # check and upgrade old organization
401 hg_path = os.path.join(shared_path, '.hg')
402 if os.path.exists(shared_path) and not os.path.exists(hg_path):
403 repos = os.listdir(shared_path)
405 local_hg = os.path.join(shared_path, x, 'clone', '.hg')
406 if not os.path.exists(local_hg):
408 if not os.path.exists(hg_path):
409 shutil.move(local_hg, hg_path)
410 shutil.rmtree(os.path.join(shared_path, x, 'clone'))
412 # setup shared repo (if not there)
414 hg.peer(myui, {}, shared_path, create=True)
415 except error.RepoError:
418 if not os.path.exists(dirname):
421 local_path = os.path.join(dirname, 'clone')
422 if not os.path.exists(local_path):
423 hg.share(myui, shared_path, local_path, update=False)
425 # make sure the shared path is always up-to-date
426 util.writefile(os.path.join(local_path, '.hg', 'sharedpath'), hg_path)
428 repo = hg.repository(myui, local_path)
430 peer = hg.peer(repo.ui, {}, url)
432 die('Repository error')
433 repo.pull(peer, heads=None, force=True)
435 updatebookmarks(repo, peer)
439 def rev_to_mark(rev):
440 return marks.from_rev(rev.hex())
442 def mark_to_rev(mark):
443 return marks.to_rev(mark)
445 # Get a range of revisions in the form of a..b (git committish)
446 def gitrange(repo, a, b):
448 pending = set([int(b)])
449 negative = set([int(a)])
450 for cur in xrange(b, -1, -1):
454 parents = [p for p in repo.changelog.parentrevs(cur) if p >= 0]
460 if p not in negative:
462 elif cur in negative:
473 def export_ref(repo, name, kind, head):
474 ename = '%s/%s' % (kind, name)
476 tip = marks.get_tip(ename)
481 revs = gitrange(repo, tip, head)
491 if marks.is_marked(c.hex()):
494 (manifest, user, (time, tz), files, desc, extra) = repo.changelog.read(node)
495 rev_branch = extra['branch']
497 author = "%s %d %s" % (fixup_user(user), time, gittz(tz))
498 if 'committer' in extra:
500 cuser, ctime, ctz = extra['committer'].rsplit(' ', 2)
501 committer = "%s %s %s" % (cuser, ctime, gittz(int(ctz)))
503 cuser = extra['committer']
504 committer = "%s %d %s" % (fixup_user(cuser), time, gittz(tz))
508 parents = [repo[p] for p in repo.changelog.parentrevs(rev) if p >= 0]
510 if len(parents) == 0:
511 modified = c.manifest().keys()
514 modified, removed = get_filechanges(repo, c, parents[0])
521 if rev_branch != 'default':
522 extra_msg += 'branch : %s\n' % rev_branch
526 if f not in c.manifest():
528 rename = c.filectx(f).renamed()
530 renames.append((rename[0], f))
533 extra_msg += "rename : %s => %s\n" % e
535 for key, value in extra.iteritems():
536 if key in ('author', 'committer', 'encoding', 'message', 'branch', 'hg-git'):
539 extra_msg += "extra : %s : %s\n" % (key, urllib.quote(value))
542 desc += '\n--HG--\n' + extra_msg
544 if len(parents) == 0 and rev:
545 print 'reset %s/%s' % (prefix, ename)
547 modified_final = export_files(c.filectx(f) for f in modified)
549 print "commit %s/%s" % (prefix, ename)
550 print "mark :%d" % (marks.get_mark(c.hex()))
551 print "author %s" % (author)
552 print "committer %s" % (committer)
553 print "data %d" % (len(desc))
557 print "from :%s" % (rev_to_mark(parents[0]))
559 print "merge :%s" % (rev_to_mark(parents[1]))
562 print "D %s" % (fix_file_path(f))
563 for f in modified_final:
564 print "M %s :%u %s" % f
567 progress = (rev - tip)
568 if (progress % 100 == 0):
569 print "progress revision %d '%s' (%d/%d)" % (rev, name, progress, total)
571 # make sure the ref is updated
572 print "reset %s/%s" % (prefix, ename)
573 print "from :%u" % rev_to_mark(head)
576 pending_revs = set(revs) - notes
578 note_mark = marks.next_mark()
579 ref = "refs/notes/hg"
581 print "commit %s" % ref
582 print "mark :%d" % (note_mark)
583 print "committer remote-hg <> %d %s" % (ptime.time(), gittz(ptime.timezone))
584 desc = "Notes for %s\n" % (name)
585 print "data %d" % (len(desc))
588 print "from :%u" % marks.last_note
590 for rev in pending_revs:
593 print "N inline :%u" % rev_to_mark(c)
595 print "data %d" % (len(msg))
599 marks.last_note = note_mark
601 marks.set_tip(ename, head.hex())
603 def export_tag(repo, tag):
604 export_ref(repo, tag, 'tags', repo[hgref(tag)])
606 def export_bookmark(repo, bmark):
607 head = bmarks[hgref(bmark)]
608 export_ref(repo, bmark, 'bookmarks', head)
610 def export_branch(repo, branch):
611 tip = get_branch_tip(repo, branch)
613 export_ref(repo, branch, 'branches', head)
615 def export_head(repo):
616 export_ref(repo, g_head[0], 'bookmarks', g_head[1])
618 def do_capabilities(parser):
621 print "refspec refs/heads/branches/*:%s/branches/*" % prefix
622 print "refspec refs/heads/*:%s/bookmarks/*" % prefix
623 print "refspec refs/tags/*:%s/tags/*" % prefix
625 path = os.path.join(dirname, 'marks-git')
627 if os.path.exists(path):
628 print "*import-marks %s" % path
629 print "*export-marks %s" % path
634 def branch_tip(branch):
635 return branches[branch][-1]
637 def get_branch_tip(repo, branch):
638 heads = branches.get(hgref(branch), None)
642 # verify there's only one head
644 warn("Branch '%s' has more than one head, consider merging" % branch)
645 return branch_tip(hgref(branch))
649 def list_head(repo, cur):
650 global g_head, fake_bmark
652 if 'default' not in branches:
656 node = repo[branch_tip('default')]
657 head = 'master' if 'master' not in bmarks else 'default'
662 print "@refs/heads/%s HEAD" % head
663 g_head = (head, node)
667 for bmark, node in bookmarks.listbookmarks(repo).iteritems():
668 bmarks[bmark] = repo[node]
670 cur = repo.dirstate.branch()
671 orig = peer if peer else repo
673 for branch, heads in orig.branchmap().iteritems():
675 heads = [h for h in heads if 'close' not in repo.changelog.read(h)[5]]
677 branches[branch] = heads
682 for branch in branches:
683 print "? refs/heads/branches/%s" % gitref(branch)
686 if bmarks[bmark].hex() == '0' * 40:
687 warn("Ignoring invalid bookmark '%s'", bmark)
689 print "? refs/heads/%s" % gitref(bmark)
691 for tag, node in repo.tagslist():
694 print "? refs/tags/%s" % gitref(tag)
698 def do_import(parser):
701 path = os.path.join(dirname, 'marks-git')
704 if os.path.exists(path):
705 print "feature import-marks=%s" % path
706 print "feature export-marks=%s" % path
707 print "feature force"
710 tmp = encoding.encoding
711 encoding.encoding = 'utf-8'
713 # lets get all the import lines
714 while parser.check('import'):
719 elif ref.startswith('refs/heads/branches/'):
720 branch = ref[len('refs/heads/branches/'):]
721 export_branch(repo, branch)
722 elif ref.startswith('refs/heads/'):
723 bmark = ref[len('refs/heads/'):]
724 export_bookmark(repo, bmark)
725 elif ref.startswith('refs/tags/'):
726 tag = ref[len('refs/tags/'):]
727 export_tag(repo, tag)
731 encoding.encoding = tmp
735 def parse_blob(parser):
737 mark = parser.get_mark()
739 data = parser.get_data()
740 blob_marks[mark] = data
743 def get_merge_files(repo, p1, p2, files):
744 for e in repo[p1].files():
746 if e not in repo[p1].manifest():
748 f = { 'ctx': repo[p1][e] }
751 def c_style_unescape(string):
752 if string[0] == string[-1] == '"':
753 return string.decode('string-escape')[1:-1]
756 def parse_commit(parser):
757 from_mark = merge_mark = None
762 commit_mark = parser.get_mark()
764 author = parser.get_author()
766 committer = parser.get_author()
768 data = parser.get_data()
770 if parser.check('from'):
771 from_mark = parser.get_mark()
773 if parser.check('merge'):
774 merge_mark = parser.get_mark()
776 if parser.check('merge'):
777 die('octopus merges are not supported yet')
779 # fast-export adds an extra newline
786 if parser.check('M'):
787 t, m, mark_ref, path = line.split(' ', 3)
788 mark = int(mark_ref[1:])
789 f = { 'mode': hgmode(m), 'data': blob_marks[mark] }
790 elif parser.check('D'):
791 t, path = line.split(' ', 1)
792 f = { 'deleted': True }
794 die('Unknown file command: %s' % line)
795 path = c_style_unescape(path)
798 # only export the commits if we are on an internal proxy repo
799 if dry_run and not peer:
800 parsed_refs[ref] = None
803 def getfilectx(repo, memctx, f):
809 is_exec = of['mode'] == 'x'
810 is_link = of['mode'] == 'l'
811 rename = of.get('rename', None)
812 return context.memfilectx(f, of['data'],
813 is_link, is_exec, rename)
817 user, date, tz = author
820 if committer != author:
821 extra['committer'] = "%s %u %u" % committer
824 p1 = mark_to_rev(from_mark)
829 p2 = mark_to_rev(merge_mark)
834 # If files changed from any of the parents, hg wants to know, but in git if
835 # nothing changed from the first parent, nothing changed.
838 get_merge_files(repo, p1, p2, files)
840 # Check if the ref is supposed to be a named branch
841 if ref.startswith('refs/heads/branches/'):
842 branch = ref[len('refs/heads/branches/'):]
843 extra['branch'] = hgref(branch)
846 i = data.find('\n--HG--\n')
848 tmp = data[i + len('\n--HG--\n'):].strip()
849 for k, v in [e.split(' : ', 1) for e in tmp.split('\n')]:
851 old, new = v.split(' => ', 1)
852 files[new]['rename'] = old
856 ek, ev = v.split(' : ', 1)
857 extra[ek] = urllib.unquote(ev)
860 ctx = context.memctx(repo, (p1, p2), data,
861 files.keys(), getfilectx,
862 user, (date, tz), extra)
864 tmp = encoding.encoding
865 encoding.encoding = 'utf-8'
867 node = hghex(repo.commitctx(ctx))
869 encoding.encoding = tmp
871 parsed_refs[ref] = node
872 marks.new_mark(node, commit_mark)
874 def parse_reset(parser):
878 if parser.check('commit'):
881 if not parser.check('from'):
883 from_mark = parser.get_mark()
887 rev = mark_to_rev(from_mark)
890 parsed_refs[ref] = rev
892 def parse_tag(parser):
895 from_mark = parser.get_mark()
897 tagger = parser.get_author()
899 data = parser.get_data()
902 parsed_tags[name] = (tagger, data)
904 def write_tag(repo, tag, node, msg, author):
905 branch = repo[node].branch()
906 tip = branch_tip(branch)
909 def getfilectx(repo, memctx, f):
911 fctx = tip.filectx(f)
913 except error.ManifestLookupError:
915 content = data + "%s %s\n" % (node, tag)
916 return context.memfilectx(f, content, False, False, None)
921 user, date, tz = author
924 cmd = ['git', 'var', 'GIT_COMMITTER_IDENT']
925 process = subprocess.Popen(cmd, stdout=subprocess.PIPE)
926 output, _ = process.communicate()
927 m = re.match('^.* <.*>', output)
931 user = repo.ui.username()
934 ctx = context.memctx(repo, (p1, p2), msg,
935 ['.hgtags'], getfilectx,
936 user, date_tz, {'branch': branch})
938 tmp = encoding.encoding
939 encoding.encoding = 'utf-8'
941 tagnode = repo.commitctx(ctx)
943 encoding.encoding = tmp
945 return (tagnode, branch)
947 def checkheads_bmark(repo, ref, ctx):
948 bmark = ref[len('refs/heads/'):]
949 if bmark not in bmarks:
953 ctx_old = bmarks[bmark]
957 print "error %s unknown" % ref
960 if not repo.changelog.descendant(ctx_old.rev(), ctx_new.rev()):
962 print "ok %s forced update" % ref
964 print "error %s non-fast forward" % ref
969 def checkheads(repo, remote, p_revs):
971 remotemap = remote.branchmap()
979 for node, ref in p_revs.iteritems():
981 branch = ctx.branch()
982 if branch not in remotemap:
985 if not ref.startswith('refs/heads/branches'):
986 if ref.startswith('refs/heads/'):
987 if not checkheads_bmark(repo, ref, ctx):
990 # only check branches
992 new.setdefault(branch, []).append(ctx.rev())
994 for branch, heads in new.iteritems():
995 old = [repo.changelog.rev(x) for x in remotemap[branch]]
997 if check_version(2, 3):
998 ancestors = repo.changelog.ancestors([rev], stoprev=min(old))
1000 ancestors = repo.changelog.ancestors(rev)
1011 node = repo.changelog.node(rev)
1014 print "ok %s forced update" % ref
1016 print "error %s non-fast forward" % ref
1021 def push_unsafe(repo, remote, parsed_refs, p_revs):
1025 fci = discovery.findcommonincoming
1026 commoninc = fci(repo, remote, force=force)
1027 common, _, remoteheads = commoninc
1029 if not checkheads(repo, remote, p_revs):
1032 if check_version(3, 0):
1033 cg = changegroup.getbundle(repo, 'push', heads=list(p_revs), common=common)
1035 cg = repo.getbundle('push', heads=list(p_revs), common=common)
1037 unbundle = remote.capable('unbundle')
1040 remoteheads = ['force']
1041 ret = remote.unbundle(cg, remoteheads, 'push')
1043 ret = remote.addchangegroup(cg, 'push', repo.url())
1045 phases = remote.listkeys('phases')
1049 remote.pushkey('phases', hghex(head), '1', '0')
1053 def push(repo, remote, parsed_refs, p_revs):
1054 if hasattr(remote, 'canpush') and not remote.canpush():
1055 print "error cannot push"
1062 unbundle = remote.capable('unbundle')
1064 lock = remote.lock()
1066 ret = push_unsafe(repo, remote, parsed_refs, p_revs)
1068 if lock is not None:
1073 def check_tip(ref, kind, name, heads):
1075 ename = '%s/%s' % (kind, name)
1076 tip = marks.get_tip(ename)
1082 def do_export(parser):
1088 for line in parser.each_block('done'):
1089 if parser.check('blob'):
1091 elif parser.check('commit'):
1092 parse_commit(parser)
1093 elif parser.check('reset'):
1095 elif parser.check('tag'):
1097 elif parser.check('feature'):
1100 die('unhandled export command: %s' % line)
1104 for ref, node in parsed_refs.iteritems():
1105 bnode = hgbin(node) if node else None
1106 if ref.startswith('refs/heads/branches'):
1107 branch = ref[len('refs/heads/branches/'):]
1108 if branch in branches and bnode in branches[branch]:
1113 remotemap = peer.branchmap()
1114 if remotemap and branch in remotemap:
1115 heads = [hghex(e) for e in remotemap[branch]]
1116 if not check_tip(ref, 'branches', branch, heads):
1117 print "error %s fetch first" % ref
1123 elif ref.startswith('refs/heads/'):
1124 bmark = ref[len('refs/heads/'):]
1126 old = bmarks[bmark].hex() if bmark in bmarks else ''
1132 if bmark != fake_bmark and \
1133 not (bmark == 'master' and bmark not in parser.repo._bookmarks):
1134 p_bmarks.append((ref, bmark, old, new))
1137 remote_old = peer.listkeys('bookmarks').get(bmark)
1139 if not check_tip(ref, 'bookmarks', bmark, remote_old):
1140 print "error %s fetch first" % ref
1145 elif ref.startswith('refs/tags/'):
1149 tag = ref[len('refs/tags/'):]
1151 author, msg = parsed_tags.get(tag, (None, None))
1154 msg = 'Added tag %s for changeset %s' % (tag, node[:12])
1155 tagnode, branch = write_tag(parser.repo, tag, node, msg, author)
1156 p_revs[tagnode] = 'refs/heads/branches/' + gitref(branch)
1158 fp = parser.repo.opener('localtags', 'a')
1159 fp.write('%s %s\n' % (node, tag))
1164 # transport-helper/fast-export bugs
1172 if peer and not force_push:
1173 checkheads(parser.repo, peer, p_revs)
1178 if not push(parser.repo, peer, parsed_refs, p_revs):
1179 # do not update bookmarks
1183 # update remote bookmarks
1184 remote_bmarks = peer.listkeys('bookmarks')
1185 for ref, bmark, old, new in p_bmarks:
1187 old = remote_bmarks.get(bmark, '')
1188 if not peer.pushkey('bookmarks', bmark, old, new):
1189 print "error %s" % ref
1191 # update local bookmarks
1192 for ref, bmark, old, new in p_bmarks:
1193 if not bookmarks.pushbookmark(parser.repo, bmark, old, new):
1194 print "error %s" % ref
1198 def do_option(parser):
1199 global dry_run, force_push
1200 _, key, value = parser.line.split(' ')
1201 if key == 'dry-run':
1202 dry_run = (value == 'true')
1204 elif key == 'force':
1205 force_push = (value == 'true')
1210 def fix_path(alias, repo, orig_url):
1211 url = urlparse.urlparse(orig_url, 'file')
1212 if url.scheme != 'file' or os.path.isabs(os.path.expanduser(url.path)):
1214 abs_url = urlparse.urljoin("%s/" % os.getcwd(), orig_url)
1215 cmd = ['git', 'config', 'remote.%s.url' % alias, "hg::%s" % abs_url]
1216 subprocess.call(cmd)
1219 global prefix, gitdir, dirname, branches, bmarks
1220 global marks, blob_marks, parsed_refs
1221 global peer, mode, bad_mail, bad_name
1222 global track_branches, force_push, is_tmp
1225 global fake_bmark, hg_version
1231 gitdir = os.environ.get('GIT_DIR', None)
1234 die('Not enough arguments.')
1237 die('GIT_DIR not set')
1243 hg_git_compat = get_config_bool('remote-hg.hg-git-compat')
1244 track_branches = get_config_bool('remote-hg.track-branches', True)
1249 bad_mail = 'none@none'
1253 bad_mail = 'unknown'
1254 bad_name = 'Unknown'
1256 if alias[4:] == url:
1258 alias = hashlib.sha1(alias).hexdigest()
1260 dirname = os.path.join(gitdir, 'hg', alias)
1269 hg_version = tuple(int(e) for e in util.version().split('.'))
1275 repo = get_repo(url, alias)
1276 prefix = 'refs/hg/%s' % alias
1279 fix_path(alias, peer or repo, url)
1281 marks_path = os.path.join(dirname, 'marks-hg')
1282 marks = Marks(marks_path, repo)
1284 if sys.platform == 'win32':
1286 msvcrt.setmode(sys.stdout.fileno(), os.O_BINARY)
1288 parser = Parser(repo)
1290 if parser.check('capabilities'):
1291 do_capabilities(parser)
1292 elif parser.check('list'):
1294 elif parser.check('import'):
1296 elif parser.check('export'):
1298 elif parser.check('option'):
1301 die('unhandled command: %s' % line)
1308 shutil.rmtree(dirname)
1310 atexit.register(bye)
1311 sys.exit(main(sys.argv))