diff mercurial/ui.py @ 38526:313a940d49a3

ui: add an uninterruptable context manager that can block SIGINT The blocking of SIGINT is not done by default, but my hope is that we will one day. This was inspired by Facebook's "nointerrupt" extension, which is a bit more heavy-handed than this (whole commands are treated as unsafe to interrupt). A future patch will enable this for varying bits of Mercurial that are performing unsafe operations. It's intentional that the KeyboardInterrupt is raised as the context manager exits: during the span of the context manager interrupting Mercurial could lead to data loss, but typically those spans are fairly narrow, so we can let the unsafe block complete and then terminate hg (which will leave the repo in a consistent state, even if it's not the user's desired state). .. api:: New context manager ``ui.uninterruptable()`` to mark portions of a command as potentially unsafe places to interrupt Mercurial with Control-C or similar. Differential Revision: https://phab.mercurial-scm.org/D3716
author Augie Fackler <augie@google.com>
date Wed, 27 Jun 2018 10:47:14 -0400
parents bec1212eceaa
children 152f4822d210
line wrap: on
line diff
--- a/mercurial/ui.py	Tue Jul 03 12:22:37 2018 -0400
+++ b/mercurial/ui.py	Wed Jun 27 10:47:14 2018 -0400
@@ -224,6 +224,7 @@
         self._colormode = None
         self._terminfoparams = {}
         self._styles = {}
+        self._uninterruptible = False
 
         if src:
             self.fout = src.fout
@@ -334,6 +335,37 @@
             self._blockedtimes[key + '_blocked'] += \
                 (util.timer() - starttime) * 1000
 
+    @contextlib.contextmanager
+    def uninterruptable(self):
+        """Mark an operation as unsafe.
+
+        Most operations on a repository are safe to interrupt, but a
+        few are risky (for example repair.strip). This context manager
+        lets you advise Mercurial that something risky is happening so
+        that control-C etc can be blocked if desired.
+        """
+        enabled = self.configbool('experimental', 'nointerrupt')
+        if (enabled and
+            self.configbool('experimental', 'nointerrupt-interactiveonly')):
+            enabled = self.interactive()
+        if self._uninterruptible or not enabled:
+            # if nointerrupt support is turned off, the process isn't
+            # interactive, or we're already in an uninterruptable
+            # block, do nothing.
+            yield
+            return
+        def warn():
+            self.warn(_("shutting down cleanly\n"))
+            self.warn(
+                _("press ^C again to terminate immediately (dangerous)\n"))
+            return True
+        with procutil.uninterruptable(warn):
+            try:
+                self._uninterruptible = True
+                yield
+            finally:
+                self._uninterruptible = False
+
     def formatter(self, topic, opts):
         return formatter.formatter(self, self, topic, opts)