base.py 58 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633
  1. # Copyright (C) 2008, 2009 Michael Trier (mtrier@gmail.com) and contributors
  2. #
  3. # This module is part of GitPython and is released under the
  4. # 3-Clause BSD License: https://opensource.org/license/bsd-3-clause/
  5. from __future__ import annotations
  6. __all__ = ["Repo"]
  7. import gc
  8. import logging
  9. import os
  10. import os.path as osp
  11. from pathlib import Path
  12. import re
  13. import shlex
  14. import sys
  15. import warnings
  16. import gitdb
  17. from gitdb.db.loose import LooseObjectDB
  18. from gitdb.exc import BadObject
  19. from git.cmd import Git, handle_process_output
  20. from git.compat import defenc, safe_decode
  21. from git.config import GitConfigParser
  22. from git.db import GitCmdObjectDB
  23. from git.exc import (
  24. GitCommandError,
  25. InvalidGitRepositoryError,
  26. NoSuchPathError,
  27. )
  28. from git.index import IndexFile
  29. from git.objects import Submodule, RootModule, Commit
  30. from git.refs import HEAD, Head, Reference, TagReference
  31. from git.remote import Remote, add_progress, to_progress_instance
  32. from git.util import (
  33. Actor,
  34. cygpath,
  35. expand_path,
  36. finalize_process,
  37. hex_to_bin,
  38. remove_password_if_present,
  39. )
  40. from .fun import (
  41. find_submodule_git_dir,
  42. find_worktree_git_dir,
  43. is_git_dir,
  44. rev_parse,
  45. touch,
  46. )
  47. # typing ------------------------------------------------------
  48. from git.types import (
  49. CallableProgress,
  50. Commit_ish,
  51. Lit_config_levels,
  52. PathLike,
  53. TBD,
  54. Tree_ish,
  55. assert_never,
  56. )
  57. from typing import (
  58. Any,
  59. BinaryIO,
  60. Callable,
  61. Dict,
  62. Iterator,
  63. List,
  64. Mapping,
  65. NamedTuple,
  66. Optional,
  67. Sequence,
  68. TYPE_CHECKING,
  69. TextIO,
  70. Tuple,
  71. Type,
  72. Union,
  73. cast,
  74. )
  75. from git.types import ConfigLevels_Tup, TypedDict
  76. if TYPE_CHECKING:
  77. from git.objects import Tree
  78. from git.objects.submodule.base import UpdateProgress
  79. from git.refs.symbolic import SymbolicReference
  80. from git.remote import RemoteProgress
  81. from git.util import IterableList
  82. # -----------------------------------------------------------
  83. _logger = logging.getLogger(__name__)
  84. class BlameEntry(NamedTuple):
  85. commit: Dict[str, Commit]
  86. linenos: range
  87. orig_path: Optional[str]
  88. orig_linenos: range
  89. class Repo:
  90. """Represents a git repository and allows you to query references, create commit
  91. information, generate diffs, create and clone repositories, and query the log.
  92. The following attributes are worth using:
  93. * :attr:`working_dir` is the working directory of the git command, which is the
  94. working tree directory if available or the ``.git`` directory in case of bare
  95. repositories.
  96. * :attr:`working_tree_dir` is the working tree directory, but will return ``None``
  97. if we are a bare repository.
  98. * :attr:`git_dir` is the ``.git`` repository directory, which is always set.
  99. """
  100. DAEMON_EXPORT_FILE = "git-daemon-export-ok"
  101. # Must exist, or __del__ will fail in case we raise on `__init__()`.
  102. git = cast("Git", None)
  103. working_dir: PathLike
  104. """The working directory of the git command."""
  105. # stored as string for easier processing, but annotated as path for clearer intention
  106. _working_tree_dir: Optional[PathLike] = None
  107. git_dir: PathLike
  108. """The ``.git`` repository directory."""
  109. _common_dir: PathLike = ""
  110. # Precompiled regex
  111. re_whitespace = re.compile(r"\s+")
  112. re_hexsha_only = re.compile(r"^[0-9A-Fa-f]{40}$")
  113. re_hexsha_shortened = re.compile(r"^[0-9A-Fa-f]{4,40}$")
  114. re_envvars = re.compile(r"(\$(\{\s?)?[a-zA-Z_]\w*(\}\s?)?|%\s?[a-zA-Z_]\w*\s?%)")
  115. re_author_committer_start = re.compile(r"^(author|committer)")
  116. re_tab_full_line = re.compile(r"^\t(.*)$")
  117. unsafe_git_clone_options = [
  118. # Executes arbitrary commands:
  119. "--upload-pack",
  120. "-u",
  121. # Can override configuration variables that execute arbitrary commands:
  122. "--config",
  123. "-c",
  124. ]
  125. """Options to :manpage:`git-clone(1)` that allow arbitrary commands to be executed.
  126. The ``--upload-pack``/``-u`` option allows users to execute arbitrary commands
  127. directly:
  128. https://git-scm.com/docs/git-clone#Documentation/git-clone.txt---upload-packltupload-packgt
  129. The ``--config``/``-c`` option allows users to override configuration variables like
  130. ``protocol.allow`` and ``core.gitProxy`` to execute arbitrary commands:
  131. https://git-scm.com/docs/git-clone#Documentation/git-clone.txt---configltkeygtltvaluegt
  132. """
  133. # Invariants
  134. config_level: ConfigLevels_Tup = ("system", "user", "global", "repository")
  135. """Represents the configuration level of a configuration file."""
  136. # Subclass configuration
  137. GitCommandWrapperType = Git
  138. """Subclasses may easily bring in their own custom types by placing a constructor or
  139. type here."""
  140. def __init__(
  141. self,
  142. path: Optional[PathLike] = None,
  143. odbt: Type[LooseObjectDB] = GitCmdObjectDB,
  144. search_parent_directories: bool = False,
  145. expand_vars: bool = True,
  146. ) -> None:
  147. R"""Create a new :class:`Repo` instance.
  148. :param path:
  149. The path to either the worktree directory or the .git directory itself::
  150. repo = Repo("/Users/mtrier/Development/git-python")
  151. repo = Repo("/Users/mtrier/Development/git-python.git")
  152. repo = Repo("~/Development/git-python.git")
  153. repo = Repo("$REPOSITORIES/Development/git-python.git")
  154. repo = Repo(R"C:\Users\mtrier\Development\git-python\.git")
  155. - In *Cygwin*, `path` may be a ``cygdrive/...`` prefixed path.
  156. - If `path` is ``None`` or an empty string, :envvar:`GIT_DIR` is used. If
  157. that environment variable is absent or empty, the current directory is
  158. used.
  159. :param odbt:
  160. Object DataBase type - a type which is constructed by providing the
  161. directory containing the database objects, i.e. ``.git/objects``. It will be
  162. used to access all object data.
  163. :param search_parent_directories:
  164. If ``True``, all parent directories will be searched for a valid repo as
  165. well.
  166. Please note that this was the default behaviour in older versions of
  167. GitPython, which is considered a bug though.
  168. :raise git.exc.InvalidGitRepositoryError:
  169. :raise git.exc.NoSuchPathError:
  170. :return:
  171. :class:`Repo`
  172. """
  173. epath = path or os.getenv("GIT_DIR")
  174. if not epath:
  175. epath = os.getcwd()
  176. epath = os.fspath(epath)
  177. if Git.is_cygwin():
  178. # Given how the tests are written, this seems more likely to catch Cygwin
  179. # git used from Windows than Windows git used from Cygwin. Therefore
  180. # changing to Cygwin-style paths is the relevant operation.
  181. epath = cygpath(epath)
  182. if expand_vars and re.search(self.re_envvars, epath):
  183. warnings.warn(
  184. "The use of environment variables in paths is deprecated"
  185. + "\nfor security reasons and may be removed in the future!!",
  186. stacklevel=1,
  187. )
  188. epath = expand_path(epath, expand_vars)
  189. if epath is not None:
  190. if not os.path.exists(epath):
  191. raise NoSuchPathError(epath)
  192. # Walk up the path to find the `.git` dir.
  193. curpath = epath
  194. git_dir = None
  195. while curpath:
  196. # ABOUT osp.NORMPATH
  197. # It's important to normalize the paths, as submodules will otherwise
  198. # initialize their repo instances with paths that depend on path-portions
  199. # that will not exist after being removed. It's just cleaner.
  200. if is_git_dir(curpath):
  201. git_dir = curpath
  202. # from man git-config : core.worktree
  203. # Set the path to the root of the working tree. If GIT_COMMON_DIR
  204. # environment variable is set, core.worktree is ignored and not used for
  205. # determining the root of working tree. This can be overridden by the
  206. # GIT_WORK_TREE environment variable. The value can be an absolute path
  207. # or relative to the path to the .git directory, which is either
  208. # specified by GIT_DIR, or automatically discovered. If GIT_DIR is
  209. # specified but none of GIT_WORK_TREE and core.worktree is specified,
  210. # the current working directory is regarded as the top level of your
  211. # working tree.
  212. self._working_tree_dir = os.path.dirname(git_dir)
  213. if os.environ.get("GIT_COMMON_DIR") is None:
  214. gitconf = self._config_reader("repository", git_dir)
  215. if gitconf.has_option("core", "worktree"):
  216. self._working_tree_dir = gitconf.get("core", "worktree")
  217. if "GIT_WORK_TREE" in os.environ:
  218. self._working_tree_dir = os.getenv("GIT_WORK_TREE")
  219. break
  220. dotgit = osp.join(curpath, ".git")
  221. sm_gitpath = find_submodule_git_dir(dotgit)
  222. if sm_gitpath is not None:
  223. git_dir = osp.normpath(sm_gitpath)
  224. sm_gitpath = find_submodule_git_dir(dotgit)
  225. if sm_gitpath is None:
  226. sm_gitpath = find_worktree_git_dir(dotgit)
  227. if sm_gitpath is not None:
  228. git_dir = expand_path(sm_gitpath, expand_vars)
  229. self._working_tree_dir = curpath
  230. break
  231. if not search_parent_directories:
  232. break
  233. curpath, tail = osp.split(curpath)
  234. if not tail:
  235. break
  236. # END while curpath
  237. if git_dir is None:
  238. raise InvalidGitRepositoryError(epath)
  239. self.git_dir = git_dir
  240. self._bare = False
  241. try:
  242. self._bare = self.config_reader("repository").getboolean("core", "bare")
  243. except Exception:
  244. # Let's not assume the option exists, although it should.
  245. pass
  246. try:
  247. common_dir = (Path(self.git_dir) / "commondir").read_text().splitlines()[0].strip()
  248. self._common_dir = osp.join(self.git_dir, common_dir)
  249. except OSError:
  250. self._common_dir = ""
  251. # Adjust the working directory in case we are actually bare - we didn't know
  252. # that in the first place.
  253. if self._bare:
  254. self._working_tree_dir = None
  255. # END working dir handling
  256. self.working_dir: PathLike = self._working_tree_dir or self.common_dir
  257. self.git = self.GitCommandWrapperType(self.working_dir)
  258. # Special handling, in special times.
  259. rootpath = osp.join(self.common_dir, "objects")
  260. if issubclass(odbt, GitCmdObjectDB):
  261. self.odb = odbt(rootpath, self.git)
  262. else:
  263. self.odb = odbt(rootpath)
  264. def __enter__(self) -> "Repo":
  265. return self
  266. def __exit__(self, *args: Any) -> None:
  267. self.close()
  268. def __del__(self) -> None:
  269. try:
  270. self.close()
  271. except Exception:
  272. pass
  273. def close(self) -> None:
  274. if self.git:
  275. self.git.clear_cache()
  276. # Tempfiles objects on Windows are holding references to open files until
  277. # they are collected by the garbage collector, thus preventing deletion.
  278. # TODO: Find these references and ensure they are closed and deleted
  279. # synchronously rather than forcing a gc collection.
  280. if sys.platform == "win32":
  281. gc.collect()
  282. gitdb.util.mman.collect()
  283. if sys.platform == "win32":
  284. gc.collect()
  285. def __eq__(self, rhs: object) -> bool:
  286. if isinstance(rhs, Repo):
  287. return self.git_dir == rhs.git_dir
  288. return False
  289. def __ne__(self, rhs: object) -> bool:
  290. return not self.__eq__(rhs)
  291. def __hash__(self) -> int:
  292. return hash(self.git_dir)
  293. @property
  294. def description(self) -> str:
  295. """The project's description"""
  296. filename = osp.join(self.git_dir, "description")
  297. with open(filename, "rb") as fp:
  298. return fp.read().rstrip().decode(defenc)
  299. @description.setter
  300. def description(self, descr: str) -> None:
  301. filename = osp.join(self.git_dir, "description")
  302. with open(filename, "wb") as fp:
  303. fp.write((descr + "\n").encode(defenc))
  304. @property
  305. def working_tree_dir(self) -> Optional[PathLike]:
  306. """
  307. :return:
  308. The working tree directory of our git repository.
  309. If this is a bare repository, ``None`` is returned.
  310. """
  311. return self._working_tree_dir
  312. @property
  313. def common_dir(self) -> PathLike:
  314. """
  315. :return:
  316. The git dir that holds everything except possibly HEAD, FETCH_HEAD,
  317. ORIG_HEAD, COMMIT_EDITMSG, index, and logs/.
  318. """
  319. return self._common_dir or self.git_dir
  320. @property
  321. def bare(self) -> bool:
  322. """:return: ``True`` if the repository is bare"""
  323. return self._bare
  324. @property
  325. def heads(self) -> "IterableList[Head]":
  326. """A list of :class:`~git.refs.head.Head` objects representing the branch heads
  327. in this repo.
  328. :return:
  329. ``git.IterableList(Head, ...)``
  330. """
  331. return Head.list_items(self)
  332. @property
  333. def branches(self) -> "IterableList[Head]":
  334. """Alias for heads.
  335. A list of :class:`~git.refs.head.Head` objects representing the branch heads
  336. in this repo.
  337. :return:
  338. ``git.IterableList(Head, ...)``
  339. """
  340. return self.heads
  341. @property
  342. def references(self) -> "IterableList[Reference]":
  343. """A list of :class:`~git.refs.reference.Reference` objects representing tags,
  344. heads and remote references.
  345. :return:
  346. ``git.IterableList(Reference, ...)``
  347. """
  348. return Reference.list_items(self)
  349. @property
  350. def refs(self) -> "IterableList[Reference]":
  351. """Alias for references.
  352. A list of :class:`~git.refs.reference.Reference` objects representing tags,
  353. heads and remote references.
  354. :return:
  355. ``git.IterableList(Reference, ...)``
  356. """
  357. return self.references
  358. @property
  359. def index(self) -> "IndexFile":
  360. """
  361. :return:
  362. A :class:`~git.index.base.IndexFile` representing this repository's index.
  363. :note:
  364. This property can be expensive, as the returned
  365. :class:`~git.index.base.IndexFile` will be reinitialized.
  366. It is recommended to reuse the object.
  367. """
  368. return IndexFile(self)
  369. @property
  370. def head(self) -> "HEAD":
  371. """
  372. :return:
  373. :class:`~git.refs.head.HEAD` object pointing to the current head reference
  374. """
  375. return HEAD(self, "HEAD")
  376. @property
  377. def remotes(self) -> "IterableList[Remote]":
  378. """A list of :class:`~git.remote.Remote` objects allowing to access and
  379. manipulate remotes.
  380. :return:
  381. ``git.IterableList(Remote, ...)``
  382. """
  383. return Remote.list_items(self)
  384. def remote(self, name: str = "origin") -> "Remote":
  385. """:return: The remote with the specified name
  386. :raise ValueError:
  387. If no remote with such a name exists.
  388. """
  389. r = Remote(self, name)
  390. if not r.exists():
  391. raise ValueError("Remote named '%s' didn't exist" % name)
  392. return r
  393. # { Submodules
  394. @property
  395. def submodules(self) -> "IterableList[Submodule]":
  396. """
  397. :return:
  398. git.IterableList(Submodule, ...) of direct submodules available from the
  399. current head
  400. """
  401. return Submodule.list_items(self)
  402. def submodule(self, name: str) -> "Submodule":
  403. """:return: The submodule with the given name
  404. :raise ValueError:
  405. If no such submodule exists.
  406. """
  407. try:
  408. return self.submodules[name]
  409. except IndexError as e:
  410. raise ValueError("Didn't find submodule named %r" % name) from e
  411. # END exception handling
  412. def create_submodule(self, *args: Any, **kwargs: Any) -> Submodule:
  413. """Create a new submodule.
  414. :note:
  415. For a description of the applicable parameters, see the documentation of
  416. :meth:`Submodule.add <git.objects.submodule.base.Submodule.add>`.
  417. :return:
  418. The created submodule.
  419. """
  420. return Submodule.add(self, *args, **kwargs)
  421. def iter_submodules(self, *args: Any, **kwargs: Any) -> Iterator[Submodule]:
  422. """An iterator yielding Submodule instances.
  423. See the :class:`~git.objects.util.Traversable` interface for a description of `args`
  424. and `kwargs`.
  425. :return:
  426. Iterator
  427. """
  428. return RootModule(self).traverse(*args, **kwargs)
  429. def submodule_update(self, *args: Any, **kwargs: Any) -> RootModule:
  430. """Update the submodules, keeping the repository consistent as it will
  431. take the previous state into consideration.
  432. :note:
  433. For more information, please see the documentation of
  434. :meth:`RootModule.update <git.objects.submodule.root.RootModule.update>`.
  435. """
  436. return RootModule(self).update(*args, **kwargs)
  437. # }END submodules
  438. @property
  439. def tags(self) -> "IterableList[TagReference]":
  440. """A list of :class:`~git.refs.tag.TagReference` objects that are available in
  441. this repo.
  442. :return:
  443. ``git.IterableList(TagReference, ...)``
  444. """
  445. return TagReference.list_items(self)
  446. def tag(self, path: PathLike) -> TagReference:
  447. """
  448. :return:
  449. :class:`~git.refs.tag.TagReference` object, reference pointing to a
  450. :class:`~git.objects.commit.Commit` or tag
  451. :param path:
  452. Path to the tag reference, e.g. ``0.1.5`` or ``tags/0.1.5``.
  453. """
  454. full_path = self._to_full_tag_path(path)
  455. return TagReference(self, full_path)
  456. @staticmethod
  457. def _to_full_tag_path(path: PathLike) -> str:
  458. path_str = str(path)
  459. if path_str.startswith(TagReference._common_path_default + "/"):
  460. return path_str
  461. if path_str.startswith(TagReference._common_default + "/"):
  462. return Reference._common_path_default + "/" + path_str
  463. else:
  464. return TagReference._common_path_default + "/" + path_str
  465. def create_head(
  466. self,
  467. path: PathLike,
  468. commit: Union["SymbolicReference", "str"] = "HEAD",
  469. force: bool = False,
  470. logmsg: Optional[str] = None,
  471. ) -> "Head":
  472. """Create a new head within the repository.
  473. :note:
  474. For more documentation, please see the
  475. :meth:`Head.create <git.refs.head.Head.create>` method.
  476. :return:
  477. Newly created :class:`~git.refs.head.Head` Reference.
  478. """
  479. return Head.create(self, path, commit, logmsg, force)
  480. def delete_head(self, *heads: "Union[str, Head]", **kwargs: Any) -> None:
  481. """Delete the given heads.
  482. :param kwargs:
  483. Additional keyword arguments to be passed to :manpage:`git-branch(1)`.
  484. """
  485. return Head.delete(self, *heads, **kwargs)
  486. def create_tag(
  487. self,
  488. path: PathLike,
  489. ref: Union[str, "SymbolicReference"] = "HEAD",
  490. message: Optional[str] = None,
  491. force: bool = False,
  492. **kwargs: Any,
  493. ) -> TagReference:
  494. """Create a new tag reference.
  495. :note:
  496. For more documentation, please see the
  497. :meth:`TagReference.create <git.refs.tag.TagReference.create>` method.
  498. :return:
  499. :class:`~git.refs.tag.TagReference` object
  500. """
  501. return TagReference.create(self, path, ref, message, force, **kwargs)
  502. def delete_tag(self, *tags: TagReference) -> None:
  503. """Delete the given tag references."""
  504. return TagReference.delete(self, *tags)
  505. def create_remote(self, name: str, url: str, **kwargs: Any) -> Remote:
  506. """Create a new remote.
  507. For more information, please see the documentation of the
  508. :meth:`Remote.create <git.remote.Remote.create>` method.
  509. :return:
  510. :class:`~git.remote.Remote` reference
  511. """
  512. return Remote.create(self, name, url, **kwargs)
  513. def delete_remote(self, remote: "Remote") -> str:
  514. """Delete the given remote."""
  515. return Remote.remove(self, remote)
  516. def _get_config_path(self, config_level: Lit_config_levels, git_dir: Optional[PathLike] = None) -> str:
  517. if git_dir is None:
  518. git_dir = self.git_dir
  519. # We do not support an absolute path of the gitconfig on Windows.
  520. # Use the global config instead.
  521. if sys.platform == "win32" and config_level == "system":
  522. config_level = "global"
  523. if config_level == "system":
  524. return "/etc/gitconfig"
  525. elif config_level == "user":
  526. config_home = os.environ.get("XDG_CONFIG_HOME") or osp.join(os.environ.get("HOME", "~"), ".config")
  527. return osp.normpath(osp.expanduser(osp.join(config_home, "git", "config")))
  528. elif config_level == "global":
  529. return osp.normpath(osp.expanduser("~/.gitconfig"))
  530. elif config_level == "repository":
  531. repo_dir = self._common_dir or git_dir
  532. if not repo_dir:
  533. raise NotADirectoryError
  534. else:
  535. return osp.normpath(osp.join(repo_dir, "config"))
  536. else:
  537. assert_never( # type: ignore[unreachable]
  538. config_level,
  539. ValueError(f"Invalid configuration level: {config_level!r}"),
  540. )
  541. def config_reader(
  542. self,
  543. config_level: Optional[Lit_config_levels] = None,
  544. ) -> GitConfigParser:
  545. """
  546. :return:
  547. :class:`~git.config.GitConfigParser` allowing to read the full git
  548. configuration, but not to write it.
  549. The configuration will include values from the system, user and repository
  550. configuration files.
  551. :param config_level:
  552. For possible values, see the :meth:`config_writer` method. If ``None``, all
  553. applicable levels will be used. Specify a level in case you know which file
  554. you wish to read to prevent reading multiple files.
  555. :note:
  556. On Windows, system configuration cannot currently be read as the path is
  557. unknown, instead the global path will be used.
  558. """
  559. return self._config_reader(config_level=config_level)
  560. def _config_reader(
  561. self,
  562. config_level: Optional[Lit_config_levels] = None,
  563. git_dir: Optional[PathLike] = None,
  564. ) -> GitConfigParser:
  565. if config_level is None:
  566. files = [self._get_config_path(f, git_dir) for f in self.config_level if f]
  567. else:
  568. files = [self._get_config_path(config_level, git_dir)]
  569. return GitConfigParser(files, read_only=True, repo=self)
  570. def config_writer(self, config_level: Lit_config_levels = "repository") -> GitConfigParser:
  571. """
  572. :return:
  573. A :class:`~git.config.GitConfigParser` allowing to write values of the
  574. specified configuration file level. Config writers should be retrieved, used
  575. to change the configuration, and written right away as they will lock the
  576. configuration file in question and prevent other's to write it.
  577. :param config_level:
  578. One of the following values:
  579. * ``"system"`` = system wide configuration file
  580. * ``"global"`` = user level configuration file
  581. * ``"`repository"`` = configuration file for this repository only
  582. """
  583. return GitConfigParser(self._get_config_path(config_level), read_only=False, repo=self, merge_includes=False)
  584. def commit(self, rev: Union[str, Commit_ish, None] = None) -> Commit:
  585. """The :class:`~git.objects.commit.Commit` object for the specified revision.
  586. :param rev:
  587. Revision specifier, see :manpage:`git-rev-parse(1)` for viable options.
  588. :return:
  589. :class:`~git.objects.commit.Commit`
  590. """
  591. if rev is None:
  592. return self.head.commit
  593. return self.rev_parse(str(rev) + "^0")
  594. def iter_trees(self, *args: Any, **kwargs: Any) -> Iterator["Tree"]:
  595. """:return: Iterator yielding :class:`~git.objects.tree.Tree` objects
  596. :note:
  597. Accepts all arguments known to the :meth:`iter_commits` method.
  598. """
  599. return (c.tree for c in self.iter_commits(*args, **kwargs))
  600. def tree(self, rev: Union[Tree_ish, str, None] = None) -> "Tree":
  601. """The :class:`~git.objects.tree.Tree` object for the given tree-ish revision.
  602. Examples::
  603. repo.tree(repo.heads[0])
  604. :param rev:
  605. A revision pointing to a Treeish (being a commit or tree).
  606. :return:
  607. :class:`~git.objects.tree.Tree`
  608. :note:
  609. If you need a non-root level tree, find it by iterating the root tree.
  610. Otherwise it cannot know about its path relative to the repository root and
  611. subsequent operations might have unexpected results.
  612. """
  613. if rev is None:
  614. return self.head.commit.tree
  615. return self.rev_parse(str(rev) + "^{tree}")
  616. def iter_commits(
  617. self,
  618. rev: Union[str, Commit, "SymbolicReference", None] = None,
  619. paths: Union[PathLike, Sequence[PathLike]] = "",
  620. **kwargs: Any,
  621. ) -> Iterator[Commit]:
  622. """An iterator of :class:`~git.objects.commit.Commit` objects representing the
  623. history of a given ref/commit.
  624. :param rev:
  625. Revision specifier, see :manpage:`git-rev-parse(1)` for viable options.
  626. If ``None``, the active branch will be used.
  627. :param paths:
  628. An optional path or a list of paths. If set, only commits that include the
  629. path or paths will be returned.
  630. :param kwargs:
  631. Arguments to be passed to :manpage:`git-rev-list(1)`.
  632. Common ones are ``max_count`` and ``skip``.
  633. :note:
  634. To receive only commits between two named revisions, use the
  635. ``"revA...revB"`` revision specifier.
  636. :return:
  637. Iterator of :class:`~git.objects.commit.Commit` objects
  638. """
  639. if rev is None:
  640. rev = self.head.commit
  641. return Commit.iter_items(self, rev, paths, **kwargs)
  642. def merge_base(self, *rev: TBD, **kwargs: Any) -> List[Commit]:
  643. R"""Find the closest common ancestor for the given revision
  644. (:class:`~git.objects.commit.Commit`\s, :class:`~git.refs.tag.Tag`\s,
  645. :class:`~git.refs.reference.Reference`\s, etc.).
  646. :param rev:
  647. At least two revs to find the common ancestor for.
  648. :param kwargs:
  649. Additional arguments to be passed to the ``repo.git.merge_base()`` command
  650. which does all the work.
  651. :return:
  652. A list of :class:`~git.objects.commit.Commit` objects. If ``--all`` was
  653. not passed as a keyword argument, the list will have at max one
  654. :class:`~git.objects.commit.Commit`, or is empty if no common merge base
  655. exists.
  656. :raise ValueError:
  657. If fewer than two revisions are provided.
  658. """
  659. if len(rev) < 2:
  660. raise ValueError("Please specify at least two revs, got only %i" % len(rev))
  661. # END handle input
  662. res: List[Commit] = []
  663. try:
  664. lines: List[str] = self.git.merge_base(*rev, **kwargs).splitlines()
  665. except GitCommandError as err:
  666. if err.status == 128:
  667. raise
  668. # END handle invalid rev
  669. # Status code 1 is returned if there is no merge-base.
  670. # (See: https://github.com/git/git/blob/v2.44.0/builtin/merge-base.c#L19)
  671. return res
  672. # END exception handling
  673. for line in lines:
  674. res.append(self.commit(line))
  675. # END for each merge-base
  676. return res
  677. def is_ancestor(self, ancestor_rev: Commit, rev: Commit) -> bool:
  678. """Check if a commit is an ancestor of another.
  679. :param ancestor_rev:
  680. Rev which should be an ancestor.
  681. :param rev:
  682. Rev to test against `ancestor_rev`.
  683. :return:
  684. ``True`` if `ancestor_rev` is an ancestor to `rev`.
  685. """
  686. try:
  687. self.git.merge_base(ancestor_rev, rev, is_ancestor=True)
  688. except GitCommandError as err:
  689. if err.status == 1:
  690. return False
  691. raise
  692. return True
  693. def is_valid_object(self, sha: str, object_type: Union[str, None] = None) -> bool:
  694. try:
  695. complete_sha = self.odb.partial_to_complete_sha_hex(sha)
  696. object_info = self.odb.info(complete_sha)
  697. if object_type:
  698. if object_info.type == object_type.encode():
  699. return True
  700. else:
  701. _logger.debug(
  702. "Commit hash points to an object of type '%s'. Requested were objects of type '%s'",
  703. object_info.type.decode(),
  704. object_type,
  705. )
  706. return False
  707. else:
  708. return True
  709. except BadObject:
  710. _logger.debug("Commit hash is invalid.")
  711. return False
  712. def _get_daemon_export(self) -> bool:
  713. if self.git_dir:
  714. filename = osp.join(self.git_dir, self.DAEMON_EXPORT_FILE)
  715. return osp.exists(filename)
  716. def _set_daemon_export(self, value: object) -> None:
  717. if self.git_dir:
  718. filename = osp.join(self.git_dir, self.DAEMON_EXPORT_FILE)
  719. fileexists = osp.exists(filename)
  720. if value and not fileexists:
  721. touch(filename)
  722. elif not value and fileexists:
  723. os.unlink(filename)
  724. @property
  725. def daemon_export(self) -> bool:
  726. """If True, git-daemon may export this repository"""
  727. return self._get_daemon_export()
  728. @daemon_export.setter
  729. def daemon_export(self, value: object) -> None:
  730. self._set_daemon_export(value)
  731. def _get_alternates(self) -> List[str]:
  732. """The list of alternates for this repo from which objects can be retrieved.
  733. :return:
  734. List of strings being pathnames of alternates
  735. """
  736. if self.git_dir:
  737. alternates_path = osp.join(self.git_dir, "objects", "info", "alternates")
  738. if osp.exists(alternates_path):
  739. with open(alternates_path, "rb") as f:
  740. alts = f.read().decode(defenc)
  741. return alts.strip().splitlines()
  742. return []
  743. def _set_alternates(self, alts: List[str]) -> None:
  744. """Set the alternates.
  745. :param alts:
  746. The array of string paths representing the alternates at which git should
  747. look for objects, i.e. ``/home/user/repo/.git/objects``.
  748. :raise git.exc.NoSuchPathError:
  749. :note:
  750. The method does not check for the existence of the paths in `alts`, as the
  751. caller is responsible.
  752. """
  753. alternates_path = osp.join(self.common_dir, "objects", "info", "alternates")
  754. if not alts:
  755. if osp.isfile(alternates_path):
  756. os.remove(alternates_path)
  757. else:
  758. with open(alternates_path, "wb") as f:
  759. f.write("\n".join(alts).encode(defenc))
  760. @property
  761. def alternates(self) -> List[str]:
  762. """Retrieve a list of alternates paths or set a list paths to be used as alternates"""
  763. return self._get_alternates()
  764. @alternates.setter
  765. def alternates(self, alts: List[str]) -> None:
  766. self._set_alternates(alts)
  767. def is_dirty(
  768. self,
  769. index: bool = True,
  770. working_tree: bool = True,
  771. untracked_files: bool = False,
  772. submodules: bool = True,
  773. path: Optional[PathLike] = None,
  774. ) -> bool:
  775. """
  776. :return:
  777. ``True`` if the repository is considered dirty. By default it will react
  778. like a :manpage:`git-status(1)` without untracked files, hence it is dirty
  779. if the index or the working copy have changes.
  780. """
  781. if self._bare:
  782. # Bare repositories with no associated working directory are
  783. # always considered to be clean.
  784. return False
  785. # Start from the one which is fastest to evaluate.
  786. default_args = ["--abbrev=40", "--full-index", "--raw"]
  787. if not submodules:
  788. default_args.append("--ignore-submodules")
  789. if path:
  790. default_args.extend(["--", os.fspath(path)])
  791. if index:
  792. # diff index against HEAD.
  793. if osp.isfile(self.index.path) and len(self.git.diff("--cached", *default_args)):
  794. return True
  795. # END index handling
  796. if working_tree:
  797. # diff index against working tree.
  798. if len(self.git.diff(*default_args)):
  799. return True
  800. # END working tree handling
  801. if untracked_files:
  802. if len(self._get_untracked_files(path, ignore_submodules=not submodules)):
  803. return True
  804. # END untracked files
  805. return False
  806. @property
  807. def untracked_files(self) -> List[str]:
  808. """
  809. :return:
  810. list(str,...)
  811. Files currently untracked as they have not been staged yet. Paths are
  812. relative to the current working directory of the git command.
  813. :note:
  814. Ignored files will not appear here, i.e. files mentioned in ``.gitignore``.
  815. :note:
  816. This property is expensive, as no cache is involved. To process the result,
  817. please consider caching it yourself.
  818. """
  819. return self._get_untracked_files()
  820. def _get_untracked_files(self, *args: Any, **kwargs: Any) -> List[str]:
  821. # Make sure we get all files, not only untracked directories.
  822. proc = self.git.status(*args, porcelain=True, untracked_files=True, as_process=True, **kwargs)
  823. # Untracked files prefix in porcelain mode
  824. prefix = "?? "
  825. untracked_files = []
  826. for line in proc.stdout:
  827. line = line.decode(defenc)
  828. if not line.startswith(prefix):
  829. continue
  830. filename = line[len(prefix) :].rstrip("\n")
  831. # Special characters are escaped
  832. if filename[0] == filename[-1] == '"':
  833. filename = filename[1:-1]
  834. # WHATEVER ... it's a mess, but works for me
  835. filename = filename.encode("ascii").decode("unicode_escape").encode("latin1").decode(defenc)
  836. untracked_files.append(filename)
  837. finalize_process(proc)
  838. return untracked_files
  839. def ignored(self, *paths: PathLike) -> List[str]:
  840. """Checks if paths are ignored via ``.gitignore``.
  841. This does so using the :manpage:`git-check-ignore(1)` method.
  842. :param paths:
  843. List of paths to check whether they are ignored or not.
  844. :return:
  845. Subset of those paths which are ignored
  846. """
  847. try:
  848. proc: str = self.git.check_ignore(*paths)
  849. except GitCommandError as err:
  850. if err.status == 1:
  851. # If return code is 1, this means none of the items in *paths are
  852. # ignored by Git, so return an empty list.
  853. return []
  854. else:
  855. # Raise the exception on all other return codes.
  856. raise
  857. return proc.replace("\\\\", "\\").replace('"', "").split("\n")
  858. @property
  859. def active_branch(self) -> Head:
  860. """The name of the currently active branch.
  861. :raise TypeError:
  862. If HEAD is detached.
  863. :return:
  864. :class:`~git.refs.head.Head` to the active branch
  865. """
  866. # reveal_type(self.head.reference) # => Reference
  867. return self.head.reference
  868. def blame_incremental(self, rev: str | HEAD | None, file: str, **kwargs: Any) -> Iterator["BlameEntry"]:
  869. """Iterator for blame information for the given file at the given revision.
  870. Unlike :meth:`blame`, this does not return the actual file's contents, only a
  871. stream of :class:`BlameEntry` tuples.
  872. :param rev:
  873. Revision specifier. If ``None``, the blame will include all the latest
  874. uncommitted changes. Otherwise, anything successfully parsed by
  875. :manpage:`git-rev-parse(1)` is a valid option.
  876. :return:
  877. Lazy iterator of :class:`BlameEntry` tuples, where the commit indicates the
  878. commit to blame for the line, and range indicates a span of line numbers in
  879. the resulting file.
  880. If you combine all line number ranges outputted by this command, you should get
  881. a continuous range spanning all line numbers in the file.
  882. """
  883. data: bytes = self.git.blame(rev, "--", file, p=True, incremental=True, stdout_as_string=False, **kwargs)
  884. commits: Dict[bytes, Commit] = {}
  885. stream = (line for line in data.split(b"\n") if line)
  886. while True:
  887. try:
  888. # When exhausted, causes a StopIteration, terminating this function.
  889. line = next(stream)
  890. except StopIteration:
  891. return
  892. split_line = line.split()
  893. hexsha, orig_lineno_b, lineno_b, num_lines_b = split_line
  894. lineno = int(lineno_b)
  895. num_lines = int(num_lines_b)
  896. orig_lineno = int(orig_lineno_b)
  897. if hexsha not in commits:
  898. # Now read the next few lines and build up a dict of properties for this
  899. # commit.
  900. props: Dict[bytes, bytes] = {}
  901. while True:
  902. try:
  903. line = next(stream)
  904. except StopIteration:
  905. return
  906. if line == b"boundary":
  907. # "boundary" indicates a root commit and occurs instead of the
  908. # "previous" tag.
  909. continue
  910. tag, value = line.split(b" ", 1)
  911. props[tag] = value
  912. if tag == b"filename":
  913. # "filename" formally terminates the entry for --incremental.
  914. orig_filename = value
  915. break
  916. c = Commit(
  917. self,
  918. hex_to_bin(hexsha),
  919. author=Actor(
  920. safe_decode(props[b"author"]),
  921. safe_decode(props[b"author-mail"].lstrip(b"<").rstrip(b">")),
  922. ),
  923. authored_date=int(props[b"author-time"]),
  924. committer=Actor(
  925. safe_decode(props[b"committer"]),
  926. safe_decode(props[b"committer-mail"].lstrip(b"<").rstrip(b">")),
  927. ),
  928. committed_date=int(props[b"committer-time"]),
  929. )
  930. commits[hexsha] = c
  931. else:
  932. # Discard all lines until we find "filename" which is guaranteed to be
  933. # the last line.
  934. while True:
  935. try:
  936. # Will fail if we reach the EOF unexpectedly.
  937. line = next(stream)
  938. except StopIteration:
  939. return
  940. tag, value = line.split(b" ", 1)
  941. if tag == b"filename":
  942. orig_filename = value
  943. break
  944. yield BlameEntry(
  945. commits[hexsha],
  946. range(lineno, lineno + num_lines),
  947. safe_decode(orig_filename),
  948. range(orig_lineno, orig_lineno + num_lines),
  949. )
  950. def blame(
  951. self,
  952. rev: Union[str, HEAD, None],
  953. file: str,
  954. incremental: bool = False,
  955. rev_opts: Optional[List[str]] = None,
  956. **kwargs: Any,
  957. ) -> List[List[Commit | List[str | bytes] | None]] | Iterator[BlameEntry] | None:
  958. """The blame information for the given file at the given revision.
  959. :param rev:
  960. Revision specifier. If ``None``, the blame will include all the latest
  961. uncommitted changes. Otherwise, anything successfully parsed by
  962. :manpage:`git-rev-parse(1)` is a valid option.
  963. :return:
  964. list: [git.Commit, list: [<line>]]
  965. A list of lists associating a :class:`~git.objects.commit.Commit` object
  966. with a list of lines that changed within the given commit. The
  967. :class:`~git.objects.commit.Commit` objects will be given in order of
  968. appearance.
  969. """
  970. if incremental:
  971. return self.blame_incremental(rev, file, **kwargs)
  972. rev_opts = rev_opts or []
  973. data: bytes = self.git.blame(rev, *rev_opts, "--", file, p=True, stdout_as_string=False, **kwargs)
  974. commits: Dict[str, Commit] = {}
  975. blames: List[List[Commit | List[str | bytes] | None]] = []
  976. class InfoTD(TypedDict, total=False):
  977. sha: str
  978. id: str
  979. filename: str
  980. summary: str
  981. author: str
  982. author_email: str
  983. author_date: int
  984. committer: str
  985. committer_email: str
  986. committer_date: int
  987. info: InfoTD = {}
  988. keepends = True
  989. for line_bytes in data.splitlines(keepends):
  990. try:
  991. line_str = line_bytes.rstrip().decode(defenc)
  992. except UnicodeDecodeError:
  993. firstpart = ""
  994. parts = []
  995. is_binary = True
  996. else:
  997. # As we don't have an idea when the binary data ends, as it could
  998. # contain multiple newlines in the process. So we rely on being able to
  999. # decode to tell us what it is. This can absolutely fail even on text
  1000. # files, but even if it does, we should be fine treating it as binary
  1001. # instead.
  1002. parts = self.re_whitespace.split(line_str, 1)
  1003. firstpart = parts[0]
  1004. is_binary = False
  1005. # END handle decode of line
  1006. if self.re_hexsha_only.search(firstpart):
  1007. # handles
  1008. # 634396b2f541a9f2d58b00be1a07f0c358b999b3 1 1 7 - indicates blame-data start
  1009. # 634396b2f541a9f2d58b00be1a07f0c358b999b3 2 2 - indicates
  1010. # another line of blame with the same data
  1011. digits = parts[-1].split(" ")
  1012. if len(digits) == 3:
  1013. info = {"id": firstpart}
  1014. blames.append([None, []])
  1015. elif info["id"] != firstpart:
  1016. info = {"id": firstpart}
  1017. blames.append([commits.get(firstpart), []])
  1018. # END blame data initialization
  1019. else:
  1020. m = self.re_author_committer_start.search(firstpart)
  1021. if m:
  1022. # handles:
  1023. # author Tom Preston-Werner
  1024. # author-mail <tom@mojombo.com>
  1025. # author-time 1192271832
  1026. # author-tz -0700
  1027. # committer Tom Preston-Werner
  1028. # committer-mail <tom@mojombo.com>
  1029. # committer-time 1192271832
  1030. # committer-tz -0700 - IGNORED BY US
  1031. role = m.group(0)
  1032. if role == "author":
  1033. if firstpart.endswith("-mail"):
  1034. info["author_email"] = parts[-1]
  1035. elif firstpart.endswith("-time"):
  1036. info["author_date"] = int(parts[-1])
  1037. elif role == firstpart:
  1038. info["author"] = parts[-1]
  1039. elif role == "committer":
  1040. if firstpart.endswith("-mail"):
  1041. info["committer_email"] = parts[-1]
  1042. elif firstpart.endswith("-time"):
  1043. info["committer_date"] = int(parts[-1])
  1044. elif role == firstpart:
  1045. info["committer"] = parts[-1]
  1046. # END distinguish mail,time,name
  1047. else:
  1048. # handle
  1049. # filename lib/grit.rb
  1050. # summary add Blob
  1051. # <and rest>
  1052. if firstpart.startswith("filename"):
  1053. info["filename"] = parts[-1]
  1054. elif firstpart.startswith("summary"):
  1055. info["summary"] = parts[-1]
  1056. elif firstpart == "":
  1057. if info:
  1058. sha = info["id"]
  1059. c = commits.get(sha)
  1060. if c is None:
  1061. c = Commit(
  1062. self,
  1063. hex_to_bin(sha),
  1064. author=Actor._from_string(f"{info['author']} {info['author_email']}"),
  1065. authored_date=info["author_date"],
  1066. committer=Actor._from_string(f"{info['committer']} {info['committer_email']}"),
  1067. committed_date=info["committer_date"],
  1068. )
  1069. commits[sha] = c
  1070. blames[-1][0] = c
  1071. # END if commit objects needs initial creation
  1072. if blames[-1][1] is not None:
  1073. line: str | bytes
  1074. if not is_binary:
  1075. if line_str and line_str[0] == "\t":
  1076. line_str = line_str[1:]
  1077. line = line_str
  1078. else:
  1079. line = line_bytes
  1080. # NOTE: We are actually parsing lines out of binary
  1081. # data, which can lead to the binary being split up
  1082. # along the newline separator. We will append this
  1083. # to the blame we are currently looking at, even
  1084. # though it should be concatenated with the last
  1085. # line we have seen.
  1086. blames[-1][1].append(line)
  1087. info = {"id": sha}
  1088. # END if we collected commit info
  1089. # END distinguish filename,summary,rest
  1090. # END distinguish author|committer vs filename,summary,rest
  1091. # END distinguish hexsha vs other information
  1092. return blames
  1093. @classmethod
  1094. def init(
  1095. cls,
  1096. path: Union[PathLike, None] = None,
  1097. mkdir: bool = True,
  1098. odbt: Type[GitCmdObjectDB] = GitCmdObjectDB,
  1099. expand_vars: bool = True,
  1100. **kwargs: Any,
  1101. ) -> "Repo":
  1102. """Initialize a git repository at the given path if specified.
  1103. :param path:
  1104. The full path to the repo (traditionally ends with ``/<name>.git``). Or
  1105. ``None``, in which case the repository will be created in the current
  1106. working directory.
  1107. :param mkdir:
  1108. If specified, will create the repository directory if it doesn't already
  1109. exist. Creates the directory with a mode=0755.
  1110. Only effective if a path is explicitly given.
  1111. :param odbt:
  1112. Object DataBase type - a type which is constructed by providing the
  1113. directory containing the database objects, i.e. ``.git/objects``. It will be
  1114. used to access all object data.
  1115. :param expand_vars:
  1116. If specified, environment variables will not be escaped. This can lead to
  1117. information disclosure, allowing attackers to access the contents of
  1118. environment variables.
  1119. :param kwargs:
  1120. Keyword arguments serving as additional options to the
  1121. :manpage:`git-init(1)` command.
  1122. :return:
  1123. :class:`Repo` (the newly created repo)
  1124. """
  1125. if path:
  1126. path = expand_path(path, expand_vars)
  1127. if mkdir and path and not osp.exists(path):
  1128. os.makedirs(path, 0o755)
  1129. # git command automatically chdir into the directory
  1130. git = cls.GitCommandWrapperType(path)
  1131. git.init(**kwargs)
  1132. return cls(path, odbt=odbt)
  1133. @classmethod
  1134. def _clone(
  1135. cls,
  1136. git: "Git",
  1137. url: PathLike,
  1138. path: PathLike,
  1139. odb_default_type: Type[GitCmdObjectDB],
  1140. progress: Union["RemoteProgress", "UpdateProgress", Callable[..., "RemoteProgress"], None] = None,
  1141. multi_options: Optional[List[str]] = None,
  1142. allow_unsafe_protocols: bool = False,
  1143. allow_unsafe_options: bool = False,
  1144. **kwargs: Any,
  1145. ) -> "Repo":
  1146. odbt = kwargs.pop("odbt", odb_default_type)
  1147. # url may be a path and this has no effect if it is a string
  1148. url = os.fspath(url)
  1149. path = os.fspath(path)
  1150. ## A bug win cygwin's Git, when `--bare` or `--separate-git-dir`
  1151. # it prepends the cwd or(?) the `url` into the `path, so::
  1152. # git clone --bare /cygwin/d/foo.git C:\\Work
  1153. # becomes::
  1154. # git clone --bare /cygwin/d/foo.git /cygwin/d/C:\\Work
  1155. #
  1156. clone_path = Git.polish_url(path) if Git.is_cygwin() and "bare" in kwargs else path
  1157. sep_dir = kwargs.get("separate_git_dir")
  1158. if sep_dir:
  1159. kwargs["separate_git_dir"] = Git.polish_url(sep_dir)
  1160. multi = None
  1161. if multi_options:
  1162. multi = shlex.split(" ".join(multi_options))
  1163. if not allow_unsafe_protocols:
  1164. Git.check_unsafe_protocols(url)
  1165. if not allow_unsafe_options:
  1166. Git.check_unsafe_options(options=list(kwargs.keys()), unsafe_options=cls.unsafe_git_clone_options)
  1167. if not allow_unsafe_options and multi_options:
  1168. Git.check_unsafe_options(options=multi_options, unsafe_options=cls.unsafe_git_clone_options)
  1169. proc = git.clone(
  1170. multi,
  1171. "--",
  1172. Git.polish_url(url),
  1173. clone_path,
  1174. with_extended_output=True,
  1175. as_process=True,
  1176. v=True,
  1177. universal_newlines=True,
  1178. **add_progress(kwargs, git, progress),
  1179. )
  1180. if progress:
  1181. handle_process_output(
  1182. proc,
  1183. None,
  1184. to_progress_instance(progress).new_message_handler(),
  1185. finalize_process,
  1186. decode_streams=False,
  1187. )
  1188. else:
  1189. (stdout, stderr) = proc.communicate()
  1190. cmdline = getattr(proc, "args", "")
  1191. cmdline = remove_password_if_present(cmdline)
  1192. _logger.debug("Cmd(%s)'s unused stdout: %s", cmdline, stdout)
  1193. finalize_process(proc, stderr=stderr)
  1194. # Our git command could have a different working dir than our actual
  1195. # environment, hence we prepend its working dir if required.
  1196. if not osp.isabs(path):
  1197. path = osp.join(git._working_dir, path) if git._working_dir is not None else path
  1198. repo = cls(path, odbt=odbt)
  1199. # Retain env values that were passed to _clone().
  1200. repo.git.update_environment(**git.environment())
  1201. # Adjust remotes - there may be operating systems which use backslashes, These
  1202. # might be given as initial paths, but when handling the config file that
  1203. # contains the remote from which we were clones, git stops liking it as it will
  1204. # escape the backslashes. Hence we undo the escaping just to be sure.
  1205. if repo.remotes:
  1206. with repo.remotes[0].config_writer as writer:
  1207. writer.set_value("url", Git.polish_url(repo.remotes[0].url))
  1208. # END handle remote repo
  1209. return repo
  1210. def clone(
  1211. self,
  1212. path: PathLike,
  1213. progress: Optional[CallableProgress] = None,
  1214. multi_options: Optional[List[str]] = None,
  1215. allow_unsafe_protocols: bool = False,
  1216. allow_unsafe_options: bool = False,
  1217. **kwargs: Any,
  1218. ) -> "Repo":
  1219. """Create a clone from this repository.
  1220. :param path:
  1221. The full path of the new repo (traditionally ends with ``./<name>.git``).
  1222. :param progress:
  1223. See :meth:`Remote.push <git.remote.Remote.push>`.
  1224. :param multi_options:
  1225. A list of :manpage:`git-clone(1)` options that can be provided multiple
  1226. times.
  1227. One option per list item which is passed exactly as specified to clone.
  1228. For example::
  1229. [
  1230. "--config core.filemode=false",
  1231. "--config core.ignorecase",
  1232. "--recurse-submodule=repo1_path",
  1233. "--recurse-submodule=repo2_path",
  1234. ]
  1235. :param allow_unsafe_protocols:
  1236. Allow unsafe protocols to be used, like ``ext``.
  1237. :param allow_unsafe_options:
  1238. Allow unsafe options to be used, like ``--upload-pack``.
  1239. :param kwargs:
  1240. * ``odbt`` = ObjectDatabase Type, allowing to determine the object database
  1241. implementation used by the returned :class:`Repo` instance.
  1242. * All remaining keyword arguments are given to the :manpage:`git-clone(1)`
  1243. command.
  1244. :return:
  1245. :class:`Repo` (the newly cloned repo)
  1246. """
  1247. return self._clone(
  1248. self.git,
  1249. self.common_dir,
  1250. path,
  1251. type(self.odb),
  1252. progress, # type: ignore[arg-type]
  1253. multi_options,
  1254. allow_unsafe_protocols=allow_unsafe_protocols,
  1255. allow_unsafe_options=allow_unsafe_options,
  1256. **kwargs,
  1257. )
  1258. @classmethod
  1259. def clone_from(
  1260. cls,
  1261. url: PathLike,
  1262. to_path: PathLike,
  1263. progress: CallableProgress = None,
  1264. env: Optional[Mapping[str, str]] = None,
  1265. multi_options: Optional[List[str]] = None,
  1266. allow_unsafe_protocols: bool = False,
  1267. allow_unsafe_options: bool = False,
  1268. **kwargs: Any,
  1269. ) -> "Repo":
  1270. """Create a clone from the given URL.
  1271. :param url:
  1272. Valid git url, see: https://git-scm.com/docs/git-clone#URLS
  1273. :param to_path:
  1274. Path to which the repository should be cloned to.
  1275. :param progress:
  1276. See :meth:`Remote.push <git.remote.Remote.push>`.
  1277. :param env:
  1278. Optional dictionary containing the desired environment variables.
  1279. Note: Provided variables will be used to update the execution environment
  1280. for ``git``. If some variable is not specified in `env` and is defined in
  1281. :attr:`os.environ`, value from :attr:`os.environ` will be used. If you want
  1282. to unset some variable, consider providing empty string as its value.
  1283. :param multi_options:
  1284. See the :meth:`clone` method.
  1285. :param allow_unsafe_protocols:
  1286. Allow unsafe protocols to be used, like ``ext``.
  1287. :param allow_unsafe_options:
  1288. Allow unsafe options to be used, like ``--upload-pack``.
  1289. :param kwargs:
  1290. See the :meth:`clone` method.
  1291. :return:
  1292. :class:`Repo` instance pointing to the cloned directory.
  1293. """
  1294. git = cls.GitCommandWrapperType(os.getcwd())
  1295. if env is not None:
  1296. git.update_environment(**env)
  1297. return cls._clone(
  1298. git,
  1299. url,
  1300. to_path,
  1301. GitCmdObjectDB,
  1302. progress, # type: ignore[arg-type]
  1303. multi_options,
  1304. allow_unsafe_protocols=allow_unsafe_protocols,
  1305. allow_unsafe_options=allow_unsafe_options,
  1306. **kwargs,
  1307. )
  1308. def archive(
  1309. self,
  1310. ostream: Union[TextIO, BinaryIO],
  1311. treeish: Optional[str] = None,
  1312. prefix: Optional[str] = None,
  1313. **kwargs: Any,
  1314. ) -> Repo:
  1315. """Archive the tree at the given revision.
  1316. :param ostream:
  1317. File-compatible stream object to which the archive will be written as bytes.
  1318. :param treeish:
  1319. The treeish name/id, defaults to active branch.
  1320. :param prefix:
  1321. The optional prefix to prepend to each filename in the archive.
  1322. :param kwargs:
  1323. Additional arguments passed to :manpage:`git-archive(1)`:
  1324. * Use the ``format`` argument to define the kind of format. Use specialized
  1325. ostreams to write any format supported by Python.
  1326. * You may specify the special ``path`` keyword, which may either be a
  1327. repository-relative path to a directory or file to place into the archive,
  1328. or a list or tuple of multiple paths.
  1329. :raise git.exc.GitCommandError:
  1330. If something went wrong.
  1331. :return:
  1332. self
  1333. """
  1334. if treeish is None:
  1335. treeish = self.head.commit
  1336. if prefix and "prefix" not in kwargs:
  1337. kwargs["prefix"] = prefix
  1338. kwargs["output_stream"] = ostream
  1339. path = kwargs.pop("path", [])
  1340. path = cast(Union[PathLike, List[PathLike], Tuple[PathLike, ...]], path)
  1341. if not isinstance(path, (tuple, list)):
  1342. path = [path]
  1343. # END ensure paths is list (or tuple)
  1344. self.git.archive("--", treeish, *path, **kwargs)
  1345. return self
  1346. def has_separate_working_tree(self) -> bool:
  1347. """
  1348. :return:
  1349. True if our :attr:`git_dir` is not at the root of our
  1350. :attr:`working_tree_dir`, but a ``.git`` file with a platform-agnostic
  1351. symbolic link. Our :attr:`git_dir` will be wherever the ``.git`` file points
  1352. to.
  1353. :note:
  1354. Bare repositories will always return ``False`` here.
  1355. """
  1356. if self.bare:
  1357. return False
  1358. if self.working_tree_dir:
  1359. return osp.isfile(osp.join(self.working_tree_dir, ".git"))
  1360. else:
  1361. return False # Or raise Error?
  1362. rev_parse = rev_parse
  1363. def __repr__(self) -> str:
  1364. clazz = self.__class__
  1365. return "<%s.%s %r>" % (clazz.__module__, clazz.__name__, self.git_dir)
  1366. def currently_rebasing_on(self) -> Commit | None:
  1367. """
  1368. :return:
  1369. The commit which is currently being replayed while rebasing.
  1370. ``None`` if we are not currently rebasing.
  1371. """
  1372. if self.git_dir:
  1373. rebase_head_file = osp.join(self.git_dir, "REBASE_HEAD")
  1374. if not osp.isfile(rebase_head_file):
  1375. return None
  1376. with open(rebase_head_file, "rt") as f:
  1377. content = f.readline().strip()
  1378. return self.commit(content)