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 check_version(3, 6):
380 tr = repo.transaction('bookmark')
381 localmarks.recordchange(tr)
389 if hasattr(localmarks, 'write'):
392 bookmarks.write(repo)
394 def get_repo(url, alias):
398 myui.setconfig('ui', 'interactive', 'off')
399 myui.fout = sys.stderr
401 if get_config_bool('remote-hg.insecure'):
402 myui.setconfig('web', 'cacerts', '')
404 extensions.loadall(myui)
406 if hg.islocal(url) and not os.environ.get('GIT_REMOTE_HG_TEST_REMOTE'):
407 repo = hg.repository(myui, url)
408 if not os.path.exists(dirname):
411 shared_path = os.path.join(gitdir, 'hg')
413 # check and upgrade old organization
414 hg_path = os.path.join(shared_path, '.hg')
415 if os.path.exists(shared_path) and not os.path.exists(hg_path):
416 repos = os.listdir(shared_path)
418 local_hg = os.path.join(shared_path, x, 'clone', '.hg')
419 if not os.path.exists(local_hg):
421 if not os.path.exists(hg_path):
422 shutil.move(local_hg, hg_path)
423 shutil.rmtree(os.path.join(shared_path, x, 'clone'))
425 # setup shared repo (if not there)
427 hg.peer(myui, {}, shared_path, create=True)
428 except error.RepoError:
431 if not os.path.exists(dirname):
434 local_path = os.path.join(dirname, 'clone')
435 if not os.path.exists(local_path):
436 hg.share(myui, shared_path, local_path, update=False)
438 # make sure the shared path is always up-to-date
439 util.writefile(os.path.join(local_path, '.hg', 'sharedpath'), hg_path)
441 repo = hg.repository(myui, local_path)
443 peer = hg.peer(repo.ui, {}, url)
445 die('Repository error')
447 if check_version(3, 0):
448 from mercurial import exchange
449 exchange.pull(repo, peer, heads=None, force=True)
451 repo.pull(peer, heads=None, force=True)
453 updatebookmarks(repo, peer)
457 def rev_to_mark(rev):
458 return marks.from_rev(rev.hex())
460 def mark_to_rev(mark):
461 return marks.to_rev(mark)
463 # Get a range of revisions in the form of a..b (git committish)
464 def gitrange(repo, a, b):
466 pending = set([int(b)])
467 negative = set([int(a)])
468 for cur in xrange(b, -1, -1):
472 parents = [p for p in repo.changelog.parentrevs(cur) if p >= 0]
478 if p not in negative:
480 elif cur in negative:
491 def export_ref(repo, name, kind, head):
492 ename = '%s/%s' % (kind, name)
494 tip = marks.get_tip(ename)
499 revs = gitrange(repo, tip, head)
509 if marks.is_marked(c.hex()):
512 (manifest, user, (time, tz), files, desc, extra) = repo.changelog.read(node)
513 rev_branch = extra['branch']
515 author = "%s %d %s" % (fixup_user(user), time, gittz(tz))
516 if 'committer' in extra:
518 cuser, ctime, ctz = extra['committer'].rsplit(' ', 2)
519 committer = "%s %s %s" % (fixup_user(cuser), ctime, gittz(int(ctz)))
521 cuser = extra['committer']
522 committer = "%s %d %s" % (fixup_user(cuser), time, gittz(tz))
526 parents = [repo[p] for p in repo.changelog.parentrevs(rev) if p >= 0]
528 if len(parents) == 0:
529 modified = c.manifest().keys()
532 modified, removed = get_filechanges(repo, c, parents[0])
539 if rev_branch != 'default':
540 extra_msg += 'branch : %s\n' % rev_branch
544 if f not in c.manifest():
546 rename = c.filectx(f).renamed()
548 renames.append((rename[0], f))
551 extra_msg += "rename : %s => %s\n" % e
553 for key, value in extra.iteritems():
554 if key in ('author', 'committer', 'encoding', 'message', 'branch', 'hg-git'):
557 extra_msg += "extra : %s : %s\n" % (key, urllib.quote(value))
560 desc += '\n--HG--\n' + extra_msg
562 if len(parents) == 0 and rev:
563 print 'reset %s/%s' % (prefix, ename)
565 modified_final = export_files(c.filectx(f) for f in modified)
567 print "commit %s/%s" % (prefix, ename)
568 print "mark :%d" % (marks.get_mark(c.hex()))
569 print "author %s" % (author)
570 print "committer %s" % (committer)
571 print "data %d" % (len(desc))
575 print "from :%s" % (rev_to_mark(parents[0]))
577 print "merge :%s" % (rev_to_mark(parents[1]))
580 print "D %s" % (fix_file_path(f))
581 for f in modified_final:
582 print "M %s :%u %s" % f
585 progress = (rev - tip)
586 if (progress % 100 == 0):
587 print "progress revision %d '%s' (%d/%d)" % (rev, name, progress, total)
589 # make sure the ref is updated
590 print "reset %s/%s" % (prefix, ename)
591 print "from :%u" % rev_to_mark(head)
594 pending_revs = set(revs) - notes
596 note_mark = marks.next_mark()
597 ref = "refs/notes/hg"
599 print "commit %s" % ref
600 print "mark :%d" % (note_mark)
601 print "committer remote-hg <> %d %s" % (ptime.time(), gittz(ptime.timezone))
602 desc = "Notes for %s\n" % (name)
603 print "data %d" % (len(desc))
606 print "from :%u" % marks.last_note
608 for rev in pending_revs:
611 print "N inline :%u" % rev_to_mark(c)
613 print "data %d" % (len(msg))
617 marks.last_note = note_mark
619 marks.set_tip(ename, head.hex())
621 def export_tag(repo, tag):
622 export_ref(repo, tag, 'tags', repo[hgref(tag)])
624 def export_bookmark(repo, bmark):
625 head = bmarks[hgref(bmark)]
626 export_ref(repo, bmark, 'bookmarks', head)
628 def export_branch(repo, branch):
629 tip = get_branch_tip(repo, branch)
631 export_ref(repo, branch, 'branches', head)
633 def export_head(repo):
634 export_ref(repo, g_head[0], 'bookmarks', g_head[1])
636 def do_capabilities(parser):
639 print "refspec refs/heads/branches/*:%s/branches/*" % prefix
640 print "refspec refs/heads/*:%s/bookmarks/*" % prefix
641 print "refspec refs/tags/*:%s/tags/*" % prefix
643 path = os.path.join(dirname, 'marks-git')
645 if os.path.exists(path):
646 print "*import-marks %s" % path
647 print "*export-marks %s" % path
652 def branch_tip(branch):
653 return branches[branch][-1]
655 def get_branch_tip(repo, branch):
656 heads = branches.get(hgref(branch), None)
660 # verify there's only one head
662 warn("Branch '%s' has more than one head, consider merging" % branch)
663 return branch_tip(hgref(branch))
667 def list_head(repo, cur):
668 global g_head, fake_bmark
670 if 'default' not in branches:
674 node = repo[branch_tip('default')]
675 head = 'master' if 'master' not in bmarks else 'default'
680 print "@refs/heads/%s HEAD" % head
681 g_head = (head, node)
685 for bmark, node in bookmarks.listbookmarks(repo).iteritems():
686 bmarks[bmark] = repo[node]
688 cur = repo.dirstate.branch()
689 orig = peer if peer else repo
691 for branch, heads in orig.branchmap().iteritems():
693 heads = [h for h in heads if 'close' not in repo.changelog.read(h)[5]]
695 branches[branch] = heads
700 for branch in branches:
701 print "? refs/heads/branches/%s" % gitref(branch)
704 if bmarks[bmark].hex() == '0' * 40:
705 warn("Ignoring invalid bookmark '%s'", bmark)
707 print "? refs/heads/%s" % gitref(bmark)
709 for tag, node in repo.tagslist():
712 print "? refs/tags/%s" % gitref(tag)
716 def do_import(parser):
719 path = os.path.join(dirname, 'marks-git')
722 if os.path.exists(path):
723 print "feature import-marks=%s" % path
724 print "feature export-marks=%s" % path
725 print "feature force"
728 tmp = encoding.encoding
729 encoding.encoding = 'utf-8'
731 # lets get all the import lines
732 while parser.check('import'):
737 elif ref.startswith('refs/heads/branches/'):
738 branch = ref[len('refs/heads/branches/'):]
739 export_branch(repo, branch)
740 elif ref.startswith('refs/heads/'):
741 bmark = ref[len('refs/heads/'):]
742 export_bookmark(repo, bmark)
743 elif ref.startswith('refs/tags/'):
744 tag = ref[len('refs/tags/'):]
745 export_tag(repo, tag)
749 encoding.encoding = tmp
753 def parse_blob(parser):
755 mark = parser.get_mark()
757 data = parser.get_data()
758 blob_marks[mark] = data
761 def get_merge_files(repo, p1, p2, files):
762 for e in repo[p1].files():
764 if e not in repo[p1].manifest():
766 f = { 'ctx': repo[p1][e] }
769 def c_style_unescape(string):
770 if string[0] == string[-1] == '"':
771 return string.decode('string-escape')[1:-1]
774 def parse_commit(parser):
775 from_mark = merge_mark = None
780 commit_mark = parser.get_mark()
782 author = parser.get_author()
784 committer = parser.get_author()
786 data = parser.get_data()
788 if parser.check('from'):
789 from_mark = parser.get_mark()
791 if parser.check('merge'):
792 merge_mark = parser.get_mark()
794 if parser.check('merge'):
795 die('octopus merges are not supported yet')
797 # fast-export adds an extra newline
804 if parser.check('M'):
805 t, m, mark_ref, path = line.split(' ', 3)
806 mark = int(mark_ref[1:])
807 f = { 'mode': hgmode(m), 'data': blob_marks[mark] }
808 elif parser.check('D'):
809 t, path = line.split(' ', 1)
810 f = { 'deleted': True }
812 die('Unknown file command: %s' % line)
813 path = c_style_unescape(path)
816 # only export the commits if we are on an internal proxy repo
817 if dry_run and not peer:
818 parsed_refs[ref] = None
821 def getfilectx(repo, memctx, f):
824 if check_version(3, 2):
831 is_exec = ctx.isexec()
832 is_link = ctx.islink()
833 if check_version(3, 1):
834 return context.memfilectx(repo, f, ctx.data(),
837 return context.memfilectx(f, ctx.data(),
841 is_exec = of['mode'] == 'x'
842 is_link = of['mode'] == 'l'
843 rename = of.get('rename', None)
844 if check_version(3, 1):
845 return context.memfilectx(repo, f, of['data'],
846 is_link, is_exec, rename)
848 return context.memfilectx(f, of['data'],
849 is_link, is_exec, rename)
853 user, date, tz = author
856 if committer != author:
857 extra['committer'] = "%s %u %u" % committer
860 p1 = mark_to_rev(from_mark)
865 p2 = mark_to_rev(merge_mark)
870 # If files changed from any of the parents, hg wants to know, but in git if
871 # nothing changed from the first parent, nothing changed.
874 get_merge_files(repo, p1, p2, files)
876 # Check if the ref is supposed to be a named branch
877 if ref.startswith('refs/heads/branches/'):
878 branch = ref[len('refs/heads/branches/'):]
879 extra['branch'] = hgref(branch)
882 i = data.find('\n--HG--\n')
884 tmp = data[i + len('\n--HG--\n'):].strip()
885 for k, v in [e.split(' : ', 1) for e in tmp.split('\n')]:
887 old, new = v.split(' => ', 1)
888 files[new]['rename'] = old
892 ek, ev = v.split(' : ', 1)
893 extra[ek] = urllib.unquote(ev)
896 ctx = context.memctx(repo, (p1, p2), data,
897 files.keys(), getfilectx,
898 user, (date, tz), extra)
900 tmp = encoding.encoding
901 encoding.encoding = 'utf-8'
903 node = hghex(repo.commitctx(ctx))
905 encoding.encoding = tmp
907 parsed_refs[ref] = node
908 marks.new_mark(node, commit_mark)
910 def parse_reset(parser):
914 if parser.check('commit'):
917 if not parser.check('from'):
919 from_mark = parser.get_mark()
923 rev = mark_to_rev(from_mark)
926 parsed_refs[ref] = rev
928 def parse_tag(parser):
931 from_mark = parser.get_mark()
933 tagger = parser.get_author()
935 data = parser.get_data()
938 parsed_tags[name] = (tagger, data)
940 def write_tag(repo, tag, node, msg, author):
941 branch = repo[node].branch()
942 tip = branch_tip(branch)
945 def getfilectx(repo, memctx, f):
947 fctx = tip.filectx(f)
949 except error.ManifestLookupError:
951 content = data + "%s %s\n" % (node, tag)
952 if check_version(3, 1):
953 return context.memfilectx(repo, f, content, False, False, None)
955 return context.memfilectx(f, content, False, False, None)
960 user, date, tz = author
963 cmd = ['git', 'var', 'GIT_COMMITTER_IDENT']
964 process = subprocess.Popen(cmd, stdout=subprocess.PIPE)
965 output, _ = process.communicate()
966 m = re.match('^.* <.*>', output)
970 user = repo.ui.username()
973 ctx = context.memctx(repo, (p1, p2), msg,
974 ['.hgtags'], getfilectx,
975 user, date_tz, {'branch': branch})
977 tmp = encoding.encoding
978 encoding.encoding = 'utf-8'
980 tagnode = repo.commitctx(ctx)
982 encoding.encoding = tmp
984 return (tagnode, branch)
986 def checkheads_bmark(repo, ref, ctx):
987 bmark = ref[len('refs/heads/'):]
988 if bmark not in bmarks:
992 ctx_old = bmarks[bmark]
996 print "error %s unknown" % ref
999 if not repo.changelog.descendant(ctx_old.rev(), ctx_new.rev()):
1001 print "ok %s forced update" % ref
1003 print "error %s non-fast forward" % ref
1008 def checkheads(repo, remote, p_revs):
1010 remotemap = remote.branchmap()
1018 for node, ref in p_revs.iteritems():
1020 branch = ctx.branch()
1021 if branch not in remotemap:
1024 if not ref.startswith('refs/heads/branches'):
1025 if ref.startswith('refs/heads/'):
1026 if not checkheads_bmark(repo, ref, ctx):
1029 # only check branches
1031 new.setdefault(branch, []).append(ctx.rev())
1033 for branch, heads in new.iteritems():
1034 old = [repo.changelog.rev(x) for x in remotemap[branch]]
1036 if check_version(2, 3):
1037 ancestors = repo.changelog.ancestors([rev], stoprev=min(old))
1039 ancestors = repo.changelog.ancestors(rev)
1050 node = repo.changelog.node(rev)
1053 print "ok %s forced update" % ref
1055 print "error %s non-fast forward" % ref
1060 def push_unsafe(repo, remote, parsed_refs, p_revs):
1064 fci = discovery.findcommonincoming
1065 commoninc = fci(repo, remote, force=force)
1066 common, _, remoteheads = commoninc
1068 if not checkheads(repo, remote, p_revs):
1071 if check_version(3, 2):
1072 cg = changegroup.getchangegroup(repo, 'push', heads=list(p_revs), common=common)
1073 elif check_version(3, 0):
1074 cg = changegroup.getbundle(repo, 'push', heads=list(p_revs), common=common)
1076 cg = repo.getbundle('push', heads=list(p_revs), common=common)
1078 unbundle = remote.capable('unbundle')
1081 remoteheads = ['force']
1082 ret = remote.unbundle(cg, remoteheads, 'push')
1084 ret = remote.addchangegroup(cg, 'push', repo.url())
1086 phases = remote.listkeys('phases')
1090 remote.pushkey('phases', hghex(head), '1', '0')
1094 def push(repo, remote, parsed_refs, p_revs):
1095 if hasattr(remote, 'canpush') and not remote.canpush():
1096 print "error cannot push"
1103 unbundle = remote.capable('unbundle')
1105 lock = remote.lock()
1107 ret = push_unsafe(repo, remote, parsed_refs, p_revs)
1109 if lock is not None:
1114 def check_tip(ref, kind, name, heads):
1116 ename = '%s/%s' % (kind, name)
1117 tip = marks.get_tip(ename)
1123 def do_export(parser):
1129 for line in parser.each_block('done'):
1130 if parser.check('blob'):
1132 elif parser.check('commit'):
1133 parse_commit(parser)
1134 elif parser.check('reset'):
1136 elif parser.check('tag'):
1138 elif parser.check('feature'):
1141 die('unhandled export command: %s' % line)
1145 for ref, node in parsed_refs.iteritems():
1146 bnode = hgbin(node) if node else None
1147 if ref.startswith('refs/heads/branches'):
1148 branch = ref[len('refs/heads/branches/'):]
1149 if branch in branches and bnode in branches[branch]:
1154 remotemap = peer.branchmap()
1155 if remotemap and branch in remotemap:
1156 heads = [hghex(e) for e in remotemap[branch]]
1157 if not check_tip(ref, 'branches', branch, heads):
1158 print "error %s fetch first" % ref
1164 elif ref.startswith('refs/heads/'):
1165 bmark = ref[len('refs/heads/'):]
1167 old = bmarks[bmark].hex() if bmark in bmarks else ''
1173 if bmark != fake_bmark and \
1174 not (bmark == 'master' and bmark not in parser.repo._bookmarks):
1175 p_bmarks.append((ref, bmark, old, new))
1178 remote_old = peer.listkeys('bookmarks').get(bmark)
1180 if not check_tip(ref, 'bookmarks', bmark, remote_old):
1181 print "error %s fetch first" % ref
1186 elif ref.startswith('refs/tags/'):
1190 tag = ref[len('refs/tags/'):]
1192 author, msg = parsed_tags.get(tag, (None, None))
1195 msg = 'Added tag %s for changeset %s' % (tag, node[:12])
1196 tagnode, branch = write_tag(parser.repo, tag, node, msg, author)
1197 p_revs[tagnode] = 'refs/heads/branches/' + gitref(branch)
1199 fp = parser.repo.opener('localtags', 'a')
1200 fp.write('%s %s\n' % (node, tag))
1205 # transport-helper/fast-export bugs
1213 if peer and not force_push:
1214 checkheads(parser.repo, peer, p_revs)
1219 if not push(parser.repo, peer, parsed_refs, p_revs):
1220 # do not update bookmarks
1224 # update remote bookmarks
1225 remote_bmarks = peer.listkeys('bookmarks')
1226 for ref, bmark, old, new in p_bmarks:
1228 old = remote_bmarks.get(bmark, '')
1229 if not peer.pushkey('bookmarks', bmark, old, new):
1230 print "error %s" % ref
1232 # update local bookmarks
1233 for ref, bmark, old, new in p_bmarks:
1234 if not bookmarks.pushbookmark(parser.repo, bmark, old, new):
1235 print "error %s" % ref
1239 def do_option(parser):
1240 global dry_run, force_push
1241 _, key, value = parser.line.split(' ')
1242 if key == 'dry-run':
1243 dry_run = (value == 'true')
1245 elif key == 'force':
1246 force_push = (value == 'true')
1251 def fix_path(alias, repo, orig_url):
1252 url = urlparse.urlparse(orig_url, 'file')
1253 if url.scheme != 'file' or os.path.isabs(os.path.expanduser(url.path)):
1255 abs_url = urlparse.urljoin("%s/" % os.getcwd(), orig_url)
1256 cmd = ['git', 'config', 'remote.%s.url' % alias, "hg::%s" % abs_url]
1257 subprocess.call(cmd)
1260 global prefix, gitdir, dirname, branches, bmarks
1261 global marks, blob_marks, parsed_refs
1262 global peer, mode, bad_mail, bad_name
1263 global track_branches, force_push, is_tmp
1266 global fake_bmark, hg_version
1272 gitdir = os.environ.get('GIT_DIR', None)
1275 die('Not enough arguments.')
1278 die('GIT_DIR not set')
1284 hg_git_compat = get_config_bool('remote-hg.hg-git-compat')
1285 track_branches = get_config_bool('remote-hg.track-branches', True)
1290 bad_mail = 'none@none'
1294 bad_mail = 'unknown'
1295 bad_name = 'Unknown'
1297 if alias[4:] == url:
1299 alias = hashlib.sha1(alias).hexdigest()
1301 dirname = os.path.join(gitdir, 'hg', alias)
1310 version, _, extra = util.version().partition('+')
1311 version = list(int(e) for e in version.split('.'))
1314 hg_version = tuple(version)
1320 repo = get_repo(url, alias)
1321 prefix = 'refs/hg/%s' % alias
1324 fix_path(alias, peer or repo, url)
1326 marks_path = os.path.join(dirname, 'marks-hg')
1327 marks = Marks(marks_path, repo)
1329 if sys.platform == 'win32':
1331 msvcrt.setmode(sys.stdout.fileno(), os.O_BINARY)
1333 parser = Parser(repo)
1335 if parser.check('capabilities'):
1336 do_capabilities(parser)
1337 elif parser.check('list'):
1339 elif parser.check('import'):
1341 elif parser.check('export'):
1343 elif parser.check('option'):
1346 die('unhandled command: %s' % line)
1353 shutil.rmtree(dirname)
1355 atexit.register(bye)
1356 sys.exit(main(sys.argv))