changeset 589:2af1d664f498

Implement new commands: hg2git and git2hg Theses command take hg a series of hg revisions or revsets and lists their git hashes, and vice-versa
author Jordi Gutiérrez Hermoso <jordigh@octave.org>
date Fri, 23 Nov 2012 15:28:45 -0500
parents 4d9e2d2a2c19
children
files hggit/__init__.py
diffstat 1 files changed, 55 insertions(+), 1 deletions(-) [+]
line wrap: on
line diff
--- a/hggit/__init__.py
+++ b/hggit/__init__.py
@@ -30,6 +30,7 @@
 from mercurial import hg
 from mercurial import localrepo
 from mercurial import revset
+from mercurial import scmutil
 from mercurial import templatekw
 from mercurial import util as hgutil
 from mercurial import url
@@ -64,6 +65,53 @@
         def localpath(self):
             return self.p
 
+def hg2git(ui, repo, *revs, **opts):
+    """convert Mercurial revisions to their git hashes"""
+    revs = list(revs) + opts.get("rev")
+    revs = scmutil.revrange(repo, revs)
+
+    git = GitHandler(repo, ui)
+    for rev in revs:
+
+        hgsha = repo[rev].hex()
+        gitsha = git.map_git_get(hgsha)[0:12]
+        gitsha = _append_bookmarks(gitsha, hgsha)
+
+        ui.write(_("hg %s:%s -> git %s\n") % (rev, hgsha[0:12], gitsha))
+
+
+def git2hg(ui, repo, *revs, **opts):
+    """convert git hashes, branches, or refs to their Mercurial revision"""
+    revs = list(revs) + opts.get("rev")
+
+    git = GitHandler(repo, ui)
+    for rev in revs:
+        try:
+            gitsha = git.map_git_get(git.local_heads()[rev])
+        except KeyError:
+            gitsha = rev
+
+        gitshas = [sha for sha in git._map_git.keys() if sha.startswith(gitsha)]
+        if not gitshas:
+            raise hgutil.Abort(_("git ref %s not in repo") % gitsha)
+        if len(gitshas) > 1:
+            raise hgutil.Abort(_("ambiguous git ref: %s") % gitsha)
+
+        gitsha = gitshas[0]
+
+        hgsha = git.map_hg_get(gitsha)
+        hgrev = scmutil.revrange(repo, [hgsha])[0]
+        gitsha = gitshas[0][0:12]
+
+        gitsha = _append_bookmarks(gitsha, hgsha)
+
+        ui.write(_("git %s -> hg %s:%s\n") % (gitsha, hgrev, hgsha[0:12]))
+
+def _append_bookmarks(gitsha, hgsha):
+    bookmarks = [b for b, h in git.local_heads().iteritems() if h == hgsha]
+    gitsha += " (%s)" % ", ".join(bookmarks)
+    return gitsha
+
 def _local(path):
     p = urlcls(path).localpath()
     if (os.path.exists(os.path.join(p, '.git')) and
@@ -233,5 +281,11 @@
   "gclear":
       (gclear, [], _('Clears out the Git cached data')),
   "git-cleanup": (git_cleanup, [], _(
-        "Cleans up git repository after history editing"))
+        "Cleans up git repository after history editing")),
+   "hg2git": (hg2git, [('r', 'rev', [],
+                        _("hg revision to convert to git hash"))],
+                        _("hg hg2git [-r] REV")),
+   "git2hg": (git2hg, [('r', 'rev', [],
+                        _("git hash to convert to hg revision"))],
+                        _("hg hg2git [-r] REV")),
 }