hooks.py 7.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237
  1. # hooks.py -- for dealing with git hooks
  2. # Copyright (C) 2012-2013 Jelmer Vernooij and others.
  3. #
  4. # SPDX-License-Identifier: Apache-2.0 OR GPL-2.0-or-later
  5. # Dulwich is dual-licensed under the Apache License, Version 2.0 and the GNU
  6. # General Public License as published by the Free Software Foundation; version 2.0
  7. # or (at your option) any later version. You can redistribute it and/or
  8. # modify it under the terms of either of these two licenses.
  9. #
  10. # Unless required by applicable law or agreed to in writing, software
  11. # distributed under the License is distributed on an "AS IS" BASIS,
  12. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. # See the License for the specific language governing permissions and
  14. # limitations under the License.
  15. #
  16. # You should have received a copy of the licenses; if not, see
  17. # <http://www.gnu.org/licenses/> for a copy of the GNU General Public License
  18. # and <http://www.apache.org/licenses/LICENSE-2.0> for a copy of the Apache
  19. # License, Version 2.0.
  20. #
  21. """Access to hooks."""
  22. import os
  23. import subprocess
  24. from collections.abc import Callable, Sequence
  25. from typing import Any
  26. from .errors import HookError
  27. class Hook:
  28. """Generic hook object."""
  29. def execute(self, *args: Any) -> Any: # noqa: ANN401
  30. """Execute the hook with the given args.
  31. Args:
  32. args: argument list to hook
  33. Raises:
  34. HookError: hook execution failure
  35. Returns:
  36. a hook may return a useful value
  37. """
  38. raise NotImplementedError(self.execute)
  39. class ShellHook(Hook):
  40. """Hook by executable file.
  41. Implements standard githooks(5) [0]:
  42. [0] http://www.kernel.org/pub/software/scm/git/docs/githooks.html
  43. """
  44. def __init__(
  45. self,
  46. name: str,
  47. path: str,
  48. numparam: int,
  49. pre_exec_callback: Callable[..., Any] | None = None,
  50. post_exec_callback: Callable[..., Any] | None = None,
  51. cwd: str | None = None,
  52. ) -> None:
  53. """Setup shell hook definition.
  54. Args:
  55. name: name of hook for error messages
  56. path: absolute path to executable file
  57. numparam: number of requirements parameters
  58. pre_exec_callback: closure for setup before execution
  59. Defaults to None. Takes in the variable argument list from the
  60. execute functions and returns a modified argument list for the
  61. shell hook.
  62. post_exec_callback: closure for cleanup after execution
  63. Defaults to None. Takes in a boolean for hook success and the
  64. modified argument list and returns the final hook return value
  65. if applicable
  66. cwd: working directory to switch to when executing the hook
  67. """
  68. self.name = name
  69. self.filepath = path
  70. self.numparam = numparam
  71. self.pre_exec_callback = pre_exec_callback
  72. self.post_exec_callback = post_exec_callback
  73. self.cwd = cwd
  74. def execute(self, *args: Any) -> Any: # noqa: ANN401
  75. """Execute the hook with given args."""
  76. if len(args) != self.numparam:
  77. raise HookError(
  78. f"Hook {self.name} executed with wrong number of args. Expected {self.numparam}. Saw {len(args)}. 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(f"Hook {self.name} exited with non-zero status {ret}")
  90. if self.post_exec_callback is not None:
  91. return self.post_exec_callback(1, *args)
  92. except FileNotFoundError: # no file. silent failure.
  93. if self.post_exec_callback is not None:
  94. self.post_exec_callback(0, *args)
  95. class PreCommitShellHook(ShellHook):
  96. """pre-commit shell hook."""
  97. def __init__(self, cwd: str, controldir: str) -> None:
  98. """Initialize pre-commit hook.
  99. Args:
  100. cwd: Working directory for hook execution
  101. controldir: Path to the git control directory (.git)
  102. """
  103. filepath = os.path.join(controldir, "hooks", "pre-commit")
  104. ShellHook.__init__(self, "pre-commit", filepath, 0, cwd=cwd)
  105. class PostCommitShellHook(ShellHook):
  106. """post-commit shell hook."""
  107. def __init__(self, controldir: str) -> None:
  108. """Initialize post-commit hook.
  109. Args:
  110. controldir: Path to the git control directory (.git)
  111. """
  112. filepath = os.path.join(controldir, "hooks", "post-commit")
  113. ShellHook.__init__(self, "post-commit", filepath, 0, cwd=controldir)
  114. class CommitMsgShellHook(ShellHook):
  115. """commit-msg shell hook."""
  116. def __init__(self, controldir: str) -> None:
  117. """Initialize commit-msg hook.
  118. Args:
  119. controldir: Path to the git control directory (.git)
  120. """
  121. filepath = os.path.join(controldir, "hooks", "commit-msg")
  122. def prepare_msg(*args: bytes) -> tuple[str, ...]:
  123. import tempfile
  124. (fd, path) = tempfile.mkstemp()
  125. with os.fdopen(fd, "wb") as f:
  126. f.write(args[0])
  127. return (path,)
  128. def clean_msg(success: int, *args: str) -> bytes | None:
  129. if success:
  130. with open(args[0], "rb") as f:
  131. new_msg = f.read()
  132. os.unlink(args[0])
  133. return new_msg
  134. os.unlink(args[0])
  135. return None
  136. ShellHook.__init__(
  137. self, "commit-msg", filepath, 1, prepare_msg, clean_msg, controldir
  138. )
  139. class PostReceiveShellHook(ShellHook):
  140. """post-receive shell hook."""
  141. def __init__(self, controldir: str) -> None:
  142. """Initialize post-receive hook.
  143. Args:
  144. controldir: Path to the git control directory (.git)
  145. """
  146. self.controldir = controldir
  147. filepath = os.path.join(controldir, "hooks", "post-receive")
  148. ShellHook.__init__(self, "post-receive", path=filepath, numparam=0)
  149. def execute(
  150. self, client_refs: Sequence[tuple[bytes, bytes, bytes]]
  151. ) -> bytes | None:
  152. """Execute the post-receive hook.
  153. Args:
  154. client_refs: List of tuples containing (old_sha, new_sha, ref_name)
  155. for each updated reference
  156. Returns:
  157. Output from the hook execution or None if hook doesn't exist
  158. Raises:
  159. HookError: If hook execution fails
  160. """
  161. # do nothing if the script doesn't exist
  162. if not os.path.exists(self.filepath):
  163. return None
  164. try:
  165. env = os.environ.copy()
  166. env["GIT_DIR"] = self.controldir
  167. p = subprocess.Popen(
  168. self.filepath,
  169. stdin=subprocess.PIPE,
  170. stdout=subprocess.PIPE,
  171. stderr=subprocess.PIPE,
  172. env=env,
  173. )
  174. # client_refs is a list of (oldsha, newsha, ref)
  175. in_data = b"\n".join([b" ".join(ref) for ref in client_refs])
  176. out_data, err_data = p.communicate(in_data)
  177. if (p.returncode != 0) or err_data:
  178. err_msg = (
  179. f"post-receive exit code: {p.returncode}\n"
  180. f"stdout:\n{out_data.decode('utf-8', 'backslashreplace')}\n"
  181. f"stderr:\n{err_data.decode('utf-8', 'backslashreplace')}"
  182. )
  183. raise HookError(err_msg)
  184. return out_data
  185. except OSError as err:
  186. raise HookError(repr(err)) from err