浏览代码

Use try except instead exists method in PreReceiveShellHook class

Stéphane Klein 10 年之前
父节点
当前提交
6876b9b4ee
共有 3 个文件被更改,包括 25 次插入15 次删除
  1. 12 11
      dulwich/hooks.py
  2. 3 2
      dulwich/server.py
  3. 10 2
      dulwich/tests/test_hooks.py

+ 12 - 11
dulwich/hooks.py

@@ -151,15 +151,16 @@ class PreReceiveShellHook(ShellHook):
         filepath = os.path.join(controldir, 'hooks', 'pre-receive')
         ShellHook.__init__(self, 'pre-receive', filepath, 0)
 
-    def exists(self):
-        return os.path.exists(self.filepath)
-
     def execute(self, stdin):
-        p = subprocess.Popen(
-            self.filepath,
-            stdin=subprocess.PIPE,
-            stdout=subprocess.PIPE,
-            stderr=subprocess.PIPE
-        )
-        self.stdout, self.stderr = p.communicate(stdin)
-        return p.returncode
+        try:
+            p = subprocess.Popen(
+                self.filepath,
+                stdin=subprocess.PIPE,
+                stdout=subprocess.PIPE,
+                stderr=subprocess.PIPE
+            )
+            self.stdout, self.stderr = p.communicate(stdin)
+            return p.returncode
+        except OSError:  # no file. silent failure.
+            self.stdout = None
+            return 0

+ 3 - 2
dulwich/server.py

@@ -823,11 +823,12 @@ class ReceivePackHandler(Handler):
 
         hook = self.hooks.get('pre-receive', None)
         ret = 0
-        if hook and hook.exists():
+        if hook:
             ret = hook.execute(
                 stdin='\n'.join([' '.join(i) for i in client_refs])
             )
-            self.proto.write_sideband(2, hook.stdout)
+            if hook.stdout:
+                self.proto.write_sideband(2, hook.stdout)
 
         if ret == 0:
             # backend can now deal with this refs and read a

+ 10 - 2
dulwich/tests/test_hooks.py

@@ -144,7 +144,6 @@ exit 0
 
         os.chmod(pre_receive, stat.S_IREAD | stat.S_IWRITE | stat.S_IEXEC)
 
-        self.assertTrue(hook.exists())
         self.assertEqual(hook.execute("line1\nline2\nline3\n"), 0)
         self.assertEqual(
             hook.stdout,
@@ -166,5 +165,14 @@ exit 1
 
         os.chmod(pre_receive, stat.S_IREAD | stat.S_IWRITE | stat.S_IEXEC)
 
-        self.assertTrue(hook.exists())
         self.assertEqual(hook.execute("line1\nline2\nline3\n"), 1)
+
+    def test_hook_pre_receive_missing(self):
+        repo_dir = os.path.join(tempfile.mkdtemp())
+        os.makedirs(os.path.join(repo_dir, 'hooks'))
+        self.addCleanup(shutil.rmtree, repo_dir)
+
+        hook = PreReceiveShellHook(repo_dir)
+
+        self.assertEqual(hook.execute("line1\nline2\nline3\n"), 0)
+        self.assertIsNone(hook.stdout)