exc.py 7.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228
  1. # Copyright (C) 2008, 2009 Michael Trier (mtrier@gmail.com) and contributors
  2. #
  3. # This module is part of GitPython and is released under the
  4. # 3-Clause BSD License: https://opensource.org/license/bsd-3-clause/
  5. """Exceptions thrown throughout the git package."""
  6. __all__ = [
  7. # Defined in gitdb.exc:
  8. "AmbiguousObjectName",
  9. "BadName",
  10. "BadObject",
  11. "BadObjectType",
  12. "InvalidDBRoot",
  13. "ODBError",
  14. "ParseError",
  15. "UnsupportedOperation",
  16. # Introduced in this module:
  17. "GitError",
  18. "InvalidGitRepositoryError",
  19. "WorkTreeRepositoryUnsupported",
  20. "NoSuchPathError",
  21. "UnsafeProtocolError",
  22. "UnsafeOptionError",
  23. "CommandError",
  24. "GitCommandNotFound",
  25. "GitCommandError",
  26. "CheckoutError",
  27. "CacheError",
  28. "UnmergedEntriesError",
  29. "HookExecutionError",
  30. "RepositoryDirtyError",
  31. ]
  32. from gitdb.exc import (
  33. AmbiguousObjectName,
  34. BadName,
  35. BadObject,
  36. BadObjectType,
  37. InvalidDBRoot,
  38. ODBError,
  39. ParseError,
  40. UnsupportedOperation,
  41. )
  42. from git.compat import safe_decode
  43. from git.util import remove_password_if_present
  44. # typing ----------------------------------------------------
  45. from typing import List, Sequence, Tuple, TYPE_CHECKING, Union
  46. from git.types import PathLike
  47. if TYPE_CHECKING:
  48. from git.repo.base import Repo
  49. # ------------------------------------------------------------------
  50. class GitError(Exception):
  51. """Base class for all package exceptions."""
  52. class InvalidGitRepositoryError(GitError):
  53. """Thrown if the given repository appears to have an invalid format."""
  54. class WorkTreeRepositoryUnsupported(InvalidGitRepositoryError):
  55. """Thrown to indicate we can't handle work tree repositories."""
  56. class NoSuchPathError(GitError, OSError):
  57. """Thrown if a path could not be access by the system."""
  58. class UnsafeProtocolError(GitError):
  59. """Thrown if unsafe protocols are passed without being explicitly allowed."""
  60. class UnsafeOptionError(GitError):
  61. """Thrown if unsafe options are passed without being explicitly allowed."""
  62. class CommandError(GitError):
  63. """Base class for exceptions thrown at every stage of :class:`~subprocess.Popen`
  64. execution.
  65. :param command:
  66. A non-empty list of argv comprising the command-line.
  67. """
  68. _msg = "Cmd('%s') failed%s"
  69. """Format string with 2 ``%s`` for ``<cmdline>`` and the rest.
  70. For example: ``"'%s' failed%s"``
  71. Subclasses may override this attribute, provided it is still in this form.
  72. """
  73. def __init__(
  74. self,
  75. command: Union[List[str], Tuple[str, ...], str],
  76. status: Union[str, int, None, Exception] = None,
  77. stderr: Union[bytes, str, None] = None,
  78. stdout: Union[bytes, str, None] = None,
  79. ) -> None:
  80. if not isinstance(command, (tuple, list)):
  81. command = command.split()
  82. self.command = remove_password_if_present(command)
  83. self.status = status
  84. if status:
  85. if isinstance(status, Exception):
  86. status = "%s('%s')" % (type(status).__name__, safe_decode(str(status)))
  87. else:
  88. try:
  89. status = "exit code(%s)" % int(status)
  90. except (ValueError, TypeError):
  91. s = safe_decode(str(status))
  92. status = "'%s'" % s if isinstance(status, str) else s
  93. self._cmd = safe_decode(self.command[0])
  94. self._cmdline = " ".join(safe_decode(i) for i in self.command)
  95. self._cause = status and " due to: %s" % status or "!"
  96. stdout_decode = safe_decode(stdout)
  97. stderr_decode = safe_decode(stderr)
  98. self.stdout = stdout_decode and "\n stdout: '%s'" % stdout_decode or ""
  99. self.stderr = stderr_decode and "\n stderr: '%s'" % stderr_decode or ""
  100. def __str__(self) -> str:
  101. return (self._msg + "\n cmdline: %s%s%s") % (
  102. self._cmd,
  103. self._cause,
  104. self._cmdline,
  105. self.stdout,
  106. self.stderr,
  107. )
  108. class GitCommandNotFound(CommandError):
  109. """Thrown if we cannot find the ``git`` executable in the :envvar:`PATH` or at the
  110. path given by the :envvar:`GIT_PYTHON_GIT_EXECUTABLE` environment variable."""
  111. def __init__(self, command: Union[List[str], Tuple[str], str], cause: Union[str, Exception]) -> None:
  112. super().__init__(command, cause)
  113. self._msg = "Cmd('%s') not found%s"
  114. class GitCommandError(CommandError):
  115. """Thrown if execution of the git command fails with non-zero status code."""
  116. def __init__(
  117. self,
  118. command: Union[List[str], Tuple[str, ...], str],
  119. status: Union[str, int, None, Exception] = None,
  120. stderr: Union[bytes, str, None] = None,
  121. stdout: Union[bytes, str, None] = None,
  122. ) -> None:
  123. super().__init__(command, status, stderr, stdout)
  124. class CheckoutError(GitError):
  125. """Thrown if a file could not be checked out from the index as it contained
  126. changes.
  127. The :attr:`failed_files` attribute contains a list of relative paths that failed to
  128. be checked out as they contained changes that did not exist in the index.
  129. The :attr:`failed_reasons` attribute contains a string informing about the actual
  130. cause of the issue.
  131. The :attr:`valid_files` attribute contains a list of relative paths to files that
  132. were checked out successfully and hence match the version stored in the index.
  133. """
  134. def __init__(
  135. self,
  136. message: str,
  137. failed_files: Sequence[PathLike],
  138. valid_files: Sequence[PathLike],
  139. failed_reasons: List[str],
  140. ) -> None:
  141. Exception.__init__(self, message)
  142. self.failed_files = failed_files
  143. self.failed_reasons = failed_reasons
  144. self.valid_files = valid_files
  145. def __str__(self) -> str:
  146. return Exception.__str__(self) + ":%s" % self.failed_files
  147. class CacheError(GitError):
  148. """Base for all errors related to the git index, which is called "cache"
  149. internally."""
  150. class UnmergedEntriesError(CacheError):
  151. """Thrown if an operation cannot proceed as there are still unmerged
  152. entries in the cache."""
  153. class HookExecutionError(CommandError):
  154. """Thrown if a hook exits with a non-zero exit code.
  155. This provides access to the exit code and the string returned via standard output.
  156. """
  157. def __init__(
  158. self,
  159. command: Union[List[str], Tuple[str, ...], str],
  160. status: Union[str, int, None, Exception],
  161. stderr: Union[bytes, str, None] = None,
  162. stdout: Union[bytes, str, None] = None,
  163. ) -> None:
  164. super().__init__(command, status, stderr, stdout)
  165. self._msg = "Hook('%s') failed%s"
  166. class RepositoryDirtyError(GitError):
  167. """Thrown whenever an operation on a repository fails as it has uncommitted changes
  168. that would be overwritten."""
  169. def __init__(self, repo: "Repo", message: str) -> None:
  170. self.repo = repo
  171. self.message = message
  172. def __str__(self) -> str:
  173. return "Operation cannot be performed on %r: %s" % (self.repo, self.message)