hooks.py 5.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156
  1. # hooks.py -- for dealing with git hooks
  2. # Copyright (C) 2012-2013 Jelmer Vernooij and others.
  3. #
  4. # Dulwich is dual-licensed under the Apache License, Version 2.0 and the GNU
  5. # General Public License as public by the Free Software Foundation; version 2.0
  6. # or (at your option) any later version. You can redistribute it and/or
  7. # modify it under the terms of either of these two licenses.
  8. #
  9. # Unless required by applicable law or agreed to in writing, software
  10. # distributed under the License is distributed on an "AS IS" BASIS,
  11. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. # See the License for the specific language governing permissions and
  13. # limitations under the License.
  14. #
  15. # You should have received a copy of the licenses; if not, see
  16. # <http://www.gnu.org/licenses/> for a copy of the GNU General Public License
  17. # and <http://www.apache.org/licenses/LICENSE-2.0> for a copy of the Apache
  18. # License, Version 2.0.
  19. #
  20. """Access to hooks."""
  21. import os
  22. import subprocess
  23. import sys
  24. import tempfile
  25. from dulwich.errors import (
  26. HookError,
  27. )
  28. class Hook(object):
  29. """Generic hook object."""
  30. def execute(self, *args):
  31. """Execute the hook with the given args
  32. :param args: argument list to hook
  33. :raise HookError: hook execution failure
  34. :return: a hook may return a useful value
  35. """
  36. raise NotImplementedError(self.execute)
  37. class ShellHook(Hook):
  38. """Hook by executable file
  39. Implements standard githooks(5) [0]:
  40. [0] http://www.kernel.org/pub/software/scm/git/docs/githooks.html
  41. """
  42. def __init__(self, name, path, numparam,
  43. pre_exec_callback=None, post_exec_callback=None,
  44. cwd=None):
  45. """Setup shell hook definition
  46. :param name: name of hook for error messages
  47. :param path: absolute path to executable file
  48. :param numparam: number of requirements parameters
  49. :param pre_exec_callback: closure for setup before execution
  50. Defaults to None. Takes in the variable argument list from the
  51. execute functions and returns a modified argument list for the
  52. shell hook.
  53. :param post_exec_callback: closure for cleanup after execution
  54. Defaults to None. Takes in a boolean for hook success and the
  55. modified argument list and returns the final hook return value
  56. if applicable
  57. :param cwd: working directory to switch to when executing the hook
  58. """
  59. self.name = name
  60. self.filepath = path
  61. self.numparam = numparam
  62. self.pre_exec_callback = pre_exec_callback
  63. self.post_exec_callback = post_exec_callback
  64. self.cwd = cwd
  65. if sys.version_info[0] == 2 and sys.platform == 'win32':
  66. # Python 2 on windows does not support unicode file paths
  67. # http://bugs.python.org/issue1759845
  68. self.filepath = self.filepath.encode(sys.getfilesystemencoding())
  69. def execute(self, *args):
  70. """Execute the hook with given args"""
  71. if len(args) != self.numparam:
  72. raise HookError("Hook %s executed with wrong number of args. \
  73. Expected %d. Saw %d. args: %s"
  74. % (self.name, self.numparam, len(args), args))
  75. if (self.pre_exec_callback is not None):
  76. args = self.pre_exec_callback(*args)
  77. try:
  78. ret = subprocess.call([self.filepath] + list(args), cwd=self.cwd)
  79. if ret != 0:
  80. if (self.post_exec_callback is not None):
  81. self.post_exec_callback(0, *args)
  82. raise HookError("Hook %s exited with non-zero status"
  83. % (self.name))
  84. if (self.post_exec_callback is not None):
  85. return self.post_exec_callback(1, *args)
  86. except OSError: # no file. silent failure.
  87. if (self.post_exec_callback is not None):
  88. self.post_exec_callback(0, *args)
  89. class PreCommitShellHook(ShellHook):
  90. """pre-commit shell hook"""
  91. def __init__(self, controldir):
  92. filepath = os.path.join(controldir, 'hooks', 'pre-commit')
  93. ShellHook.__init__(self, 'pre-commit', filepath, 0, cwd=controldir)
  94. class PostCommitShellHook(ShellHook):
  95. """post-commit shell hook"""
  96. def __init__(self, controldir):
  97. filepath = os.path.join(controldir, 'hooks', 'post-commit')
  98. ShellHook.__init__(self, 'post-commit', filepath, 0, cwd=controldir)
  99. class CommitMsgShellHook(ShellHook):
  100. """commit-msg shell hook
  101. :param args[0]: commit message
  102. :return: new commit message or None
  103. """
  104. def __init__(self, controldir):
  105. filepath = os.path.join(controldir, 'hooks', 'commit-msg')
  106. def prepare_msg(*args):
  107. (fd, path) = tempfile.mkstemp()
  108. with os.fdopen(fd, 'wb') as f:
  109. f.write(args[0])
  110. return (path,)
  111. def clean_msg(success, *args):
  112. if success:
  113. with open(args[0], 'rb') as f:
  114. new_msg = f.read()
  115. os.unlink(args[0])
  116. return new_msg
  117. os.unlink(args[0])
  118. ShellHook.__init__(self, 'commit-msg', filepath, 1,
  119. prepare_msg, clean_msg, controldir)