evolvecmd: move more chunks of code from __init__.py to evolvecmd.py
authorPulkit Goyal <7895pulkit@gmail.com>
Fri, 19 Jan 2018 15:22:28 +0530
changeset 3463 f994c480cea9
parent 3462 e147c18ed064
child 3464 908d2b5dfa7e
evolvecmd: move more chunks of code from __init__.py to evolvecmd.py
hgext3rd/evolve/__init__.py
hgext3rd/evolve/evolvecmd.py
--- a/hgext3rd/evolve/__init__.py	Fri Jan 19 15:04:12 2018 +0530
+++ b/hgext3rd/evolve/__init__.py	Fri Jan 19 15:22:28 2018 +0530
@@ -253,7 +253,6 @@
 """.strip()
 
 import sys
-import re
 import collections
 import struct
 
@@ -291,7 +290,6 @@
     help,
     hg,
     lock as lockmod,
-    merge,
     node,
     obsolete,
     patch,
@@ -328,8 +326,6 @@
 minimumhgversion = metadata.minimumhgversion
 buglink = metadata.buglink
 
-sha1re = re.compile(r'\b[0-9a-f]{6,40}\b')
-
 # Flags for enabling optional parts of evolve
 commandopt = 'allnewcommands'
 
@@ -875,82 +871,6 @@
 ### Old Evolve extension content                                  ###
 #####################################################################
 
-# XXX need clean up and proper sorting in other section
-
-### changeset rewriting logic
-#############################
-
-class MergeFailure(error.Abort):
-    pass
-
-def relocate(repo, orig, dest, pctx=None, keepbranch=False):
-    """rewrites the orig rev on dest rev
-
-    returns the node of new commit which is formed
-    """
-    if orig.rev() == dest.rev():
-        raise error.Abort(_('tried to relocate a node on top of itself'),
-                          hint=_("This shouldn't happen. If you still "
-                                 "need to move changesets, please do so "
-                                 "manually with nothing to rebase - working "
-                                 "directory parent is also destination"))
-
-    if pctx is None:
-        if len(orig.parents()) == 2:
-            raise error.Abort(_("tried to relocate a merge commit without "
-                                "specifying which parent should be moved"),
-                              hint=_("Specify the parent by passing in pctx"))
-        pctx = orig.p1()
-
-    commitmsg = orig.description()
-
-    cache = {}
-    sha1s = re.findall(sha1re, commitmsg)
-    unfi = repo.unfiltered()
-    for sha1 in sha1s:
-        ctx = None
-        try:
-            ctx = unfi[sha1]
-        except error.RepoLookupError:
-            continue
-
-        if not ctx.obsolete():
-            continue
-
-        successors = compat.successorssets(repo, ctx.node(), cache)
-
-        # We can't make any assumptions about how to update the hash if the
-        # cset in question was split or diverged.
-        if len(successors) == 1 and len(successors[0]) == 1:
-            newsha1 = node.hex(successors[0][0])
-            commitmsg = commitmsg.replace(sha1, newsha1[:len(sha1)])
-        else:
-            repo.ui.note(_('The stale commit message reference to %s could '
-                           'not be updated\n') % sha1)
-
-    tr = repo.currenttransaction()
-    assert tr is not None
-    try:
-        r = _evolvemerge(repo, orig, dest, pctx, keepbranch)
-        if r[-1]: # some conflict
-            raise error.Abort(_('unresolved merge conflicts '
-                                '(see hg help resolve)'))
-        nodenew = _relocatecommit(repo, orig, commitmsg)
-    except error.Abort as exc:
-        with repo.dirstate.parentchange():
-            repo.setparents(repo['.'].node(), nullid)
-            repo.dirstate.write(tr)
-            # fix up dirstate for copies and renames
-            compat.duplicatecopies(repo, repo[None], dest.rev(), orig.p1().rev())
-
-        class LocalMergeFailure(MergeFailure, exc.__class__):
-            pass
-        exc.__class__ = LocalMergeFailure
-        tr.close() # to keep changes in this transaction (e.g. dirstate)
-        raise
-    _finalizerelocate(repo, orig, dest, nodenew, tr)
-    return nodenew
-
 ### new command
 #############################
 
@@ -2110,45 +2030,6 @@
                               _helploader))
         help.helptable.sort()
 
-def _relocatecommit(repo, orig, commitmsg):
-    if commitmsg is None:
-        commitmsg = orig.description()
-    extra = dict(orig.extra())
-    if 'branch' in extra:
-        del extra['branch']
-    extra['rebase_source'] = orig.hex()
-
-    backup = repo.ui.backupconfig('phases', 'new-commit')
-    try:
-        targetphase = max(orig.phase(), phases.draft)
-        repo.ui.setconfig('phases', 'new-commit', targetphase, 'evolve')
-        # Commit might fail if unresolved files exist
-        nodenew = repo.commit(text=commitmsg, user=orig.user(),
-                              date=orig.date(), extra=extra)
-    finally:
-        repo.ui.restoreconfig(backup)
-    return nodenew
-
-def _finalizerelocate(repo, orig, dest, nodenew, tr):
-    destbookmarks = repo.nodebookmarks(dest.node())
-    nodesrc = orig.node()
-    oldbookmarks = repo.nodebookmarks(nodesrc)
-    bmchanges = []
-
-    if nodenew is not None:
-        obsolete.createmarkers(repo, [(repo[nodesrc], (repo[nodenew],))])
-        for book in oldbookmarks:
-            bmchanges.append((book, nodenew))
-    else:
-        obsolete.createmarkers(repo, [(repo[nodesrc], ())])
-        # Behave like rebase, move bookmarks to dest
-        for book in oldbookmarks:
-            bmchanges.append((book, dest.node()))
-    for book in destbookmarks: # restore bookmark that rebase move
-        bmchanges.append((book, dest.node()))
-    if bmchanges:
-        compat.bookmarkapplychanges(repo, tr, bmchanges)
-
 evolvestateversion = 0
 
 @eh.uisetup
@@ -2162,27 +2043,3 @@
     ret = orig(repo, *args, **kwargs)
     util.unlinkpath(repo.vfs.join('evolvestate'), ignoremissing=True)
     return ret
-
-def _evolvemerge(repo, orig, dest, pctx, keepbranch):
-    """Used by the evolve function to merge dest on top of pctx.
-    return the same tuple as merge.graft"""
-    if repo['.'].rev() != dest.rev():
-        merge.update(repo,
-                     dest,
-                     branchmerge=False,
-                     force=True)
-    if repo._activebookmark:
-        repo.ui.status(_("(leaving bookmark %s)\n") % repo._activebookmark)
-    bookmarksmod.deactivate(repo)
-    if keepbranch:
-        repo.dirstate.setbranch(orig.branch())
-    if util.safehasattr(repo, 'currenttopic'):
-        # uurrgs
-        # there no other topic setter yet
-        if not orig.topic() and repo.vfs.exists('topic'):
-                repo.vfs.unlink('topic')
-        else:
-            with repo.vfs.open('topic', 'w') as f:
-                f.write(orig.topic())
-
-    return merge.graft(repo, orig, pctx, ['destination', 'evolving'], True)
--- a/hgext3rd/evolve/evolvecmd.py	Fri Jan 19 15:04:12 2018 +0530
+++ b/hgext3rd/evolve/evolvecmd.py	Fri Jan 19 15:22:28 2018 +0530
@@ -8,7 +8,10 @@
 
 """logic related to hg evolve command"""
 
+import re
+
 from mercurial import (
+    bookmarks as bookmarksmod,
     cmdutil,
     context,
     copies,
@@ -19,6 +22,7 @@
     node,
     obsolete,
     phases,
+    util,
 )
 
 from mercurial.i18n import _
@@ -34,8 +38,9 @@
 TROUBLES = compat.TROUBLES
 shorttemplate = utility.shorttemplate
 _bookmarksupdater = rewriteutil.bookmarksupdater
+sha1re = re.compile(r'\b[0-9a-f]{6,40}\b')
 
-from . import relocate, divergentdata, MergeFailure
+from . import divergentdata
 
 def _solveone(ui, repo, ctx, dryrun, confirm, progresscb, category):
     """Resolve the troubles affecting one revision
