head.py 9.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277
  1. from git.config import GitConfigParser, SectionConstraint
  2. from git.util import join_path
  3. from git.exc import GitCommandError
  4. from .symbolic import SymbolicReference
  5. from .reference import Reference
  6. # typinng ---------------------------------------------------
  7. from typing import Any, Sequence, Union, TYPE_CHECKING
  8. from git.types import PathLike, Commit_ish
  9. if TYPE_CHECKING:
  10. from git.repo import Repo
  11. from git.objects import Commit
  12. from git.refs import RemoteReference
  13. # -------------------------------------------------------------------
  14. __all__ = ["HEAD", "Head"]
  15. def strip_quotes(string: str) -> str:
  16. if string.startswith('"') and string.endswith('"'):
  17. return string[1:-1]
  18. return string
  19. class HEAD(SymbolicReference):
  20. """Special case of a Symbolic Reference as it represents the repository's
  21. HEAD reference."""
  22. _HEAD_NAME = "HEAD"
  23. _ORIG_HEAD_NAME = "ORIG_HEAD"
  24. __slots__ = ()
  25. def __init__(self, repo: "Repo", path: PathLike = _HEAD_NAME):
  26. if path != self._HEAD_NAME:
  27. raise ValueError("HEAD instance must point to %r, got %r" % (self._HEAD_NAME, path))
  28. super(HEAD, self).__init__(repo, path)
  29. self.commit: "Commit"
  30. def orig_head(self) -> SymbolicReference:
  31. """
  32. :return: SymbolicReference pointing at the ORIG_HEAD, which is maintained
  33. to contain the previous value of HEAD"""
  34. return SymbolicReference(self.repo, self._ORIG_HEAD_NAME)
  35. def reset(
  36. self,
  37. commit: Union[Commit_ish, SymbolicReference, str] = "HEAD",
  38. index: bool = True,
  39. working_tree: bool = False,
  40. paths: Union[PathLike, Sequence[PathLike], None] = None,
  41. **kwargs: Any,
  42. ) -> "HEAD":
  43. """Reset our HEAD to the given commit optionally synchronizing
  44. the index and working tree. The reference we refer to will be set to
  45. commit as well.
  46. :param commit:
  47. Commit object, Reference Object or string identifying a revision we
  48. should reset HEAD to.
  49. :param index:
  50. If True, the index will be set to match the given commit. Otherwise
  51. it will not be touched.
  52. :param working_tree:
  53. If True, the working tree will be forcefully adjusted to match the given
  54. commit, possibly overwriting uncommitted changes without warning.
  55. If working_tree is True, index must be true as well
  56. :param paths:
  57. Single path or list of paths relative to the git root directory
  58. that are to be reset. This allows to partially reset individual files.
  59. :param kwargs:
  60. Additional arguments passed to git-reset.
  61. :return: self"""
  62. mode: Union[str, None]
  63. mode = "--soft"
  64. if index:
  65. mode = "--mixed"
  66. # it appears, some git-versions declare mixed and paths deprecated
  67. # see http://github.com/Byron/GitPython/issues#issue/2
  68. if paths:
  69. mode = None
  70. # END special case
  71. # END handle index
  72. if working_tree:
  73. mode = "--hard"
  74. if not index:
  75. raise ValueError("Cannot reset the working tree if the index is not reset as well")
  76. # END working tree handling
  77. try:
  78. self.repo.git.reset(mode, commit, "--", paths, **kwargs)
  79. except GitCommandError as e:
  80. # git nowadays may use 1 as status to indicate there are still unstaged
  81. # modifications after the reset
  82. if e.status != 1:
  83. raise
  84. # END handle exception
  85. return self
  86. class Head(Reference):
  87. """A Head is a named reference to a Commit. Every Head instance contains a name
  88. and a Commit object.
  89. Examples::
  90. >>> repo = Repo("/path/to/repo")
  91. >>> head = repo.heads[0]
  92. >>> head.name
  93. 'master'
  94. >>> head.commit
  95. <git.Commit "1c09f116cbc2cb4100fb6935bb162daa4723f455">
  96. >>> head.commit.hexsha
  97. '1c09f116cbc2cb4100fb6935bb162daa4723f455'"""
  98. _common_path_default = "refs/heads"
  99. k_config_remote = "remote"
  100. k_config_remote_ref = "merge" # branch to merge from remote
  101. @classmethod
  102. def delete(cls, repo: "Repo", *heads: "Union[Head, str]", force: bool = False, **kwargs: Any) -> None:
  103. """Delete the given heads
  104. :param force:
  105. If True, the heads will be deleted even if they are not yet merged into
  106. the main development stream.
  107. Default False"""
  108. flag = "-d"
  109. if force:
  110. flag = "-D"
  111. repo.git.branch(flag, *heads)
  112. def set_tracking_branch(self, remote_reference: Union["RemoteReference", None]) -> "Head":
  113. """
  114. Configure this branch to track the given remote reference. This will alter
  115. this branch's configuration accordingly.
  116. :param remote_reference: The remote reference to track or None to untrack
  117. any references
  118. :return: self"""
  119. from .remote import RemoteReference
  120. if remote_reference is not None and not isinstance(remote_reference, RemoteReference):
  121. raise ValueError("Incorrect parameter type: %r" % remote_reference)
  122. # END handle type
  123. with self.config_writer() as writer:
  124. if remote_reference is None:
  125. writer.remove_option(self.k_config_remote)
  126. writer.remove_option(self.k_config_remote_ref)
  127. if len(writer.options()) == 0:
  128. writer.remove_section()
  129. else:
  130. writer.set_value(self.k_config_remote, remote_reference.remote_name)
  131. writer.set_value(
  132. self.k_config_remote_ref,
  133. Head.to_full_path(remote_reference.remote_head),
  134. )
  135. return self
  136. def tracking_branch(self) -> Union["RemoteReference", None]:
  137. """
  138. :return: The remote_reference we are tracking, or None if we are
  139. not a tracking branch"""
  140. from .remote import RemoteReference
  141. reader = self.config_reader()
  142. if reader.has_option(self.k_config_remote) and reader.has_option(self.k_config_remote_ref):
  143. ref = Head(
  144. self.repo,
  145. Head.to_full_path(strip_quotes(reader.get_value(self.k_config_remote_ref))),
  146. )
  147. remote_refpath = RemoteReference.to_full_path(join_path(reader.get_value(self.k_config_remote), ref.name))
  148. return RemoteReference(self.repo, remote_refpath)
  149. # END handle have tracking branch
  150. # we are not a tracking branch
  151. return None
  152. def rename(self, new_path: PathLike, force: bool = False) -> "Head":
  153. """Rename self to a new path
  154. :param new_path:
  155. Either a simple name or a path, i.e. new_name or features/new_name.
  156. The prefix refs/heads is implied
  157. :param force:
  158. If True, the rename will succeed even if a head with the target name
  159. already exists.
  160. :return: self
  161. :note: respects the ref log as git commands are used"""
  162. flag = "-m"
  163. if force:
  164. flag = "-M"
  165. self.repo.git.branch(flag, self, new_path)
  166. self.path = "%s/%s" % (self._common_path_default, new_path)
  167. return self
  168. def checkout(self, force: bool = False, **kwargs: Any) -> Union["HEAD", "Head"]:
  169. """Checkout this head by setting the HEAD to this reference, by updating the index
  170. to reflect the tree we point to and by updating the working tree to reflect
  171. the latest index.
  172. The command will fail if changed working tree files would be overwritten.
  173. :param force:
  174. If True, changes to the index and the working tree will be discarded.
  175. If False, GitCommandError will be raised in that situation.
  176. :param kwargs:
  177. Additional keyword arguments to be passed to git checkout, i.e.
  178. b='new_branch' to create a new branch at the given spot.
  179. :return:
  180. The active branch after the checkout operation, usually self unless
  181. a new branch has been created.
  182. If there is no active branch, as the HEAD is now detached, the HEAD
  183. reference will be returned instead.
  184. :note:
  185. By default it is only allowed to checkout heads - everything else
  186. will leave the HEAD detached which is allowed and possible, but remains
  187. a special state that some tools might not be able to handle."""
  188. kwargs["f"] = force
  189. if kwargs["f"] is False:
  190. kwargs.pop("f")
  191. self.repo.git.checkout(self, **kwargs)
  192. if self.repo.head.is_detached:
  193. return self.repo.head
  194. else:
  195. return self.repo.active_branch
  196. # { Configuration
  197. def _config_parser(self, read_only: bool) -> SectionConstraint[GitConfigParser]:
  198. if read_only:
  199. parser = self.repo.config_reader()
  200. else:
  201. parser = self.repo.config_writer()
  202. # END handle parser instance
  203. return SectionConstraint(parser, 'branch "%s"' % self.name)
  204. def config_reader(self) -> SectionConstraint[GitConfigParser]:
  205. """
  206. :return: A configuration parser instance constrained to only read
  207. this instance's values"""
  208. return self._config_parser(read_only=True)
  209. def config_writer(self) -> SectionConstraint[GitConfigParser]:
  210. """
  211. :return: A configuration writer instance with read-and write access
  212. to options of this head"""
  213. return self._config_parser(read_only=False)
  214. # } END configuration