hooks.py 6.6 KB

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