hooks.py 6.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200
  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. from typing import Any
  24. from .errors import HookError
  25. class Hook:
  26. """Generic hook object."""
  27. def execute(self, *args) -> Any:
  28. """Execute the hook with the given args.
  29. Args:
  30. args: argument list to hook
  31. Raises:
  32. HookError: hook execution failure
  33. Returns:
  34. 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__(
  43. self,
  44. name,
  45. path,
  46. numparam,
  47. pre_exec_callback=None,
  48. post_exec_callback=None,
  49. cwd=None,
  50. ) -> None:
  51. """Setup shell hook definition.
  52. Args:
  53. name: name of hook for error messages
  54. path: absolute path to executable file
  55. numparam: number of requirements parameters
  56. pre_exec_callback: closure for setup before execution
  57. Defaults to None. Takes in the variable argument list from the
  58. execute functions and returns a modified argument list for the
  59. shell hook.
  60. post_exec_callback: closure for cleanup after execution
  61. Defaults to None. Takes in a boolean for hook success and the
  62. modified argument list and returns the final hook return value
  63. if applicable
  64. cwd: working directory to switch to when executing the hook
  65. """
  66. self.name = name
  67. self.filepath = path
  68. self.numparam = numparam
  69. self.pre_exec_callback = pre_exec_callback
  70. self.post_exec_callback = post_exec_callback
  71. self.cwd = cwd
  72. def execute(self, *args):
  73. """Execute the hook with given args."""
  74. if len(args) != self.numparam:
  75. raise HookError(
  76. "Hook %s executed with wrong number of args. \
  77. Expected %d. Saw %d. args: %s"
  78. % (self.name, self.numparam, len(args), args)
  79. )
  80. if self.pre_exec_callback is not None:
  81. args = self.pre_exec_callback(*args)
  82. try:
  83. ret = subprocess.call(
  84. [os.path.relpath(self.filepath, self.cwd), *list(args)], cwd=self.cwd
  85. )
  86. if ret != 0:
  87. if self.post_exec_callback is not None:
  88. self.post_exec_callback(0, *args)
  89. raise HookError(
  90. "Hook %s exited with non-zero status %d" % (self.name, ret)
  91. )
  92. if self.post_exec_callback is not None:
  93. return self.post_exec_callback(1, *args)
  94. except OSError: # no file. silent failure.
  95. if self.post_exec_callback is not None:
  96. self.post_exec_callback(0, *args)
  97. class PreCommitShellHook(ShellHook):
  98. """pre-commit shell hook."""
  99. def __init__(self, cwd, controldir) -> None:
  100. filepath = os.path.join(controldir, "hooks", "pre-commit")
  101. ShellHook.__init__(self, "pre-commit", filepath, 0, cwd=cwd)
  102. class PostCommitShellHook(ShellHook):
  103. """post-commit shell hook."""
  104. def __init__(self, controldir) -> None:
  105. filepath = os.path.join(controldir, "hooks", "post-commit")
  106. ShellHook.__init__(self, "post-commit", filepath, 0, cwd=controldir)
  107. class CommitMsgShellHook(ShellHook):
  108. """commit-msg shell hook."""
  109. def __init__(self, controldir) -> None:
  110. filepath = os.path.join(controldir, "hooks", "commit-msg")
  111. def prepare_msg(*args):
  112. import tempfile
  113. (fd, path) = tempfile.mkstemp()
  114. with os.fdopen(fd, "wb") as f:
  115. f.write(args[0])
  116. return (path,)
  117. def clean_msg(success, *args):
  118. if success:
  119. with open(args[0], "rb") as f:
  120. new_msg = f.read()
  121. os.unlink(args[0])
  122. return new_msg
  123. os.unlink(args[0])
  124. ShellHook.__init__(
  125. self, "commit-msg", filepath, 1, prepare_msg, clean_msg, controldir
  126. )
  127. class PostReceiveShellHook(ShellHook):
  128. """post-receive shell hook."""
  129. def __init__(self, controldir) -> None:
  130. self.controldir = controldir
  131. filepath = os.path.join(controldir, "hooks", "post-receive")
  132. ShellHook.__init__(self, "post-receive", path=filepath, numparam=0)
  133. def execute(self, client_refs):
  134. # do nothing if the script doesn't exist
  135. if not os.path.exists(self.filepath):
  136. return None
  137. try:
  138. env = os.environ.copy()
  139. env["GIT_DIR"] = self.controldir
  140. p = subprocess.Popen(
  141. self.filepath,
  142. stdin=subprocess.PIPE,
  143. stdout=subprocess.PIPE,
  144. stderr=subprocess.PIPE,
  145. env=env,
  146. )
  147. # client_refs is a list of (oldsha, newsha, ref)
  148. in_data = b"\n".join([b" ".join(ref) for ref in client_refs])
  149. out_data, err_data = p.communicate(in_data)
  150. if (p.returncode != 0) or err_data:
  151. err_fmt = b"post-receive exit code: %d\n" + b"stdout:\n%s\nstderr:\n%s"
  152. err_msg = err_fmt % (p.returncode, out_data, err_data)
  153. raise HookError(err_msg.decode("utf-8", "backslashreplace"))
  154. return out_data
  155. except OSError as err:
  156. raise HookError(repr(err)) from err