You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

248 lines
8.5KB

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