util.py 3.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121
  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__ = [
  4. "sm_section",
  5. "sm_name",
  6. "mkhead",
  7. "find_first_remote_branch",
  8. "SubmoduleConfigParser",
  9. ]
  10. from io import BytesIO
  11. import weakref
  12. import git
  13. from git.config import GitConfigParser
  14. from git.exc import InvalidGitRepositoryError
  15. # typing -----------------------------------------------------------------------
  16. from typing import Any, Sequence, TYPE_CHECKING, Union
  17. from git.types import PathLike
  18. if TYPE_CHECKING:
  19. from weakref import ReferenceType
  20. from git.refs import Head, RemoteReference
  21. from git.remote import Remote
  22. from git.repo import Repo
  23. from .base import Submodule
  24. # { Utilities
  25. def sm_section(name: str) -> str:
  26. """:return: Section title used in ``.gitmodules`` configuration file"""
  27. return f'submodule "{name}"'
  28. def sm_name(section: str) -> str:
  29. """:return: Name of the submodule as parsed from the section name"""
  30. section = section.strip()
  31. return section[11:-1]
  32. def mkhead(repo: "Repo", path: PathLike) -> "Head":
  33. """:return: New branch/head instance"""
  34. return git.Head(repo, git.Head.to_full_path(path))
  35. def find_first_remote_branch(remotes: Sequence["Remote"], branch_name: str) -> "RemoteReference":
  36. """Find the remote branch matching the name of the given branch or raise
  37. :exc:`~git.exc.InvalidGitRepositoryError`."""
  38. for remote in remotes:
  39. try:
  40. return remote.refs[branch_name]
  41. except IndexError:
  42. continue
  43. # END exception handling
  44. # END for remote
  45. raise InvalidGitRepositoryError("Didn't find remote branch '%r' in any of the given remotes" % branch_name)
  46. # } END utilities
  47. # { Classes
  48. class SubmoduleConfigParser(GitConfigParser):
  49. """Catches calls to :meth:`~git.config.GitConfigParser.write`, and updates the
  50. ``.gitmodules`` blob in the index with the new data, if we have written into a
  51. stream.
  52. Otherwise it would add the local file to the index to make it correspond with the
  53. working tree. Additionally, the cache must be cleared.
  54. Please note that no mutating method will work in bare mode.
  55. """
  56. def __init__(self, *args: Any, **kwargs: Any) -> None:
  57. self._smref: Union["ReferenceType[Submodule]", None] = None
  58. self._index = None
  59. self._auto_write = True
  60. super().__init__(*args, **kwargs)
  61. # { Interface
  62. def set_submodule(self, submodule: "Submodule") -> None:
  63. """Set this instance's submodule. It must be called before the first write
  64. operation begins."""
  65. self._smref = weakref.ref(submodule)
  66. def flush_to_index(self) -> None:
  67. """Flush changes in our configuration file to the index."""
  68. assert self._smref is not None
  69. # Should always have a file here.
  70. assert not isinstance(self._file_or_files, BytesIO)
  71. sm = self._smref()
  72. if sm is not None:
  73. index = self._index
  74. if index is None:
  75. index = sm.repo.index
  76. # END handle index
  77. index.add([sm.k_modules_file], write=self._auto_write)
  78. sm._clear_cache()
  79. # END handle weakref
  80. # } END interface
  81. # { Overridden Methods
  82. def write(self) -> None: # type: ignore[override]
  83. rval: None = super().write()
  84. self.flush_to_index()
  85. return rval
  86. # END overridden methods
  87. # } END classes