reference.py 5.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177
  1. # This module is part of GitPython and is released under the
  2. # 3-Clause BSD License: https://opensource.org/license/bsd-3-clause/
  3. __all__ = ["Reference"]
  4. import os
  5. from git.util import IterableObj, LazyMixin
  6. from .symbolic import SymbolicReference, T_References
  7. # typing ------------------------------------------------------------------
  8. from typing import Any, Callable, Iterator, TYPE_CHECKING, Type, Union
  9. from git.types import AnyGitObject, PathLike, _T
  10. if TYPE_CHECKING:
  11. from git.repo import Repo
  12. # ------------------------------------------------------------------------------
  13. # { Utilities
  14. def require_remote_ref_path(func: Callable[..., _T]) -> Callable[..., _T]:
  15. """A decorator raising :exc:`ValueError` if we are not a valid remote, based on the
  16. path."""
  17. def wrapper(self: T_References, *args: Any) -> _T:
  18. if not self.is_remote():
  19. raise ValueError("ref path does not point to a remote reference: %s" % self.path)
  20. return func(self, *args)
  21. # END wrapper
  22. wrapper.__name__ = func.__name__
  23. return wrapper
  24. # } END utilities
  25. class Reference(SymbolicReference, LazyMixin, IterableObj):
  26. """A named reference to any object.
  27. Subclasses may apply restrictions though, e.g., a :class:`~git.refs.head.Head` can
  28. only point to commits.
  29. """
  30. __slots__ = ()
  31. _points_to_commits_only = False
  32. _resolve_ref_on_create = True
  33. _common_path_default = "refs"
  34. def __init__(self, repo: "Repo", path: PathLike, check_path: bool = True) -> None:
  35. """Initialize this instance.
  36. :param repo:
  37. Our parent repository.
  38. :param path:
  39. Path relative to the ``.git/`` directory pointing to the ref in question,
  40. e.g. ``refs/heads/master``.
  41. :param check_path:
  42. If ``False``, you can provide any path.
  43. Otherwise the path must start with the default path prefix of this type.
  44. """
  45. if check_path and not os.fspath(path).startswith(self._common_path_default + "/"):
  46. raise ValueError(f"Cannot instantiate {self.__class__.__name__!r} from path {path}")
  47. self.path: str # SymbolicReference converts to string at the moment.
  48. super().__init__(repo, path)
  49. def __str__(self) -> str:
  50. return self.name
  51. # { Interface
  52. # @ReservedAssignment
  53. def set_object(
  54. self,
  55. object: Union[AnyGitObject, "SymbolicReference", str],
  56. logmsg: Union[str, None] = None,
  57. ) -> "Reference":
  58. """Special version which checks if the head-log needs an update as well.
  59. :return:
  60. self
  61. """
  62. oldbinsha = None
  63. if logmsg is not None:
  64. head = self.repo.head
  65. if not head.is_detached and head.ref == self:
  66. oldbinsha = self.commit.binsha
  67. # END handle commit retrieval
  68. # END handle message is set
  69. super().set_object(object, logmsg)
  70. if oldbinsha is not None:
  71. # From refs/files-backend.c in git-source:
  72. # /*
  73. # * Special hack: If a branch is updated directly and HEAD
  74. # * points to it (may happen on the remote side of a push
  75. # * for example) then logically the HEAD reflog should be
  76. # * updated too.
  77. # * A generic solution implies reverse symref information,
  78. # * but finding all symrefs pointing to the given branch
  79. # * would be rather costly for this rare event (the direct
  80. # * update of a branch) to be worth it. So let's cheat and
  81. # * check with HEAD only which should cover 99% of all usage
  82. # * scenarios (even 100% of the default ones).
  83. # */
  84. self.repo.head.log_append(oldbinsha, logmsg)
  85. # END check if the head
  86. return self
  87. # NOTE: No need to overwrite properties, as the will only work without a the log.
  88. @property
  89. def name(self) -> str:
  90. """
  91. :return:
  92. (shortest) Name of this reference - it may contain path components
  93. """
  94. # The first two path tokens can be removed as they are
  95. # refs/heads or refs/tags or refs/remotes.
  96. tokens = self.path.split("/")
  97. if len(tokens) < 3:
  98. return self.path # could be refs/HEAD
  99. return "/".join(tokens[2:])
  100. @classmethod
  101. def iter_items(
  102. cls: Type[T_References],
  103. repo: "Repo",
  104. common_path: Union[PathLike, None] = None,
  105. *args: Any,
  106. **kwargs: Any,
  107. ) -> Iterator[T_References]:
  108. """Equivalent to
  109. :meth:`SymbolicReference.iter_items <git.refs.symbolic.SymbolicReference.iter_items>`,
  110. but will return non-detached references as well."""
  111. return cls._iter_items(repo, common_path)
  112. # } END interface
  113. # { Remote Interface
  114. @property
  115. @require_remote_ref_path
  116. def remote_name(self) -> str:
  117. """
  118. :return:
  119. Name of the remote we are a reference of, such as ``origin`` for a reference
  120. named ``origin/master``.
  121. """
  122. tokens = self.path.split("/")
  123. # /refs/remotes/<remote name>/<branch_name>
  124. return tokens[2]
  125. @property
  126. @require_remote_ref_path
  127. def remote_head(self) -> str:
  128. """
  129. :return:
  130. Name of the remote head itself, e.g. ``master``.
  131. :note:
  132. The returned name is usually not qualified enough to uniquely identify a
  133. branch.
  134. """
  135. tokens = self.path.split("/")
  136. return "/".join(tokens[3:])
  137. # } END remote interface