@@ -387,3 +392,137 @@
         return (True, new.node())
     finally:
         repo.ui.restoreconfig(emtpycommitallowed)
+
+class MergeFailure(error.Abort):
+    pass
+
+def relocate(repo, orig, dest, pctx=None, keepbranch=False):
+    """rewrites the orig rev on dest rev
+
+    returns the node of new commit which is formed
+    """
+    if orig.rev() == dest.rev():
+        raise error.Abort(_('tried to relocate a node on top of itself'),
+                          hint=_("This shouldn't happen. If you still "
+                                 "need to move changesets, please do so "
+                                 "manually with nothing to rebase - working "
+                                 "directory parent is also destination"))
+
+    if pctx is None:
+        if len(orig.parents()) == 2:
+            raise error.Abort(_("tried to relocate a merge commit without "
+                                "specifying which parent should be moved"),
+                              hint=_("Specify the parent by passing in pctx"))
+        pctx = orig.p1()
+
+    commitmsg = orig.description()
+
+    cache = {}
+    sha1s = re.findall(sha1re, commitmsg)
+    unfi = repo.unfiltered()
+    for sha1 in sha1s:
+        ctx = None
+        try:
+            ctx = unfi[sha1]
+        except error.RepoLookupError:
+            continue
+
+        if not ctx.obsolete():
+            continue
+
+        successors = compat.successorssets(repo, ctx.node(), cache)
+
+        # We can't make any assumptions about how to update the hash if the
+        # cset in question was split or diverged.
+        if len(successors) == 1 and len(successors[0]) == 1:
+            newsha1 = node.hex(successors[0][0])
+            commitmsg = commitmsg.replace(sha1, newsha1[:len(sha1)])
+        else:
+            repo.ui.note(_('The stale commit message reference to %s could '
+                           'not be updated\n') % sha1)
+
+    tr = repo.currenttransaction()
+    assert tr is not None
+    try:
+        r = _evolvemerge(repo, orig, dest, pctx, keepbranch)
+        if r[-1]: # some conflict
+            raise error.Abort(_('unresolved merge conflicts '
+                                '(see hg help resolve)'))
+        nodenew = _relocatecommit(repo, orig, commitmsg)
+    except error.Abort as exc:
+        with repo.dirstate.parentchange():
+            repo.setparents(repo['.'].node(), node.nullid)
+            repo.dirstate.write(tr)
+            # fix up dirstate for copies and renames
+            compat.duplicatecopies(repo, repo[None], dest.rev(), orig.p1().rev())
+
+        class LocalMergeFailure(MergeFailure, exc.__class__):
+            pass
+        exc.__class__ = LocalMergeFailure
+        tr.close() # to keep changes in this transaction (e.g. dirstate)
+        raise
+    _finalizerelocate(repo, orig, dest, nodenew, tr)
+    return nodenew
+
+def _relocatecommit(repo, orig, commitmsg):
+    if commitmsg is None:
+        commitmsg = orig.description()
+    extra = dict(orig.extra())
+    if 'branch' in extra:
+        del extra['branch']
+    extra['rebase_source'] = orig.hex()
+
+    backup = repo.ui.backupconfig('phases', 'new-commit')
+    try:
+        targetphase = max(orig.phase(), phases.draft)
+        repo.ui.setconfig('phases', 'new-commit', targetphase, 'evolve')
+        # Commit might fail if unresolved files exist
+        nodenew = repo.commit(text=commitmsg, user=orig.user(),
+                              date=orig.date(), extra=extra)
+    finally:
+        repo.ui.restoreconfig(backup)
+    return nodenew
+
+def _finalizerelocate(repo, orig, dest, nodenew, tr):
+    destbookmarks = repo.nodebookmarks(dest.node())
+    nodesrc = orig.node()
+    oldbookmarks = repo.nodebookmarks(nodesrc)
+    bmchanges = []
+
+    if nodenew is not None:
+        obsolete.createmarkers(repo, [(repo[nodesrc], (repo[nodenew],))])
+        for book in oldbookmarks:
+            bmchanges.append((book, nodenew))
+    else:
+        obsolete.createmarkers(repo, [(repo[nodesrc], ())])
+        # Behave like rebase, move bookmarks to dest
+        for book in oldbookmarks:
+            bmchanges.append((book, dest.node()))
+    for book in destbookmarks: # restore bookmark that rebase move
+        bmchanges.append((book, dest.node()))
+    if bmchanges:
+        compat.bookmarkapplychanges(repo, tr, bmchanges)
+
+def _evolvemerge(repo, orig, dest, pctx, keepbranch):
+    """Used by the evolve function to merge dest on top of pctx.
+    return the same tuple as merge.graft"""
+    if repo['.'].rev() != dest.rev():
+        merge.update(repo,
+                     dest,
+                     branchmerge=False,
+                     force=True)
+    if repo._activebookmark:
+        repo.ui.status(_("(leaving bookmark %s)\n") % repo._activebookmark)
+    bookmarksmod.deactivate(repo)
+    if keepbranch:
+        repo.dirstate.setbranch(orig.branch())
+    if util.safehasattr(repo, 'currenttopic'):
+        # uurrgs
+        # there no other topic setter yet
+        if not orig.topic() and repo.vfs.exists('topic'):
+                repo.vfs.unlink('topic')
+        else:
+            with repo.vfs.open('topic', 'w') as f:
+                f.write(orig.topic())
+
+    return merge.graft(repo, orig, pctx, ['destination', 'evolving'], True)