base.py 63 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642
  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__ = ["Submodule", "UpdateProgress"]
  4. import gc
  5. from io import BytesIO
  6. import logging
  7. import os
  8. import os.path as osp
  9. import stat
  10. import sys
  11. import uuid
  12. import urllib
  13. import git
  14. from git.cmd import Git
  15. from git.compat import defenc
  16. from git.config import GitConfigParser, SectionConstraint, cp
  17. from git.exc import (
  18. BadName,
  19. InvalidGitRepositoryError,
  20. NoSuchPathError,
  21. RepositoryDirtyError,
  22. )
  23. from git.objects.base import IndexObject, Object
  24. from git.objects.util import TraversableIterableObj
  25. from git.util import (
  26. IterableList,
  27. RemoteProgress,
  28. join_path_native,
  29. rmtree,
  30. to_native_path_linux,
  31. unbare_repo,
  32. )
  33. from .util import (
  34. SubmoduleConfigParser,
  35. find_first_remote_branch,
  36. mkhead,
  37. sm_name,
  38. sm_section,
  39. )
  40. # typing ----------------------------------------------------------------------
  41. from typing import (
  42. Any,
  43. Callable,
  44. Dict,
  45. Iterator,
  46. Mapping,
  47. Sequence,
  48. TYPE_CHECKING,
  49. Union,
  50. cast,
  51. )
  52. if sys.version_info >= (3, 8):
  53. from typing import Literal
  54. else:
  55. from typing_extensions import Literal
  56. from git.types import Commit_ish, PathLike, TBD
  57. if TYPE_CHECKING:
  58. from git.index import IndexFile
  59. from git.objects.commit import Commit
  60. from git.refs import Head, RemoteReference
  61. from git.repo import Repo
  62. # -----------------------------------------------------------------------------
  63. _logger = logging.getLogger(__name__)
  64. class UpdateProgress(RemoteProgress):
  65. """Class providing detailed progress information to the caller who should
  66. derive from it and implement the
  67. :meth:`update(...) <git.util.RemoteProgress.update>` message."""
  68. CLONE, FETCH, UPDWKTREE = [1 << x for x in range(RemoteProgress._num_op_codes, RemoteProgress._num_op_codes + 3)]
  69. _num_op_codes: int = RemoteProgress._num_op_codes + 3
  70. __slots__ = ()
  71. BEGIN = UpdateProgress.BEGIN
  72. END = UpdateProgress.END
  73. CLONE = UpdateProgress.CLONE
  74. FETCH = UpdateProgress.FETCH
  75. UPDWKTREE = UpdateProgress.UPDWKTREE
  76. # IndexObject comes via the util module. It's a 'hacky' fix thanks to Python's import
  77. # mechanism, which causes plenty of trouble if the only reason for packages and modules
  78. # is refactoring - subpackages shouldn't depend on parent packages.
  79. class Submodule(IndexObject, TraversableIterableObj):
  80. """Implements access to a git submodule. They are special in that their sha
  81. represents a commit in the submodule's repository which is to be checked out
  82. at the path of this instance.
  83. The submodule type does not have a string type associated with it, as it exists
  84. solely as a marker in the tree and index.
  85. All methods work in bare and non-bare repositories.
  86. """
  87. _id_attribute_ = "name"
  88. k_modules_file = ".gitmodules"
  89. k_head_option = "branch"
  90. k_head_default = "master"
  91. k_default_mode = stat.S_IFDIR | stat.S_IFLNK
  92. """Submodule flags. Submodules are directories with link-status."""
  93. type: Literal["submodule"] = "submodule" # type: ignore[assignment]
  94. """This is a bogus type string for base class compatibility."""
  95. __slots__ = ("_parent_commit", "_url", "_branch_path", "_name", "__weakref__")
  96. _cache_attrs = ("path", "_url", "_branch_path")
  97. def __init__(
  98. self,
  99. repo: "Repo",
  100. binsha: bytes,
  101. mode: Union[int, None] = None,
  102. path: Union[PathLike, None] = None,
  103. name: Union[str, None] = None,
  104. parent_commit: Union["Commit", None] = None,
  105. url: Union[str, None] = None,
  106. branch_path: Union[PathLike, None] = None,
  107. ) -> None:
  108. """Initialize this instance with its attributes.
  109. We only document the parameters that differ from
  110. :class:`~git.objects.base.IndexObject`.
  111. :param repo:
  112. Our parent repository.
  113. :param binsha:
  114. Binary sha referring to a commit in the remote repository.
  115. See the `url` parameter.
  116. :param parent_commit:
  117. The :class:`~git.objects.commit.Commit` whose tree is supposed to contain
  118. the ``.gitmodules`` blob, or ``None`` to always point to the most recent
  119. commit. See :meth:`set_parent_commit` for details.
  120. :param url:
  121. The URL to the remote repository which is the submodule.
  122. :param branch_path:
  123. Full repository-relative path to ref to checkout when cloning the remote
  124. repository.
  125. """
  126. super().__init__(repo, binsha, mode, path)
  127. self.size = 0
  128. self._parent_commit = parent_commit
  129. if url is not None:
  130. self._url = url
  131. if branch_path is not None:
  132. self._branch_path = branch_path
  133. if name is not None:
  134. self._name = name
  135. def _set_cache_(self, attr: str) -> None:
  136. if attr in ("path", "_url", "_branch_path"):
  137. reader: SectionConstraint = self.config_reader()
  138. # Default submodule values.
  139. try:
  140. self.path = reader.get("path")
  141. except cp.NoSectionError as e:
  142. if self.repo.working_tree_dir is not None:
  143. raise ValueError(
  144. "This submodule instance does not exist anymore in '%s' file"
  145. % osp.join(self.repo.working_tree_dir, ".gitmodules")
  146. ) from e
  147. self._url = reader.get("url")
  148. # GitPython extension values - optional.
  149. self._branch_path = reader.get_value(self.k_head_option, git.Head.to_full_path(self.k_head_default))
  150. elif attr == "_name":
  151. raise AttributeError("Cannot retrieve the name of a submodule if it was not set initially")
  152. else:
  153. super()._set_cache_(attr)
  154. # END handle attribute name
  155. @classmethod
  156. def _get_intermediate_items(cls, item: "Submodule") -> IterableList["Submodule"]:
  157. """:return: All the submodules of our module repository"""
  158. try:
  159. return cls.list_items(item.module())
  160. except InvalidGitRepositoryError:
  161. return IterableList("")
  162. # END handle intermediate items
  163. @classmethod
  164. def _need_gitfile_submodules(cls, git: Git) -> bool:
  165. return git.version_info[:3] >= (1, 7, 5)
  166. def __eq__(self, other: Any) -> bool:
  167. """Compare with another submodule."""
  168. # We may only compare by name as this should be the ID they are hashed with.
  169. # Otherwise this type wouldn't be hashable.
  170. # return self.path == other.path and self.url == other.url and super().__eq__(other)
  171. return self._name == other._name
  172. def __ne__(self, other: object) -> bool:
  173. """Compare with another submodule for inequality."""
  174. return not (self == other)
  175. def __hash__(self) -> int:
  176. """Hash this instance using its logical id, not the sha."""
  177. return hash(self._name)
  178. def __str__(self) -> str:
  179. return self._name
  180. def __repr__(self) -> str:
  181. return "git.%s(name=%s, path=%s, url=%s, branch_path=%s)" % (
  182. type(self).__name__,
  183. self._name,
  184. self.path,
  185. self.url,
  186. self.branch_path,
  187. )
  188. @classmethod
  189. def _config_parser(
  190. cls, repo: "Repo", parent_commit: Union["Commit", None], read_only: bool
  191. ) -> SubmoduleConfigParser:
  192. """
  193. :return:
  194. Config parser constrained to our submodule in read or write mode
  195. :raise IOError:
  196. If the ``.gitmodules`` file cannot be found, either locally or in the
  197. repository at the given parent commit. Otherwise the exception would be
  198. delayed until the first access of the config parser.
  199. """
  200. parent_matches_head = True
  201. if parent_commit is not None:
  202. try:
  203. parent_matches_head = repo.head.commit == parent_commit
  204. except ValueError:
  205. # We are most likely in an empty repository, so the HEAD doesn't point
  206. # to a valid ref.
  207. pass
  208. # END handle parent_commit
  209. fp_module: Union[str, BytesIO]
  210. if not repo.bare and parent_matches_head and repo.working_tree_dir:
  211. fp_module = osp.join(repo.working_tree_dir, cls.k_modules_file)
  212. else:
  213. assert parent_commit is not None, "need valid parent_commit in bare repositories"
  214. try:
  215. fp_module = cls._sio_modules(parent_commit)
  216. except KeyError as e:
  217. raise IOError(
  218. "Could not find %s file in the tree of parent commit %s" % (cls.k_modules_file, parent_commit)
  219. ) from e
  220. # END handle exceptions
  221. # END handle non-bare working tree
  222. if not read_only and (repo.bare or not parent_matches_head):
  223. raise ValueError("Cannot write blobs of 'historical' submodule configurations")
  224. # END handle writes of historical submodules
  225. return SubmoduleConfigParser(fp_module, read_only=read_only)
  226. def _clear_cache(self) -> None:
  227. """Clear the possibly changed values."""
  228. for name in self._cache_attrs:
  229. try:
  230. delattr(self, name)
  231. except AttributeError:
  232. pass
  233. # END try attr deletion
  234. # END for each name to delete
  235. @classmethod
  236. def _sio_modules(cls, parent_commit: "Commit") -> BytesIO:
  237. """
  238. :return:
  239. Configuration file as :class:`~io.BytesIO` - we only access it through the
  240. respective blob's data
  241. """
  242. sio = BytesIO(parent_commit.tree[cls.k_modules_file].data_stream.read())
  243. sio.name = cls.k_modules_file
  244. return sio
  245. def _config_parser_constrained(self, read_only: bool) -> SectionConstraint:
  246. """:return: Config parser constrained to our submodule in read or write mode"""
  247. try:
  248. pc = self.parent_commit
  249. except ValueError:
  250. pc = None
  251. # END handle empty parent repository
  252. parser = self._config_parser(self.repo, pc, read_only)
  253. parser.set_submodule(self)
  254. return SectionConstraint(parser, sm_section(self.name))
  255. @classmethod
  256. def _module_abspath(cls, parent_repo: "Repo", path: PathLike, name: str) -> PathLike:
  257. if cls._need_gitfile_submodules(parent_repo.git):
  258. return osp.join(parent_repo.git_dir, "modules", name)
  259. if parent_repo.working_tree_dir:
  260. return osp.join(parent_repo.working_tree_dir, path)
  261. raise NotADirectoryError()
  262. @classmethod
  263. def _clone_repo(
  264. cls,
  265. repo: "Repo",
  266. url: str,
  267. path: PathLike,
  268. name: str,
  269. allow_unsafe_options: bool = False,
  270. allow_unsafe_protocols: bool = False,
  271. **kwargs: Any,
  272. ) -> "Repo":
  273. """
  274. :return:
  275. :class:`~git.repo.base.Repo` instance of newly cloned repository.
  276. :param repo:
  277. Our parent repository.
  278. :param url:
  279. URL to clone from.
  280. :param path:
  281. Repository-relative path to the submodule checkout location.
  282. :param name:
  283. Canonical name of the submodule.
  284. :param allow_unsafe_protocols:
  285. Allow unsafe protocols to be used, like ``ext``.
  286. :param allow_unsafe_options:
  287. Allow unsafe options to be used, like ``--upload-pack``.
  288. :param kwargs:
  289. Additional arguments given to :manpage:`git-clone(1)`.
  290. """
  291. module_abspath = cls._module_abspath(repo, path, name)
  292. module_checkout_path = module_abspath
  293. if cls._need_gitfile_submodules(repo.git):
  294. kwargs["separate_git_dir"] = module_abspath
  295. module_abspath_dir = osp.dirname(module_abspath)
  296. if not osp.isdir(module_abspath_dir):
  297. os.makedirs(module_abspath_dir)
  298. module_checkout_path = osp.join(repo.working_tree_dir, path) # type: ignore[arg-type]
  299. if url.startswith("../"):
  300. remote_name = cast("RemoteReference", repo.active_branch.tracking_branch()).remote_name
  301. repo_remote_url = repo.remote(remote_name).url
  302. url = os.path.join(repo_remote_url, url)
  303. clone = git.Repo.clone_from(
  304. url,
  305. module_checkout_path,
  306. allow_unsafe_options=allow_unsafe_options,
  307. allow_unsafe_protocols=allow_unsafe_protocols,
  308. **kwargs,
  309. )
  310. if cls._need_gitfile_submodules(repo.git):
  311. cls._write_git_file_and_module_config(module_checkout_path, module_abspath)
  312. return clone
  313. @classmethod
  314. def _to_relative_path(cls, parent_repo: "Repo", path: PathLike) -> PathLike:
  315. """:return: A path guaranteed to be relative to the given parent repository
  316. :raise ValueError:
  317. If path is not contained in the parent repository's working tree.
  318. """
  319. path = to_native_path_linux(path)
  320. if path.endswith("/"):
  321. path = path[:-1]
  322. # END handle trailing slash
  323. if osp.isabs(path) and parent_repo.working_tree_dir:
  324. working_tree_linux = to_native_path_linux(parent_repo.working_tree_dir)
  325. if not path.startswith(working_tree_linux):
  326. raise ValueError(
  327. "Submodule checkout path '%s' needs to be within the parents repository at '%s'"
  328. % (working_tree_linux, path)
  329. )
  330. path = path[len(working_tree_linux.rstrip("/")) + 1 :]
  331. if not path:
  332. raise ValueError("Absolute submodule path '%s' didn't yield a valid relative path" % path)
  333. # END verify converted relative path makes sense
  334. # END convert to a relative path
  335. return path
  336. @classmethod
  337. def _write_git_file_and_module_config(cls, working_tree_dir: PathLike, module_abspath: PathLike) -> None:
  338. """Write a ``.git`` file containing a (preferably) relative path to the actual
  339. git module repository.
  340. It is an error if the `module_abspath` cannot be made into a relative path,
  341. relative to the `working_tree_dir`.
  342. :note:
  343. This will overwrite existing files!
  344. :note:
  345. As we rewrite both the git file as well as the module configuration, we
  346. might fail on the configuration and will not roll back changes done to the
  347. git file. This should be a non-issue, but may easily be fixed if it becomes
  348. one.
  349. :param working_tree_dir:
  350. Directory to write the ``.git`` file into.
  351. :param module_abspath:
  352. Absolute path to the bare repository.
  353. """
  354. git_file = osp.join(working_tree_dir, ".git")
  355. rela_path = osp.relpath(module_abspath, start=working_tree_dir)
  356. if sys.platform == "win32" and osp.isfile(git_file):
  357. os.remove(git_file)
  358. with open(git_file, "wb") as fp:
  359. fp.write(("gitdir: %s" % rela_path).encode(defenc))
  360. with GitConfigParser(osp.join(module_abspath, "config"), read_only=False, merge_includes=False) as writer:
  361. writer.set_value(
  362. "core",
  363. "worktree",
  364. to_native_path_linux(osp.relpath(working_tree_dir, start=module_abspath)),
  365. )
  366. # { Edit Interface
  367. @classmethod
  368. def add(
  369. cls,
  370. repo: "Repo",
  371. name: str,
  372. path: PathLike,
  373. url: Union[str, None] = None,
  374. branch: Union[str, None] = None,
  375. no_checkout: bool = False,
  376. depth: Union[int, None] = None,
  377. env: Union[Mapping[str, str], None] = None,
  378. clone_multi_options: Union[Sequence[TBD], None] = None,
  379. allow_unsafe_options: bool = False,
  380. allow_unsafe_protocols: bool = False,
  381. ) -> "Submodule":
  382. """Add a new submodule to the given repository. This will alter the index as
  383. well as the ``.gitmodules`` file, but will not create a new commit. If the
  384. submodule already exists, no matter if the configuration differs from the one
  385. provided, the existing submodule will be returned.
  386. :param repo:
  387. Repository instance which should receive the submodule.
  388. :param name:
  389. The name/identifier for the submodule.
  390. :param path:
  391. Repository-relative or absolute path at which the submodule should be
  392. located.
  393. It will be created as required during the repository initialization.
  394. :param url:
  395. ``git clone ...``-compatible URL. See :manpage:`git-clone(1)` for more
  396. information. If ``None``, the repository is assumed to exist, and the URL of
  397. the first remote is taken instead. This is useful if you want to make an
  398. existing repository a submodule of another one.
  399. :param branch:
  400. Name of branch at which the submodule should (later) be checked out. The
  401. given branch must exist in the remote repository, and will be checked out
  402. locally as a tracking branch.
  403. It will only be written into the configuration if it not ``None``, which is
  404. when the checked out branch will be the one the remote HEAD pointed to.
  405. The result you get in these situation is somewhat fuzzy, and it is
  406. recommended to specify at least ``master`` here.
  407. Examples are ``master`` or ``feature/new``.
  408. :param no_checkout:
  409. If ``True``, and if the repository has to be cloned manually, no checkout
  410. will be performed.
  411. :param depth:
  412. Create a shallow clone with a history truncated to the specified number of
  413. commits.
  414. :param env:
  415. Optional dictionary containing the desired environment variables.
  416. Note: Provided variables will be used to update the execution environment
  417. for ``git``. If some variable is not specified in `env` and is defined in
  418. attr:`os.environ`, the value from attr:`os.environ` will be used. If you
  419. want to unset some variable, consider providing an empty string as its
  420. value.
  421. :param clone_multi_options:
  422. A list of clone options. Please see
  423. :meth:`Repo.clone <git.repo.base.Repo.clone>` for details.
  424. :param allow_unsafe_protocols:
  425. Allow unsafe protocols to be used, like ``ext``.
  426. :param allow_unsafe_options:
  427. Allow unsafe options to be used, like ``--upload-pack``.
  428. :return:
  429. The newly created :class:`Submodule` instance.
  430. :note:
  431. Works atomically, such that no change will be done if, for example, the
  432. repository update fails.
  433. """
  434. if repo.bare:
  435. raise InvalidGitRepositoryError("Cannot add submodules to bare repositories")
  436. # END handle bare repos
  437. path = cls._to_relative_path(repo, path)
  438. # Ensure we never put backslashes into the URL, as might happen on Windows.
  439. if url is not None:
  440. url = to_native_path_linux(url)
  441. # END ensure URL correctness
  442. # INSTANTIATE INTERMEDIATE SM
  443. sm = cls(
  444. repo,
  445. cls.NULL_BIN_SHA,
  446. cls.k_default_mode,
  447. path,
  448. name,
  449. url="invalid-temporary",
  450. )
  451. if sm.exists():
  452. # Reretrieve submodule from tree.
  453. try:
  454. sm = repo.head.commit.tree[os.fspath(path)]
  455. sm._name = name
  456. return sm
  457. except KeyError:
  458. # Could only be in index.
  459. index = repo.index
  460. entry = index.entries[index.entry_key(path, 0)]
  461. sm.binsha = entry.binsha
  462. return sm
  463. # END handle exceptions
  464. # END handle existing
  465. # fake-repo - we only need the functionality on the branch instance.
  466. br = git.Head(repo, git.Head.to_full_path(str(branch) or cls.k_head_default))
  467. has_module = sm.module_exists()
  468. branch_is_default = branch is None
  469. if has_module and url is not None:
  470. if url not in [r.url for r in sm.module().remotes]:
  471. raise ValueError(
  472. "Specified URL '%s' does not match any remote url of the repository at '%s'" % (url, sm.abspath)
  473. )
  474. # END check url
  475. # END verify urls match
  476. mrepo: Union[Repo, None] = None
  477. if url is None:
  478. if not has_module:
  479. raise ValueError("A URL was not given and a repository did not exist at %s" % path)
  480. # END check url
  481. mrepo = sm.module()
  482. # assert isinstance(mrepo, git.Repo)
  483. urls = [r.url for r in mrepo.remotes]
  484. if not urls:
  485. raise ValueError("Didn't find any remote url in repository at %s" % sm.abspath)
  486. # END verify we have url
  487. url = urls[0]
  488. else:
  489. # Clone new repo.
  490. kwargs: Dict[str, Union[bool, int, str, Sequence[TBD]]] = {"n": no_checkout}
  491. if not branch_is_default:
  492. kwargs["b"] = br.name
  493. # END setup checkout-branch
  494. if depth:
  495. if isinstance(depth, int):
  496. kwargs["depth"] = depth
  497. else:
  498. raise ValueError("depth should be an integer")
  499. if clone_multi_options:
  500. kwargs["multi_options"] = clone_multi_options
  501. # _clone_repo(cls, repo, url, path, name, **kwargs):
  502. mrepo = cls._clone_repo(
  503. repo,
  504. url,
  505. path,
  506. name,
  507. env=env,
  508. allow_unsafe_options=allow_unsafe_options,
  509. allow_unsafe_protocols=allow_unsafe_protocols,
  510. **kwargs,
  511. )
  512. # END verify url
  513. ## See #525 for ensuring git URLs in config-files are valid under Windows.
  514. url = Git.polish_url(url)
  515. # It's important to add the URL to the parent config, to let `git submodule` know.
  516. # Otherwise there is a '-' character in front of the submodule listing:
  517. # a38efa84daef914e4de58d1905a500d8d14aaf45 mymodule (v0.9.0-1-ga38efa8)
  518. # -a38efa84daef914e4de58d1905a500d8d14aaf45 submodules/intermediate/one
  519. writer: Union[GitConfigParser, SectionConstraint]
  520. with sm.repo.config_writer() as writer:
  521. writer.set_value(sm_section(name), "url", url)
  522. # Update configuration and index.
  523. index = sm.repo.index
  524. with sm.config_writer(index=index, write=False) as writer:
  525. writer.set_value("url", url)
  526. writer.set_value("path", path)
  527. sm._url = url
  528. if not branch_is_default:
  529. # Store full path.
  530. writer.set_value(cls.k_head_option, br.path)
  531. sm._branch_path = br.path
  532. # We deliberately assume that our head matches our index!
  533. if mrepo:
  534. sm.binsha = mrepo.head.commit.binsha
  535. index.add([sm], write=True)
  536. return sm
  537. def update(
  538. self,
  539. recursive: bool = False,
  540. init: bool = True,
  541. to_latest_revision: bool = False,
  542. progress: Union["UpdateProgress", None] = None,
  543. dry_run: bool = False,
  544. force: bool = False,
  545. keep_going: bool = False,
  546. env: Union[Mapping[str, str], None] = None,
  547. clone_multi_options: Union[Sequence[TBD], None] = None,
  548. allow_unsafe_options: bool = False,
  549. allow_unsafe_protocols: bool = False,
  550. ) -> "Submodule":
  551. """Update the repository of this submodule to point to the checkout we point at
  552. with the binsha of this instance.
  553. :param recursive:
  554. If ``True``, we will operate recursively and update child modules as well.
  555. :param init:
  556. If ``True``, the module repository will be cloned into place if necessary.
  557. :param to_latest_revision:
  558. If ``True``, the submodule's sha will be ignored during checkout. Instead,
  559. the remote will be fetched, and the local tracking branch updated. This only
  560. works if we have a local tracking branch, which is the case if the remote
  561. repository had a master branch, or if the ``branch`` option was specified
  562. for this submodule and the branch existed remotely.
  563. :param progress:
  564. :class:`UpdateProgress` instance, or ``None`` if no progress should be
  565. shown.
  566. :param dry_run:
  567. If ``True``, the operation will only be simulated, but not performed.
  568. All performed operations are read-only.
  569. :param force:
  570. If ``True``, we may reset heads even if the repository in question is dirty.
  571. Additionally we will be allowed to set a tracking branch which is ahead of
  572. its remote branch back into the past or the location of the remote branch.
  573. This will essentially 'forget' commits.
  574. If ``False``, local tracking branches that are in the future of their
  575. respective remote branches will simply not be moved.
  576. :param keep_going:
  577. If ``True``, we will ignore but log all errors, and keep going recursively.
  578. Unless `dry_run` is set as well, `keep_going` could cause
  579. subsequent/inherited errors you wouldn't see otherwise.
  580. In conjunction with `dry_run`, it can be useful to anticipate all errors
  581. when updating submodules.
  582. :param env:
  583. Optional dictionary containing the desired environment variables.
  584. Note: Provided variables will be used to update the execution environment
  585. for ``git``. If some variable is not specified in `env` and is defined in
  586. attr:`os.environ`, value from attr:`os.environ` will be used.
  587. If you want to unset some variable, consider providing the empty string as
  588. its value.
  589. :param clone_multi_options:
  590. List of :manpage:`git-clone(1)` options.
  591. Please see :meth:`Repo.clone <git.repo.base.Repo.clone>` for details.
  592. They only take effect with the `init` option.
  593. :param allow_unsafe_protocols:
  594. Allow unsafe protocols to be used, like ``ext``.
  595. :param allow_unsafe_options:
  596. Allow unsafe options to be used, like ``--upload-pack``.
  597. :note:
  598. Does nothing in bare repositories.
  599. :note:
  600. This method is definitely not atomic if `recursive` is ``True``.
  601. :return:
  602. self
  603. """
  604. if self.repo.bare:
  605. return self
  606. # END pass in bare mode
  607. if progress is None:
  608. progress = UpdateProgress()
  609. # END handle progress
  610. prefix = ""
  611. if dry_run:
  612. prefix = "DRY-RUN: "
  613. # END handle prefix
  614. # To keep things plausible in dry-run mode.
  615. if dry_run:
  616. mrepo = None
  617. # END init mrepo
  618. try:
  619. # ENSURE REPO IS PRESENT AND UP-TO-DATE
  620. #######################################
  621. try:
  622. mrepo = self.module()
  623. rmts = mrepo.remotes
  624. len_rmts = len(rmts)
  625. for i, remote in enumerate(rmts):
  626. op = FETCH
  627. if i == 0:
  628. op |= BEGIN
  629. # END handle start
  630. progress.update(
  631. op,
  632. i,
  633. len_rmts,
  634. prefix + "Fetching remote %s of submodule %r" % (remote, self.name),
  635. )
  636. # ===============================
  637. if not dry_run:
  638. remote.fetch(progress=progress)
  639. # END handle dry-run
  640. # ===============================
  641. if i == len_rmts - 1:
  642. op |= END
  643. # END handle end
  644. progress.update(
  645. op,
  646. i,
  647. len_rmts,
  648. prefix + "Done fetching remote of submodule %r" % self.name,
  649. )
  650. # END fetch new data
  651. except InvalidGitRepositoryError:
  652. mrepo = None
  653. if not init:
  654. return self
  655. # END early abort if init is not allowed
  656. # There is no git-repository yet - but delete empty paths.
  657. checkout_module_abspath = self.abspath
  658. if not dry_run and osp.isdir(checkout_module_abspath):
  659. try:
  660. os.rmdir(checkout_module_abspath)
  661. except OSError as e:
  662. raise OSError(
  663. "Module directory at %r does already exist and is non-empty" % checkout_module_abspath
  664. ) from e
  665. # END handle OSError
  666. # END handle directory removal
  667. # Don't check it out at first - nonetheless it will create a local
  668. # branch according to the remote-HEAD if possible.
  669. progress.update(
  670. BEGIN | CLONE,
  671. 0,
  672. 1,
  673. prefix
  674. + "Cloning url '%s' to '%s' in submodule %r" % (self.url, checkout_module_abspath, self.name),
  675. )
  676. if not dry_run:
  677. if self.url.startswith("."):
  678. url = urllib.parse.urljoin(self.repo.remotes.origin.url + "/", self.url)
  679. else:
  680. url = self.url
  681. mrepo = self._clone_repo(
  682. self.repo,
  683. url,
  684. self.path,
  685. self.name,
  686. n=True,
  687. env=env,
  688. multi_options=clone_multi_options,
  689. allow_unsafe_options=allow_unsafe_options,
  690. allow_unsafe_protocols=allow_unsafe_protocols,
  691. )
  692. # END handle dry-run
  693. progress.update(
  694. END | CLONE,
  695. 0,
  696. 1,
  697. prefix + "Done cloning to %s" % checkout_module_abspath,
  698. )
  699. if not dry_run:
  700. # See whether we have a valid branch to check out.
  701. try:
  702. mrepo = cast("Repo", mrepo)
  703. # Find a remote which has our branch - we try to be flexible.
  704. remote_branch = find_first_remote_branch(mrepo.remotes, self.branch_name)
  705. local_branch = mkhead(mrepo, self.branch_path)
  706. # Have a valid branch, but no checkout - make sure we can figure
  707. # that out by marking the commit with a null_sha.
  708. local_branch.set_object(Object(mrepo, self.NULL_BIN_SHA))
  709. # END initial checkout + branch creation
  710. # Make sure HEAD is not detached.
  711. mrepo.head.set_reference(
  712. local_branch,
  713. logmsg="submodule: attaching head to %s" % local_branch,
  714. )
  715. mrepo.head.reference.set_tracking_branch(remote_branch)
  716. except (IndexError, InvalidGitRepositoryError):
  717. _logger.warning("Failed to checkout tracking branch %s", self.branch_path)
  718. # END handle tracking branch
  719. # NOTE: Have to write the repo config file as well, otherwise the
  720. # default implementation will be offended and not update the
  721. # repository. Maybe this is a good way to ensure it doesn't get into
  722. # our way, but we want to stay backwards compatible too... It's so
  723. # redundant!
  724. with self.repo.config_writer() as writer:
  725. writer.set_value(sm_section(self.name), "url", self.url)
  726. # END handle dry_run
  727. # END handle initialization
  728. # DETERMINE SHAS TO CHECK OUT
  729. #############################
  730. binsha = self.binsha
  731. hexsha = self.hexsha
  732. if mrepo is not None:
  733. # mrepo is only set if we are not in dry-run mode or if the module
  734. # existed.
  735. is_detached = mrepo.head.is_detached
  736. # END handle dry_run
  737. if mrepo is not None and to_latest_revision:
  738. msg_base = "Cannot update to latest revision in repository at %r as " % mrepo.working_dir
  739. if not is_detached:
  740. rref = mrepo.head.reference.tracking_branch()
  741. if rref is not None:
  742. rcommit = rref.commit
  743. binsha = rcommit.binsha
  744. hexsha = rcommit.hexsha
  745. else:
  746. _logger.error(
  747. "%s a tracking branch was not set for local branch '%s'",
  748. msg_base,
  749. mrepo.head.reference,
  750. )
  751. # END handle remote ref
  752. else:
  753. _logger.error("%s there was no local tracking branch", msg_base)
  754. # END handle detached head
  755. # END handle to_latest_revision option
  756. # Update the working tree.
  757. # Handles dry_run.
  758. if mrepo is not None and mrepo.head.commit.binsha != binsha:
  759. # We must ensure that our destination sha (the one to point to) is in
  760. # the future of our current head. Otherwise, we will reset changes that
  761. # might have been done on the submodule, but were not yet pushed. We
  762. # also handle the case that history has been rewritten, leaving no
  763. # merge-base. In that case we behave conservatively, protecting possible
  764. # changes the user had done.
  765. may_reset = True
  766. if mrepo.head.commit.binsha != self.NULL_BIN_SHA:
  767. base_commit = mrepo.merge_base(mrepo.head.commit, hexsha)
  768. if len(base_commit) == 0 or (base_commit[0] is not None and base_commit[0].hexsha == hexsha):
  769. if force:
  770. msg = "Will force checkout or reset on local branch that is possibly in the future of"
  771. msg += " the commit it will be checked out to, effectively 'forgetting' new commits"
  772. _logger.debug(msg)
  773. else:
  774. msg = "Skipping %s on branch '%s' of submodule repo '%s' as it contains un-pushed commits"
  775. msg %= (
  776. is_detached and "checkout" or "reset",
  777. mrepo.head,
  778. mrepo,
  779. )
  780. _logger.info(msg)
  781. may_reset = False
  782. # END handle force
  783. # END handle if we are in the future
  784. if may_reset and not force and mrepo.is_dirty(index=True, working_tree=True, untracked_files=True):
  785. raise RepositoryDirtyError(mrepo, "Cannot reset a dirty repository")
  786. # END handle force and dirty state
  787. # END handle empty repo
  788. # END verify future/past
  789. progress.update(
  790. BEGIN | UPDWKTREE,
  791. 0,
  792. 1,
  793. prefix
  794. + "Updating working tree at %s for submodule %r to revision %s" % (self.path, self.name, hexsha),
  795. )
  796. if not dry_run and may_reset:
  797. if is_detached:
  798. # NOTE: For now we force. The user is not supposed to change
  799. # detached submodules anyway. Maybe at some point this becomes
  800. # an option, to properly handle user modifications - see below
  801. # for future options regarding rebase and merge.
  802. mrepo.git.checkout(hexsha, force=force)
  803. else:
  804. mrepo.head.reset(hexsha, index=True, working_tree=True)
  805. # END handle checkout
  806. # If we may reset/checkout.
  807. progress.update(
  808. END | UPDWKTREE,
  809. 0,
  810. 1,
  811. prefix + "Done updating working tree for submodule %r" % self.name,
  812. )
  813. # END update to new commit only if needed
  814. except Exception as err:
  815. if not keep_going:
  816. raise
  817. _logger.error(str(err))
  818. # END handle keep_going
  819. # HANDLE RECURSION
  820. ##################
  821. if recursive:
  822. # In dry_run mode, the module might not exist.
  823. if mrepo is not None:
  824. for submodule in self.iter_items(self.module()):
  825. submodule.update(
  826. recursive,
  827. init,
  828. to_latest_revision,
  829. progress=progress,
  830. dry_run=dry_run,
  831. force=force,
  832. keep_going=keep_going,
  833. )
  834. # END handle recursive update
  835. # END handle dry run
  836. # END for each submodule
  837. return self
  838. @unbare_repo
  839. def move(self, module_path: PathLike, configuration: bool = True, module: bool = True) -> "Submodule":
  840. """Move the submodule to a another module path. This involves physically moving
  841. the repository at our current path, changing the configuration, as well as
  842. adjusting our index entry accordingly.
  843. :param module_path:
  844. The path to which to move our module in the parent repository's working
  845. tree, given as repository-relative or absolute path. Intermediate
  846. directories will be created accordingly. If the path already exists, it must
  847. be empty. Trailing (back)slashes are removed automatically.
  848. :param configuration:
  849. If ``True``, the configuration will be adjusted to let the submodule point
  850. to the given path.
  851. :param module:
  852. If ``True``, the repository managed by this submodule will be moved as well.
  853. If ``False``, we don't move the submodule's checkout, which may leave the
  854. parent repository in an inconsistent state.
  855. :return:
  856. self
  857. :raise ValueError:
  858. If the module path existed and was not empty, or was a file.
  859. :note:
  860. Currently the method is not atomic, and it could leave the repository in an
  861. inconsistent state if a sub-step fails for some reason.
  862. """
  863. if module + configuration < 1:
  864. raise ValueError("You must specify to move at least the module or the configuration of the submodule")
  865. # END handle input
  866. module_checkout_path = self._to_relative_path(self.repo, module_path)
  867. # VERIFY DESTINATION
  868. if module_checkout_path == self.path:
  869. return self
  870. # END handle no change
  871. module_checkout_abspath = join_path_native(str(self.repo.working_tree_dir), module_checkout_path)
  872. if osp.isfile(module_checkout_abspath):
  873. raise ValueError("Cannot move repository onto a file: %s" % module_checkout_abspath)
  874. # END handle target files
  875. index = self.repo.index
  876. tekey = index.entry_key(module_checkout_path, 0)
  877. # if the target item already exists, fail
  878. if configuration and tekey in index.entries:
  879. raise ValueError("Index entry for target path did already exist")
  880. # END handle index key already there
  881. # Remove existing destination.
  882. if module:
  883. if osp.exists(module_checkout_abspath):
  884. if len(os.listdir(module_checkout_abspath)):
  885. raise ValueError("Destination module directory was not empty")
  886. # END handle non-emptiness
  887. if osp.islink(module_checkout_abspath):
  888. os.remove(module_checkout_abspath)
  889. else:
  890. os.rmdir(module_checkout_abspath)
  891. # END handle link
  892. else:
  893. # Recreate parent directories.
  894. # NOTE: renames() does that now.
  895. pass
  896. # END handle existence
  897. # END handle module
  898. # Move the module into place if possible.
  899. cur_path = self.abspath
  900. renamed_module = False
  901. if module and osp.exists(cur_path):
  902. os.renames(cur_path, module_checkout_abspath)
  903. renamed_module = True
  904. if osp.isfile(osp.join(module_checkout_abspath, ".git")):
  905. module_abspath = self._module_abspath(self.repo, self.path, self.name)
  906. self._write_git_file_and_module_config(module_checkout_abspath, module_abspath)
  907. # END handle git file rewrite
  908. # END move physical module
  909. # Rename the index entry - we have to manipulate the index directly as git-mv
  910. # cannot be used on submodules... yeah.
  911. previous_sm_path = self.path
  912. try:
  913. if configuration:
  914. try:
  915. ekey = index.entry_key(self.path, 0)
  916. entry = index.entries[ekey]
  917. del index.entries[ekey]
  918. nentry = git.IndexEntry(entry[:3] + (module_checkout_path,) + entry[4:])
  919. index.entries[tekey] = nentry
  920. except KeyError as e:
  921. raise InvalidGitRepositoryError("Submodule's entry at %r did not exist" % (self.path)) from e
  922. # END handle submodule doesn't exist
  923. # Update configuration.
  924. with self.config_writer(index=index) as writer: # Auto-write.
  925. writer.set_value("path", module_checkout_path)
  926. self.path = module_checkout_path
  927. # END handle configuration flag
  928. except Exception:
  929. if renamed_module:
  930. os.renames(module_checkout_abspath, cur_path)
  931. # END undo module renaming
  932. raise
  933. # END handle undo rename
  934. # Auto-rename submodule if its name was 'default', that is, the checkout
  935. # directory.
  936. if previous_sm_path == self.name:
  937. self.rename(module_checkout_path)
  938. return self
  939. @unbare_repo
  940. def remove(
  941. self,
  942. module: bool = True,
  943. force: bool = False,
  944. configuration: bool = True,
  945. dry_run: bool = False,
  946. ) -> "Submodule":
  947. """Remove this submodule from the repository. This will remove our entry
  948. from the ``.gitmodules`` file and the entry in the ``.git/config`` file.
  949. :param module:
  950. If ``True``, the checked out module we point to will be deleted as well. If
  951. that module is currently on a commit outside any branch in the remote, or if
  952. it is ahead of its tracking branch, or if there are modified or untracked
  953. files in its working tree, then the removal will fail. In case the removal
  954. of the repository fails for these reasons, the submodule status will not
  955. have been altered.
  956. If this submodule has child modules of its own, these will be deleted prior
  957. to touching the direct submodule.
  958. :param force:
  959. Enforces the deletion of the module even though it contains modifications.
  960. This basically enforces a brute-force file system based deletion.
  961. :param configuration:
  962. If ``True``, the submodule is deleted from the configuration, otherwise it
  963. isn't. Although this should be enabled most of the time, this flag enables
  964. you to safely delete the repository of your submodule.
  965. :param dry_run:
  966. If ``True``, we will not actually do anything, but throw the errors we would
  967. usually throw.
  968. :return:
  969. self
  970. :note:
  971. Doesn't work in bare repositories.
  972. :note:
  973. Doesn't work atomically, as failure to remove any part of the submodule will
  974. leave an inconsistent state.
  975. :raise git.exc.InvalidGitRepositoryError:
  976. Thrown if the repository cannot be deleted.
  977. :raise OSError:
  978. If directories or files could not be removed.
  979. """
  980. if not (module or configuration):
  981. raise ValueError("Need to specify to delete at least the module, or the configuration")
  982. # END handle parameters
  983. # Recursively remove children of this submodule.
  984. nc = 0
  985. for csm in self.children():
  986. nc += 1
  987. csm.remove(module, force, configuration, dry_run)
  988. del csm
  989. if configuration and not dry_run and nc > 0:
  990. # Ensure we don't leave the parent repository in a dirty state, and commit
  991. # our changes. It's important for recursive, unforced, deletions to work as
  992. # expected.
  993. self.module().index.commit("Removed at least one of child-modules of '%s'" % self.name)
  994. # END handle recursion
  995. # DELETE REPOSITORY WORKING TREE
  996. ################################
  997. if module and self.module_exists():
  998. mod = self.module()
  999. git_dir = mod.git_dir
  1000. if force:
  1001. # Take the fast lane and just delete everything in our module path.
  1002. # TODO: If we run into permission problems, we have a highly
  1003. # inconsistent state. Delete the .git folders last, start with the
  1004. # submodules first.
  1005. mp = self.abspath
  1006. method: Union[None, Callable[[PathLike], None]] = None
  1007. if osp.islink(mp):
  1008. method = os.remove
  1009. elif osp.isdir(mp):
  1010. method = rmtree
  1011. elif osp.exists(mp):
  1012. raise AssertionError("Cannot forcibly delete repository as it was neither a link, nor a directory")
  1013. # END handle brutal deletion
  1014. if not dry_run:
  1015. assert method
  1016. method(mp)
  1017. # END apply deletion method
  1018. else:
  1019. # Verify we may delete our module.
  1020. if mod.is_dirty(index=True, working_tree=True, untracked_files=True):
  1021. raise InvalidGitRepositoryError(
  1022. "Cannot delete module at %s with any modifications, unless force is specified"
  1023. % mod.working_tree_dir
  1024. )
  1025. # END check for dirt
  1026. # Figure out whether we have new commits compared to the remotes.
  1027. # NOTE: If the user pulled all the time, the remote heads might not have
  1028. # been updated, so commits coming from the remote look as if they come
  1029. # from us. But we stay strictly read-only and don't fetch beforehand.
  1030. for remote in mod.remotes:
  1031. num_branches_with_new_commits = 0
  1032. rrefs = remote.refs
  1033. for rref in rrefs:
  1034. num_branches_with_new_commits += len(mod.git.cherry(rref)) != 0
  1035. # END for each remote ref
  1036. # Not a single remote branch contained all our commits.
  1037. if len(rrefs) and num_branches_with_new_commits == len(rrefs):
  1038. raise InvalidGitRepositoryError(
  1039. "Cannot delete module at %s as there are new commits" % mod.working_tree_dir
  1040. )
  1041. # END handle new commits
  1042. # We have to manually delete some references to allow resources to
  1043. # be cleaned up immediately when we are done with them, because
  1044. # Python's scoping is no more granular than the whole function (loop
  1045. # bodies are not scopes). When the objects stay alive longer, they
  1046. # can keep handles open. On Windows, this is a problem.
  1047. if len(rrefs):
  1048. del rref # skipcq: PYL-W0631
  1049. # END handle remotes
  1050. del rrefs
  1051. del remote
  1052. # END for each remote
  1053. # Finally delete our own submodule.
  1054. if not dry_run:
  1055. self._clear_cache()
  1056. wtd = mod.working_tree_dir
  1057. del mod # Release file-handles (Windows).
  1058. gc.collect()
  1059. rmtree(str(wtd))
  1060. # END delete tree if possible
  1061. # END handle force
  1062. if not dry_run and osp.isdir(git_dir):
  1063. self._clear_cache()
  1064. rmtree(git_dir)
  1065. # END handle separate bare repository
  1066. # END handle module deletion
  1067. # Void our data so as not to delay invalid access.
  1068. if not dry_run:
  1069. self._clear_cache()
  1070. # DELETE CONFIGURATION
  1071. ######################
  1072. if configuration and not dry_run:
  1073. # First the index-entry.
  1074. parent_index = self.repo.index
  1075. try:
  1076. del parent_index.entries[parent_index.entry_key(self.path, 0)]
  1077. except KeyError:
  1078. pass
  1079. # END delete entry
  1080. parent_index.write()
  1081. # Now git config - we need the config intact, otherwise we can't query
  1082. # information anymore.
  1083. with self.repo.config_writer() as gcp_writer:
  1084. gcp_writer.remove_section(sm_section(self.name))
  1085. with self.config_writer() as sc_writer:
  1086. sc_writer.remove_section()
  1087. # END delete configuration
  1088. return self
  1089. def set_parent_commit(self, commit: Union[Commit_ish, str, None], check: bool = True) -> "Submodule":
  1090. """Set this instance to use the given commit whose tree is supposed to
  1091. contain the ``.gitmodules`` blob.
  1092. :param commit:
  1093. Commit-ish reference pointing at the root tree, or ``None`` to always point
  1094. to the most recent commit.
  1095. :param check:
  1096. If ``True``, relatively expensive checks will be performed to verify
  1097. validity of the submodule.
  1098. :raise ValueError:
  1099. If the commit's tree didn't contain the ``.gitmodules`` blob.
  1100. :raise ValueError:
  1101. If the parent commit didn't store this submodule under the current path.
  1102. :return:
  1103. self
  1104. """
  1105. if commit is None:
  1106. self._parent_commit = None
  1107. return self
  1108. # END handle None
  1109. pcommit = self.repo.commit(commit)
  1110. pctree = pcommit.tree
  1111. if self.k_modules_file not in pctree:
  1112. raise ValueError("Tree of commit %s did not contain the %s file" % (commit, self.k_modules_file))
  1113. # END handle exceptions
  1114. prev_pc = self._parent_commit
  1115. self._parent_commit = pcommit
  1116. if check:
  1117. parser = self._config_parser(self.repo, self._parent_commit, read_only=True)
  1118. if not parser.has_section(sm_section(self.name)):
  1119. self._parent_commit = prev_pc
  1120. raise ValueError("Submodule at path %r did not exist in parent commit %s" % (self.path, commit))
  1121. # END handle submodule did not exist
  1122. # END handle checking mode
  1123. # Update our sha, it could have changed.
  1124. # If check is False, we might see a parent-commit that doesn't even contain the
  1125. # submodule anymore. in that case, mark our sha as being NULL.
  1126. try:
  1127. self.binsha = pctree[str(self.path)].binsha
  1128. except KeyError:
  1129. self.binsha = self.NULL_BIN_SHA
  1130. self._clear_cache()
  1131. return self
  1132. @unbare_repo
  1133. def config_writer(
  1134. self, index: Union["IndexFile", None] = None, write: bool = True
  1135. ) -> SectionConstraint["SubmoduleConfigParser"]:
  1136. """
  1137. :return:
  1138. A config writer instance allowing you to read and write the data belonging
  1139. to this submodule into the ``.gitmodules`` file.
  1140. :param index:
  1141. If not ``None``, an :class:`~git.index.base.IndexFile` instance which should
  1142. be written. Defaults to the index of the :class:`Submodule`'s parent
  1143. repository.
  1144. :param write:
  1145. If ``True``, the index will be written each time a configuration value changes.
  1146. :note:
  1147. The parameters allow for a more efficient writing of the index, as you can
  1148. pass in a modified index on your own, prevent automatic writing, and write
  1149. yourself once the whole operation is complete.
  1150. :raise ValueError:
  1151. If trying to get a writer on a parent_commit which does not match the
  1152. current head commit.
  1153. :raise IOError:
  1154. If the ``.gitmodules`` file/blob could not be read.
  1155. """
  1156. writer = self._config_parser_constrained(read_only=False)
  1157. if index is not None:
  1158. writer.config._index = index
  1159. writer.config._auto_write = write
  1160. return writer
  1161. @unbare_repo
  1162. def rename(self, new_name: str) -> "Submodule":
  1163. """Rename this submodule.
  1164. :note:
  1165. This method takes care of renaming the submodule in various places, such as:
  1166. * ``$parent_git_dir / config``
  1167. * ``$working_tree_dir / .gitmodules``
  1168. * (git >= v1.8.0: move submodule repository to new name)
  1169. As ``.gitmodules`` will be changed, you would need to make a commit afterwards.
  1170. The changed ``.gitmodules`` file will already be added to the index.
  1171. :return:
  1172. This :class:`Submodule` instance
  1173. """
  1174. if self.name == new_name:
  1175. return self
  1176. # .git/config
  1177. with self.repo.config_writer() as pw:
  1178. # As we ourselves didn't write anything about submodules into the parent
  1179. # .git/config, we will not require it to exist, and just ignore missing
  1180. # entries.
  1181. if pw.has_section(sm_section(self.name)):
  1182. pw.rename_section(sm_section(self.name), sm_section(new_name))
  1183. # .gitmodules
  1184. with self.config_writer(write=True).config as cw:
  1185. cw.rename_section(sm_section(self.name), sm_section(new_name))
  1186. self._name = new_name
  1187. # .git/modules
  1188. mod = self.module()
  1189. if mod.has_separate_working_tree():
  1190. destination_module_abspath = self._module_abspath(self.repo, self.path, new_name)
  1191. source_dir = mod.git_dir
  1192. # Let's be sure the submodule name is not so obviously tied to a directory.
  1193. if str(destination_module_abspath).startswith(str(mod.git_dir)):
  1194. tmp_dir = self._module_abspath(self.repo, self.path, str(uuid.uuid4()))
  1195. os.renames(source_dir, tmp_dir)
  1196. source_dir = tmp_dir
  1197. # END handle self-containment
  1198. os.renames(source_dir, destination_module_abspath)
  1199. if mod.working_tree_dir:
  1200. self._write_git_file_and_module_config(mod.working_tree_dir, destination_module_abspath)
  1201. # END move separate git repository
  1202. return self
  1203. # } END edit interface
  1204. # { Query Interface
  1205. @unbare_repo
  1206. def module(self) -> "Repo":
  1207. """
  1208. :return:
  1209. :class:`~git.repo.base.Repo` instance initialized from the repository at our
  1210. submodule path
  1211. :raise git.exc.InvalidGitRepositoryError:
  1212. If a repository was not available.
  1213. This could also mean that it was not yet initialized.
  1214. """
  1215. module_checkout_abspath = self.abspath
  1216. try:
  1217. repo = git.Repo(module_checkout_abspath)
  1218. if repo != self.repo:
  1219. return repo
  1220. # END handle repo uninitialized
  1221. except (InvalidGitRepositoryError, NoSuchPathError) as e:
  1222. raise InvalidGitRepositoryError("No valid repository at %s" % module_checkout_abspath) from e
  1223. else:
  1224. raise InvalidGitRepositoryError("Repository at %r was not yet checked out" % module_checkout_abspath)
  1225. # END handle exceptions
  1226. def module_exists(self) -> bool:
  1227. """
  1228. :return:
  1229. ``True`` if our module exists and is a valid git repository.
  1230. See the :meth:`module` method.
  1231. """
  1232. try:
  1233. self.module()
  1234. return True
  1235. except Exception:
  1236. return False
  1237. # END handle exception
  1238. def exists(self) -> bool:
  1239. """
  1240. :return:
  1241. ``True`` if the submodule exists, ``False`` otherwise.
  1242. Please note that a submodule may exist (in the ``.gitmodules`` file) even
  1243. though its module doesn't exist on disk.
  1244. """
  1245. # Keep attributes for later, and restore them if we have no valid data.
  1246. # This way we do not actually alter the state of the object.
  1247. loc = locals()
  1248. for attr in self._cache_attrs:
  1249. try:
  1250. if hasattr(self, attr):
  1251. loc[attr] = getattr(self, attr)
  1252. # END if we have the attribute cache
  1253. except (cp.NoSectionError, ValueError):
  1254. # On PY3, this can happen apparently... don't know why this doesn't
  1255. # happen on PY2.
  1256. pass
  1257. # END for each attr
  1258. self._clear_cache()
  1259. try:
  1260. try:
  1261. self.path # noqa: B018
  1262. return True
  1263. except Exception:
  1264. return False
  1265. # END handle exceptions
  1266. finally:
  1267. for attr in self._cache_attrs:
  1268. if attr in loc:
  1269. setattr(self, attr, loc[attr])
  1270. # END if we have a cache
  1271. # END reapply each attribute
  1272. # END handle object state consistency
  1273. @property
  1274. def branch(self) -> "Head":
  1275. """
  1276. :return:
  1277. The branch instance that we are to checkout
  1278. :raise git.exc.InvalidGitRepositoryError:
  1279. If our module is not yet checked out.
  1280. """
  1281. return mkhead(self.module(), self._branch_path)
  1282. @property
  1283. def branch_path(self) -> PathLike:
  1284. """
  1285. :return:
  1286. Full repository-relative path as string to the branch we would checkout from
  1287. the remote and track
  1288. """
  1289. return self._branch_path
  1290. @property
  1291. def branch_name(self) -> str:
  1292. """
  1293. :return:
  1294. The name of the branch, which is the shortest possible branch name
  1295. """
  1296. # Use an instance method, for this we create a temporary Head instance which
  1297. # uses a repository that is available at least (it makes no difference).
  1298. return git.Head(self.repo, self._branch_path).name
  1299. @property
  1300. def url(self) -> str:
  1301. """:return: The url to the repository our submodule's repository refers to"""
  1302. return self._url
  1303. @property
  1304. def parent_commit(self) -> "Commit":
  1305. """
  1306. :return:
  1307. :class:`~git.objects.commit.Commit` instance with the tree containing the
  1308. ``.gitmodules`` file
  1309. :note:
  1310. Will always point to the current head's commit if it was not set explicitly.
  1311. """
  1312. if self._parent_commit is None:
  1313. return self.repo.commit()
  1314. return self._parent_commit
  1315. @property
  1316. def name(self) -> str:
  1317. """
  1318. :return:
  1319. The name of this submodule. It is used to identify it within the
  1320. ``.gitmodules`` file.
  1321. :note:
  1322. By default, this is the name is the path at which to find the submodule, but
  1323. in GitPython it should be a unique identifier similar to the identifiers
  1324. used for remotes, which allows to change the path of the submodule easily.
  1325. """
  1326. return self._name
  1327. def config_reader(self) -> SectionConstraint[SubmoduleConfigParser]:
  1328. """
  1329. :return:
  1330. ConfigReader instance which allows you to query the configuration values of
  1331. this submodule, as provided by the ``.gitmodules`` file.
  1332. :note:
  1333. The config reader will actually read the data directly from the repository
  1334. and thus does not need nor care about your working tree.
  1335. :note:
  1336. Should be cached by the caller and only kept as long as needed.
  1337. :raise IOError:
  1338. If the ``.gitmodules`` file/blob could not be read.
  1339. """
  1340. return self._config_parser_constrained(read_only=True)
  1341. def children(self) -> IterableList["Submodule"]:
  1342. """
  1343. :return:
  1344. IterableList(Submodule, ...) An iterable list of :class:`Submodule`
  1345. instances which are children of this submodule or 0 if the submodule is not
  1346. checked out.
  1347. """
  1348. return self._get_intermediate_items(self)
  1349. # } END query interface
  1350. # { Iterable Interface
  1351. @classmethod
  1352. def iter_items(
  1353. cls,
  1354. repo: "Repo",
  1355. parent_commit: Union[Commit_ish, str] = "HEAD",
  1356. *args: Any,
  1357. **kwargs: Any,
  1358. ) -> Iterator["Submodule"]:
  1359. """
  1360. :return:
  1361. Iterator yielding :class:`Submodule` instances available in the given
  1362. repository
  1363. """
  1364. try:
  1365. pc = repo.commit(parent_commit) # Parent commit instance
  1366. parser = cls._config_parser(repo, pc, read_only=True)
  1367. except (IOError, BadName):
  1368. return
  1369. # END handle empty iterator
  1370. for sms in parser.sections():
  1371. n = sm_name(sms)
  1372. p = parser.get(sms, "path")
  1373. u = parser.get(sms, "url")
  1374. b = cls.k_head_default
  1375. if parser.has_option(sms, cls.k_head_option):
  1376. b = str(parser.get(sms, cls.k_head_option))
  1377. # END handle optional information
  1378. # Get the binsha.
  1379. index = repo.index
  1380. try:
  1381. rt = pc.tree # Root tree
  1382. sm = rt[p]
  1383. except KeyError:
  1384. # Try the index, maybe it was just added.
  1385. try:
  1386. entry = index.entries[index.entry_key(p, 0)]
  1387. sm = Submodule(repo, entry.binsha, entry.mode, entry.path)
  1388. except KeyError:
  1389. # The submodule doesn't exist, probably it wasn't removed from the
  1390. # .gitmodules file.
  1391. continue
  1392. # END handle keyerror
  1393. # END handle critical error
  1394. # Make sure we are looking at a submodule object.
  1395. if type(sm) is not git.objects.submodule.base.Submodule:
  1396. continue
  1397. # Fill in remaining info - saves time as it doesn't have to be parsed again.
  1398. sm._name = n
  1399. if pc != repo.commit():
  1400. sm._parent_commit = pc
  1401. # END set only if not most recent!
  1402. sm._branch_path = git.Head.to_full_path(b)
  1403. sm._url = u
  1404. yield sm
  1405. # END for each section
  1406. # } END iterable interface