remote.py 2.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  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. """Module implementing a remote object allowing easy access to git remotes."""
  4. __all__ = ["RemoteReference"]
  5. import os
  6. from git.util import join_path
  7. from .head import Head
  8. # typing ------------------------------------------------------------------
  9. from typing import Any, Iterator, NoReturn, TYPE_CHECKING, Union
  10. from git.types import PathLike
  11. if TYPE_CHECKING:
  12. from git.remote import Remote
  13. from git.repo import Repo
  14. # ------------------------------------------------------------------------------
  15. class RemoteReference(Head):
  16. """A reference pointing to a remote head."""
  17. _common_path_default = Head._remote_common_path_default
  18. @classmethod
  19. def iter_items(
  20. cls,
  21. repo: "Repo",
  22. common_path: Union[PathLike, None] = None,
  23. remote: Union["Remote", None] = None,
  24. *args: Any,
  25. **kwargs: Any,
  26. ) -> Iterator["RemoteReference"]:
  27. """Iterate remote references, and if given, constrain them to the given remote."""
  28. common_path = common_path or cls._common_path_default
  29. if remote is not None:
  30. common_path = join_path(common_path, str(remote))
  31. # END handle remote constraint
  32. # super is Reference
  33. return super().iter_items(repo, common_path)
  34. # The Head implementation of delete also accepts strs, but this implementation does
  35. # not. mypy doesn't have a way of representing tightening the types of arguments in
  36. # subclasses and recommends Any or "type: ignore".
  37. # (See: https://github.com/python/typing/issues/241)
  38. @classmethod
  39. def delete(cls, repo: "Repo", *refs: "RemoteReference", **kwargs: Any) -> None: # type: ignore[override]
  40. """Delete the given remote references.
  41. :note:
  42. `kwargs` are given for comparability with the base class method as we
  43. should not narrow the signature.
  44. """
  45. repo.git.branch("-d", "-r", *refs)
  46. # The official deletion method will ignore remote symbolic refs - these are
  47. # generally ignored in the refs/ folder. We don't though and delete remainders
  48. # manually.
  49. for ref in refs:
  50. try:
  51. os.remove(os.path.join(repo.common_dir, ref.path))
  52. except OSError:
  53. pass
  54. try:
  55. os.remove(os.path.join(repo.git_dir, ref.path))
  56. except OSError:
  57. pass
  58. # END for each ref
  59. @classmethod
  60. def create(cls, *args: Any, **kwargs: Any) -> NoReturn:
  61. """Raise :exc:`TypeError`. Defined so the ``create`` method is disabled."""
  62. raise TypeError("Cannot explicitly create remote references")