make hook code nicer.
authorVadim Gelfer <vadim.gelfer@gmail.com>
Tue, 14 Feb 2006 15:28:06 -0800
changeset 1718 c1996b84d4f5
parent 1717 7a4a16a7d21f
child 1719 98072468ffde
make hook code nicer. pre hooks can raise exception if fail. tidy up better if exception raised (like KeyboardInterrupt) when running hook program.
mercurial/localrepo.py
--- a/mercurial/localrepo.py	Tue Feb 14 15:10:45 2006 -0800
+++ b/mercurial/localrepo.py	Tue Feb 14 15:28:06 2006 -0800
@@ -48,7 +48,7 @@
         except IOError:
             pass
 
-    def hook(self, name, **args):
+    def hook(self, name, throw=False, **args):
         def runhook(name, cmd):
             self.ui.note(_("running hook %s: %s\n") % (name, cmd))
             old = {}
@@ -57,21 +57,25 @@
                 old[k] = os.environ.get(k, None)
                 os.environ[k] = v
 
-            # Hooks run in the repository root
-            olddir = os.getcwd()
-            os.chdir(self.root)
-            r = os.system(cmd)
-            os.chdir(olddir)
+            try:
+                # Hooks run in the repository root
+                olddir = os.getcwd()
+                os.chdir(self.root)
+                r = os.system(cmd)
+            finally:
+                for k, v in old.items():
+                    if v != None:
+                        os.environ[k] = v
+                    else:
+                        del os.environ[k]
 
-            for k, v in old.items():
-                if v != None:
-                    os.environ[k] = v
-                else:
-                    del os.environ[k]
+                os.chdir(olddir)
 
             if r:
-                self.ui.warn(_("abort: %s hook failed with status %d!\n") %
-                             (name, r))
+                desc, r = util.explain_exit(r)
+                if throw:
+                    raise util.Abort(_('%s hook %s') % (name, desc))
+                self.ui.warn(_('error: %s hook %s\n') % (name, desc))
                 return False
             return True
 
@@ -372,8 +376,7 @@
             self.ui.status(_("nothing changed\n"))
             return None
 
-        if not self.hook("precommit"):
-            return None
+        self.hook("precommit", throw=True)
 
         if not wlock:
             wlock = self.wlock()