cmd.py 66 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741
  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__ = ["GitMeta", "Git"]
  7. import contextlib
  8. import io
  9. import itertools
  10. import logging
  11. import os
  12. import re
  13. import signal
  14. import subprocess
  15. from subprocess import DEVNULL, PIPE, Popen
  16. import sys
  17. from textwrap import dedent
  18. import threading
  19. import warnings
  20. from git.compat import defenc, force_bytes, safe_decode
  21. from git.exc import (
  22. CommandError,
  23. GitCommandError,
  24. GitCommandNotFound,
  25. UnsafeOptionError,
  26. UnsafeProtocolError,
  27. )
  28. from git.util import (
  29. cygpath,
  30. expand_path,
  31. is_cygwin_git,
  32. patch_env,
  33. remove_password_if_present,
  34. stream_copy,
  35. )
  36. # typing ---------------------------------------------------------------------------
  37. from typing import (
  38. Any,
  39. AnyStr,
  40. BinaryIO,
  41. Callable,
  42. Dict,
  43. IO,
  44. Iterator,
  45. List,
  46. Mapping,
  47. Optional,
  48. Sequence,
  49. TYPE_CHECKING,
  50. TextIO,
  51. Tuple,
  52. Union,
  53. cast,
  54. overload,
  55. )
  56. if sys.version_info >= (3, 10):
  57. from typing import TypeAlias
  58. else:
  59. from typing_extensions import TypeAlias
  60. from git.types import Literal, PathLike, TBD
  61. if TYPE_CHECKING:
  62. from git.diff import DiffIndex
  63. from git.repo.base import Repo
  64. # ---------------------------------------------------------------------------------
  65. execute_kwargs = {
  66. "istream",
  67. "with_extended_output",
  68. "with_exceptions",
  69. "as_process",
  70. "output_stream",
  71. "stdout_as_string",
  72. "kill_after_timeout",
  73. "with_stdout",
  74. "universal_newlines",
  75. "shell",
  76. "env",
  77. "max_chunk_size",
  78. "strip_newline_in_stdout",
  79. }
  80. _logger = logging.getLogger(__name__)
  81. # ==============================================================================
  82. ## @name Utilities
  83. # ------------------------------------------------------------------------------
  84. # Documentation
  85. ## @{
  86. def handle_process_output(
  87. process: "Git.AutoInterrupt" | Popen,
  88. stdout_handler: Union[
  89. None,
  90. Callable[[AnyStr], None],
  91. Callable[[List[AnyStr]], None],
  92. Callable[[bytes, "Repo", "DiffIndex"], None],
  93. ],
  94. stderr_handler: Union[None, Callable[[AnyStr], None], Callable[[List[AnyStr]], None]],
  95. finalizer: Union[None, Callable[[Union[Popen, "Git.AutoInterrupt"]], None]] = None,
  96. decode_streams: bool = True,
  97. kill_after_timeout: Union[None, float] = None,
  98. ) -> None:
  99. R"""Register for notifications to learn that process output is ready to read, and
  100. dispatch lines to the respective line handlers.
  101. This function returns once the finalizer returns.
  102. :param process:
  103. :class:`subprocess.Popen` instance.
  104. :param stdout_handler:
  105. f(stdout_line_string), or ``None``.
  106. :param stderr_handler:
  107. f(stderr_line_string), or ``None``.
  108. :param finalizer:
  109. f(proc) - wait for proc to finish.
  110. :param decode_streams:
  111. Assume stdout/stderr streams are binary and decode them before pushing their
  112. contents to handlers.
  113. This defaults to ``True``. Set it to ``False`` if:
  114. - ``universal_newlines == True``, as then streams are in text mode, or
  115. - decoding must happen later, such as for :class:`~git.diff.Diff`\s.
  116. :param kill_after_timeout:
  117. :class:`float` or ``None``, Default = ``None``
  118. To specify a timeout in seconds for the git command, after which the process
  119. should be killed.
  120. """
  121. # Use 2 "pump" threads and wait for both to finish.
  122. def pump_stream(
  123. cmdline: List[str],
  124. name: str,
  125. stream: Union[BinaryIO, TextIO],
  126. is_decode: bool,
  127. handler: Union[None, Callable[[Union[bytes, str]], None]],
  128. ) -> None:
  129. try:
  130. for line in stream:
  131. if handler:
  132. if is_decode:
  133. assert isinstance(line, bytes)
  134. line_str = line.decode(defenc)
  135. handler(line_str)
  136. else:
  137. handler(line)
  138. except Exception as ex:
  139. _logger.error(f"Pumping {name!r} of cmd({remove_password_if_present(cmdline)}) failed due to: {ex!r}")
  140. if "I/O operation on closed file" not in str(ex):
  141. # Only reraise if the error was not due to the stream closing.
  142. raise CommandError([f"<{name}-pump>"] + remove_password_if_present(cmdline), ex) from ex
  143. finally:
  144. stream.close()
  145. if hasattr(process, "proc"):
  146. process = cast("Git.AutoInterrupt", process)
  147. cmdline: str | Tuple[str, ...] | List[str] = getattr(process.proc, "args", "")
  148. p_stdout = process.proc.stdout if process.proc else None
  149. p_stderr = process.proc.stderr if process.proc else None
  150. else:
  151. process = cast(Popen, process) # type: ignore[redundant-cast]
  152. cmdline = getattr(process, "args", "")
  153. p_stdout = process.stdout
  154. p_stderr = process.stderr
  155. if not isinstance(cmdline, (tuple, list)):
  156. cmdline = cmdline.split()
  157. pumps: List[Tuple[str, IO, Callable[..., None] | None]] = []
  158. if p_stdout:
  159. pumps.append(("stdout", p_stdout, stdout_handler))
  160. if p_stderr:
  161. pumps.append(("stderr", p_stderr, stderr_handler))
  162. threads: List[threading.Thread] = []
  163. for name, stream, handler in pumps:
  164. t = threading.Thread(target=pump_stream, args=(cmdline, name, stream, decode_streams, handler))
  165. t.daemon = True
  166. t.start()
  167. threads.append(t)
  168. # FIXME: Why join? Will block if stdin needs feeding...
  169. for t in threads:
  170. t.join(timeout=kill_after_timeout)
  171. if t.is_alive():
  172. if isinstance(process, Git.AutoInterrupt):
  173. process._terminate()
  174. else: # Don't want to deal with the other case.
  175. raise RuntimeError(
  176. "Thread join() timed out in cmd.handle_process_output()."
  177. f" kill_after_timeout={kill_after_timeout} seconds"
  178. )
  179. if stderr_handler:
  180. error_str: Union[str, bytes] = (
  181. f"error: process killed because it timed out. kill_after_timeout={kill_after_timeout} seconds"
  182. )
  183. if not decode_streams and isinstance(p_stderr, BinaryIO):
  184. # Assume stderr_handler needs binary input.
  185. error_str = cast(str, error_str)
  186. error_str = error_str.encode()
  187. # We ignore typing on the next line because mypy does not like the way
  188. # we inferred that stderr takes str or bytes.
  189. stderr_handler(error_str) # type: ignore[arg-type]
  190. if finalizer:
  191. finalizer(process)
  192. safer_popen: Callable[..., Popen]
  193. if sys.platform == "win32":
  194. def _safer_popen_windows(
  195. command: Union[str, Sequence[Any]],
  196. *,
  197. shell: bool = False,
  198. env: Optional[Mapping[str, str]] = None,
  199. **kwargs: Any,
  200. ) -> Popen:
  201. """Call :class:`subprocess.Popen` on Windows but don't include a CWD in the
  202. search.
  203. This avoids an untrusted search path condition where a file like ``git.exe`` in
  204. a malicious repository would be run when GitPython operates on the repository.
  205. The process using GitPython may have an untrusted repository's working tree as
  206. its current working directory. Some operations may temporarily change to that
  207. directory before running a subprocess. In addition, while by default GitPython
  208. does not run external commands with a shell, it can be made to do so, in which
  209. case the CWD of the subprocess, which GitPython usually sets to a repository
  210. working tree, can itself be searched automatically by the shell. This wrapper
  211. covers all those cases.
  212. :note:
  213. This currently works by setting the
  214. :envvar:`NoDefaultCurrentDirectoryInExePath` environment variable during
  215. subprocess creation. It also takes care of passing Windows-specific process
  216. creation flags, but that is unrelated to path search.
  217. :note:
  218. The current implementation contains a race condition on :attr:`os.environ`.
  219. GitPython isn't thread-safe, but a program using it on one thread should
  220. ideally be able to mutate :attr:`os.environ` on another, without
  221. unpredictable results. See comments in:
  222. https://github.com/gitpython-developers/GitPython/pull/1650
  223. """
  224. # CREATE_NEW_PROCESS_GROUP is needed for some ways of killing it afterwards.
  225. # https://docs.python.org/3/library/subprocess.html#subprocess.Popen.send_signal
  226. # https://docs.python.org/3/library/subprocess.html#subprocess.CREATE_NEW_PROCESS_GROUP
  227. creationflags = subprocess.CREATE_NO_WINDOW | subprocess.CREATE_NEW_PROCESS_GROUP
  228. # When using a shell, the shell is the direct subprocess, so the variable must
  229. # be set in its environment, to affect its search behavior.
  230. if shell:
  231. # The original may be immutable, or the caller may reuse it. Mutate a copy.
  232. env = {} if env is None else dict(env)
  233. env["NoDefaultCurrentDirectoryInExePath"] = "1" # The "1" can be any value.
  234. # When not using a shell, the current process does the search in a
  235. # CreateProcessW API call, so the variable must be set in our environment. With
  236. # a shell, that's unnecessary if https://github.com/python/cpython/issues/101283
  237. # is patched. In Python versions where it is unpatched, in the rare case the
  238. # ComSpec environment variable is unset, the search for the shell itself is
  239. # unsafe. Setting NoDefaultCurrentDirectoryInExePath in all cases, as done here,
  240. # is simpler and protects against that. (As above, the "1" can be any value.)
  241. with patch_env("NoDefaultCurrentDirectoryInExePath", "1"):
  242. return Popen(
  243. command,
  244. shell=shell,
  245. env=env,
  246. creationflags=creationflags,
  247. **kwargs,
  248. )
  249. safer_popen = _safer_popen_windows
  250. else:
  251. safer_popen = Popen
  252. def dashify(string: str) -> str:
  253. return string.replace("_", "-")
  254. def slots_to_dict(self: "Git", exclude: Sequence[str] = ()) -> Dict[str, Any]:
  255. return {s: getattr(self, s) for s in self.__slots__ if s not in exclude}
  256. def dict_to_slots_and__excluded_are_none(self: object, d: Mapping[str, Any], excluded: Sequence[str] = ()) -> None:
  257. for k, v in d.items():
  258. setattr(self, k, v)
  259. for k in excluded:
  260. setattr(self, k, None)
  261. ## -- End Utilities -- @}
  262. class _AutoInterrupt:
  263. """Process wrapper that terminates the wrapped process on finalization.
  264. This kills/interrupts the stored process instance once this instance goes out of
  265. scope. It is used to prevent processes piling up in case iterators stop reading.
  266. All attributes are wired through to the contained process object.
  267. The wait method is overridden to perform automatic status code checking and possibly
  268. raise.
  269. """
  270. __slots__ = ("proc", "args", "status")
  271. # If this is non-zero it will override any status code during _terminate, used
  272. # to prevent race conditions in testing.
  273. _status_code_if_terminate: int = 0
  274. def __init__(self, proc: Union[None, subprocess.Popen], args: Any) -> None:
  275. self.proc = proc
  276. self.args = args
  277. self.status: Union[int, None] = None
  278. def _terminate(self) -> None:
  279. """Terminate the underlying process."""
  280. if self.proc is None:
  281. return
  282. proc = self.proc
  283. self.proc = None
  284. if proc.stdin:
  285. proc.stdin.close()
  286. if proc.stdout:
  287. proc.stdout.close()
  288. if proc.stderr:
  289. proc.stderr.close()
  290. # Did the process finish already so we have a return code?
  291. try:
  292. if proc.poll() is not None:
  293. self.status = self._status_code_if_terminate or proc.poll()
  294. return
  295. except OSError as ex:
  296. _logger.info("Ignored error after process had died: %r", ex)
  297. # It can be that nothing really exists anymore...
  298. if os is None or getattr(os, "kill", None) is None:
  299. return
  300. # Try to kill it.
  301. try:
  302. proc.terminate()
  303. status = proc.wait() # Ensure the process goes away.
  304. self.status = self._status_code_if_terminate or status
  305. except OSError as ex:
  306. _logger.info("Ignored error after process had died: %r", ex)
  307. # END exception handling
  308. def __del__(self) -> None:
  309. self._terminate()
  310. def __getattr__(self, attr: str) -> Any:
  311. return getattr(self.proc, attr)
  312. # TODO: Bad choice to mimic `proc.wait()` but with different args.
  313. def wait(self, stderr: Union[None, str, bytes] = b"") -> int:
  314. """Wait for the process and return its status code.
  315. :param stderr:
  316. Previously read value of stderr, in case stderr is already closed.
  317. :warn:
  318. May deadlock if output or error pipes are used and not handled separately.
  319. :raise git.exc.GitCommandError:
  320. If the return status is not 0.
  321. """
  322. if stderr is None:
  323. stderr_b = b""
  324. stderr_b = force_bytes(data=stderr, encoding="utf-8")
  325. status: Union[int, None]
  326. if self.proc is not None:
  327. status = self.proc.wait()
  328. p_stderr = self.proc.stderr
  329. else: # Assume the underlying proc was killed earlier or never existed.
  330. status = self.status
  331. p_stderr = None
  332. def read_all_from_possibly_closed_stream(stream: Union[IO[bytes], None]) -> bytes:
  333. if stream:
  334. try:
  335. return stderr_b + force_bytes(stream.read())
  336. except (OSError, ValueError):
  337. return stderr_b or b""
  338. else:
  339. return stderr_b or b""
  340. # END status handling
  341. if status != 0:
  342. errstr = read_all_from_possibly_closed_stream(p_stderr)
  343. _logger.debug("AutoInterrupt wait stderr: %r" % (errstr,))
  344. raise GitCommandError(remove_password_if_present(self.args), status, errstr)
  345. return status
  346. _AutoInterrupt.__name__ = "AutoInterrupt"
  347. _AutoInterrupt.__qualname__ = "Git.AutoInterrupt"
  348. class _CatFileContentStream:
  349. """Object representing a sized read-only stream returning the contents of
  350. an object.
  351. This behaves like a stream, but counts the data read and simulates an empty stream
  352. once our sized content region is empty.
  353. If not all data are read to the end of the object's lifetime, we read the rest to
  354. ensure the underlying stream continues to work.
  355. """
  356. __slots__ = ("_stream", "_nbr", "_size")
  357. def __init__(self, size: int, stream: IO[bytes]) -> None:
  358. self._stream = stream
  359. self._size = size
  360. self._nbr = 0 # Number of bytes read.
  361. # Special case: If the object is empty, has null bytes, get the final
  362. # newline right away.
  363. if size == 0:
  364. stream.read(1)
  365. # END handle empty streams
  366. def read(self, size: int = -1) -> bytes:
  367. bytes_left = self._size - self._nbr
  368. if bytes_left == 0:
  369. return b""
  370. if size > -1:
  371. # Ensure we don't try to read past our limit.
  372. size = min(bytes_left, size)
  373. else:
  374. # They try to read all, make sure it's not more than what remains.
  375. size = bytes_left
  376. # END check early depletion
  377. data = self._stream.read(size)
  378. self._nbr += len(data)
  379. # Check for depletion, read our final byte to make the stream usable by
  380. # others.
  381. if self._size - self._nbr == 0:
  382. self._stream.read(1) # final newline
  383. # END finish reading
  384. return data
  385. def readline(self, size: int = -1) -> bytes:
  386. if self._nbr == self._size:
  387. return b""
  388. # Clamp size to lowest allowed value.
  389. bytes_left = self._size - self._nbr
  390. if size > -1:
  391. size = min(bytes_left, size)
  392. else:
  393. size = bytes_left
  394. # END handle size
  395. data = self._stream.readline(size)
  396. self._nbr += len(data)
  397. # Handle final byte.
  398. if self._size - self._nbr == 0:
  399. self._stream.read(1)
  400. # END finish reading
  401. return data
  402. def readlines(self, size: int = -1) -> List[bytes]:
  403. if self._nbr == self._size:
  404. return []
  405. # Leave all additional logic to our readline method, we just check the size.
  406. out = []
  407. nbr = 0
  408. while True:
  409. line = self.readline()
  410. if not line:
  411. break
  412. out.append(line)
  413. if size > -1:
  414. nbr += len(line)
  415. if nbr > size:
  416. break
  417. # END handle size constraint
  418. # END readline loop
  419. return out
  420. # skipcq: PYL-E0301
  421. def __iter__(self) -> "Git.CatFileContentStream":
  422. return self
  423. def __next__(self) -> bytes:
  424. line = self.readline()
  425. if not line:
  426. raise StopIteration
  427. return line
  428. next = __next__
  429. def __del__(self) -> None:
  430. bytes_left = self._size - self._nbr
  431. if bytes_left:
  432. # Read and discard - seeking is impossible within a stream.
  433. # This includes any terminating newline.
  434. self._stream.read(bytes_left + 1)
  435. # END handle incomplete read
  436. _CatFileContentStream.__name__ = "CatFileContentStream"
  437. _CatFileContentStream.__qualname__ = "Git.CatFileContentStream"
  438. _USE_SHELL_DEFAULT_MESSAGE = (
  439. "Git.USE_SHELL is deprecated, because only its default value of False is safe. "
  440. "It will be removed in a future release."
  441. )
  442. _USE_SHELL_DANGER_MESSAGE = (
  443. "Setting Git.USE_SHELL to True is unsafe and insecure, as the effect of special "
  444. "shell syntax cannot usually be accounted for. This can result in a command "
  445. "injection vulnerability and arbitrary code execution. Git.USE_SHELL is deprecated "
  446. "and will be removed in a future release."
  447. )
  448. def _warn_use_shell(*, extra_danger: bool) -> None:
  449. warnings.warn(
  450. _USE_SHELL_DANGER_MESSAGE if extra_danger else _USE_SHELL_DEFAULT_MESSAGE,
  451. DeprecationWarning,
  452. stacklevel=3,
  453. )
  454. class _GitMeta(type):
  455. """Metaclass for :class:`Git`.
  456. This helps issue :class:`DeprecationWarning` if :attr:`Git.USE_SHELL` is used.
  457. """
  458. def __getattribute(cls, name: str) -> Any:
  459. if name == "USE_SHELL":
  460. _warn_use_shell(extra_danger=False)
  461. return super().__getattribute__(name)
  462. def __setattr(cls, name: str, value: Any) -> Any:
  463. if name == "USE_SHELL":
  464. _warn_use_shell(extra_danger=value)
  465. super().__setattr__(name, value)
  466. if not TYPE_CHECKING:
  467. # To preserve static checking for undefined/misspelled attributes while letting
  468. # the methods' bodies be type-checked, these are defined as non-special methods,
  469. # then bound to special names out of view of static type checkers. (The original
  470. # names invoke name mangling (leading "__") to avoid confusion in other scopes.)
  471. __getattribute__ = __getattribute
  472. __setattr__ = __setattr
  473. GitMeta = _GitMeta
  474. """Alias of :class:`Git`'s metaclass, whether it is :class:`type` or a custom metaclass.
  475. Whether the :class:`Git` class has the default :class:`type` as its metaclass or uses a
  476. custom metaclass is not documented and may change at any time. This statically checkable
  477. metaclass alias is equivalent at runtime to ``type(Git)``. This should almost never be
  478. used. Code that benefits from it is likely to be remain brittle even if it is used.
  479. In view of the :class:`Git` class's intended use and :class:`Git` objects' dynamic
  480. callable attributes representing git subcommands, it rarely makes sense to inherit from
  481. :class:`Git` at all. Using :class:`Git` in multiple inheritance can be especially tricky
  482. to do correctly. Attempting uses of :class:`Git` where its metaclass is relevant, such
  483. as when a sibling class has an unrelated metaclass and a shared lower bound metaclass
  484. might have to be introduced to solve a metaclass conflict, is not recommended.
  485. :note:
  486. The correct static type of the :class:`Git` class itself, and any subclasses, is
  487. ``Type[Git]``. (This can be written as ``type[Git]`` in Python 3.9 later.)
  488. :class:`GitMeta` should never be used in any annotation where ``Type[Git]`` is
  489. intended or otherwise possible to use. This alias is truly only for very rare and
  490. inherently precarious situations where it is necessary to deal with the metaclass
  491. explicitly.
  492. """
  493. class Git(metaclass=_GitMeta):
  494. """The Git class manages communication with the Git binary.
  495. It provides a convenient interface to calling the Git binary, such as in::
  496. g = Git( git_dir )
  497. g.init() # calls 'git init' program
  498. rval = g.ls_files() # calls 'git ls-files' program
  499. Debugging:
  500. * Set the :envvar:`GIT_PYTHON_TRACE` environment variable to print each invocation
  501. of the command to stdout.
  502. * Set its value to ``full`` to see details about the returned values.
  503. """
  504. __slots__ = (
  505. "_working_dir",
  506. "cat_file_all",
  507. "cat_file_header",
  508. "_version_info",
  509. "_version_info_token",
  510. "_git_options",
  511. "_persistent_git_options",
  512. "_environment",
  513. )
  514. _excluded_ = (
  515. "cat_file_all",
  516. "cat_file_header",
  517. "_version_info",
  518. "_version_info_token",
  519. )
  520. re_unsafe_protocol = re.compile(r"(.+)::.+")
  521. def __getstate__(self) -> Dict[str, Any]:
  522. return slots_to_dict(self, exclude=self._excluded_)
  523. def __setstate__(self, d: Dict[str, Any]) -> None:
  524. dict_to_slots_and__excluded_are_none(self, d, excluded=self._excluded_)
  525. # CONFIGURATION
  526. git_exec_name = "git"
  527. """Default git command that should work on Linux, Windows, and other systems."""
  528. GIT_PYTHON_TRACE = os.environ.get("GIT_PYTHON_TRACE", False)
  529. """Enables debugging of GitPython's git commands."""
  530. USE_SHELL: bool = False
  531. """Deprecated. If set to ``True``, a shell will be used when executing git commands.
  532. Code that uses ``USE_SHELL = True`` or that passes ``shell=True`` to any GitPython
  533. functions should be updated to use the default value of ``False`` instead. ``True``
  534. is unsafe unless the effect of syntax treated specially by the shell is fully
  535. considered and accounted for, which is not possible under most circumstances. As
  536. detailed below, it is also no longer needed, even where it had been in the past.
  537. It is in many if not most cases a command injection vulnerability for an application
  538. to set :attr:`USE_SHELL` to ``True``. Any attacker who can cause a specially crafted
  539. fragment of text to make its way into any part of any argument to any git command
  540. (including paths, branch names, etc.) can cause the shell to read and write
  541. arbitrary files and execute arbitrary commands. Innocent input may also accidentally
  542. contain special shell syntax, leading to inadvertent malfunctions.
  543. In addition, how a value of ``True`` interacts with some aspects of GitPython's
  544. operation is not precisely specified and may change without warning, even before
  545. GitPython 4.0.0 when :attr:`USE_SHELL` may be removed. This includes:
  546. * Whether or how GitPython automatically customizes the shell environment.
  547. * Whether, outside of Windows (where :class:`subprocess.Popen` supports lists of
  548. separate arguments even when ``shell=True``), this can be used with any GitPython
  549. functionality other than direct calls to the :meth:`execute` method.
  550. * Whether any GitPython feature that runs git commands ever attempts to partially
  551. sanitize data a shell may treat specially. Currently this is not done.
  552. Prior to GitPython 2.0.8, this had a narrow purpose in suppressing console windows
  553. in graphical Windows applications. In 2.0.8 and higher, it provides no benefit, as
  554. GitPython solves that problem more robustly and safely by using the
  555. ``CREATE_NO_WINDOW`` process creation flag on Windows.
  556. Because Windows path search differs subtly based on whether a shell is used, in rare
  557. cases changing this from ``True`` to ``False`` may keep an unusual git "executable",
  558. such as a batch file, from being found. To fix this, set the command name or full
  559. path in the :envvar:`GIT_PYTHON_GIT_EXECUTABLE` environment variable or pass the
  560. full path to :func:`git.refresh` (or invoke the script using a ``.exe`` shim).
  561. Further reading:
  562. * :meth:`Git.execute` (on the ``shell`` parameter).
  563. * https://github.com/gitpython-developers/GitPython/commit/0d9390866f9ce42870d3116094cd49e0019a970a
  564. * https://learn.microsoft.com/en-us/windows/win32/procthread/process-creation-flags
  565. * https://github.com/python/cpython/issues/91558#issuecomment-1100942950
  566. * https://learn.microsoft.com/en-us/windows/win32/api/processthreadsapi/nf-processthreadsapi-createprocessw
  567. """
  568. _git_exec_env_var = "GIT_PYTHON_GIT_EXECUTABLE"
  569. _refresh_env_var = "GIT_PYTHON_REFRESH"
  570. GIT_PYTHON_GIT_EXECUTABLE = None
  571. """Provide the full path to the git executable. Otherwise it assumes git is in the
  572. executable search path.
  573. :note:
  574. The git executable is actually found during the refresh step in the top level
  575. ``__init__``. It can also be changed by explicitly calling :func:`git.refresh`.
  576. """
  577. _refresh_token = object() # Since None would match an initial _version_info_token.
  578. @classmethod
  579. def refresh(cls, path: Union[None, PathLike] = None) -> bool:
  580. """Update information about the git executable :class:`Git` objects will use.
  581. Called by the :func:`git.refresh` function in the top level ``__init__``.
  582. :param path:
  583. Optional path to the git executable. If not absolute, it is resolved
  584. immediately, relative to the current directory. (See note below.)
  585. :note:
  586. The top-level :func:`git.refresh` should be preferred because it calls this
  587. method and may also update other state accordingly.
  588. :note:
  589. There are three different ways to specify the command that refreshing causes
  590. to be used for git:
  591. 1. Pass no `path` argument and do not set the
  592. :envvar:`GIT_PYTHON_GIT_EXECUTABLE` environment variable. The command
  593. name ``git`` is used. It is looked up in a path search by the system, in
  594. each command run (roughly similar to how git is found when running
  595. ``git`` commands manually). This is usually the desired behavior.
  596. 2. Pass no `path` argument but set the :envvar:`GIT_PYTHON_GIT_EXECUTABLE`
  597. environment variable. The command given as the value of that variable is
  598. used. This may be a simple command or an arbitrary path. It is looked up
  599. in each command run. Setting :envvar:`GIT_PYTHON_GIT_EXECUTABLE` to
  600. ``git`` has the same effect as not setting it.
  601. 3. Pass a `path` argument. This path, if not absolute, is immediately
  602. resolved, relative to the current directory. This resolution occurs at
  603. the time of the refresh. When git commands are run, they are run using
  604. that previously resolved path. If a `path` argument is passed, the
  605. :envvar:`GIT_PYTHON_GIT_EXECUTABLE` environment variable is not
  606. consulted.
  607. :note:
  608. Refreshing always sets the :attr:`Git.GIT_PYTHON_GIT_EXECUTABLE` class
  609. attribute, which can be read on the :class:`Git` class or any of its
  610. instances to check what command is used to run git. This attribute should
  611. not be confused with the related :envvar:`GIT_PYTHON_GIT_EXECUTABLE`
  612. environment variable. The class attribute is set no matter how refreshing is
  613. performed.
  614. """
  615. # Discern which path to refresh with.
  616. if path is not None:
  617. new_git = os.path.expanduser(path)
  618. new_git = os.path.abspath(new_git)
  619. else:
  620. new_git = os.environ.get(cls._git_exec_env_var, cls.git_exec_name)
  621. # Keep track of the old and new git executable path.
  622. old_git = cls.GIT_PYTHON_GIT_EXECUTABLE
  623. old_refresh_token = cls._refresh_token
  624. cls.GIT_PYTHON_GIT_EXECUTABLE = new_git
  625. cls._refresh_token = object()
  626. # Test if the new git executable path is valid. A GitCommandNotFound error is
  627. # raised by us. A PermissionError is raised if the git executable cannot be
  628. # executed for whatever reason.
  629. has_git = False
  630. try:
  631. cls().version()
  632. has_git = True
  633. except (GitCommandNotFound, PermissionError):
  634. pass
  635. # Warn or raise exception if test failed.
  636. if not has_git:
  637. err = (
  638. dedent(
  639. """\
  640. Bad git executable.
  641. The git executable must be specified in one of the following ways:
  642. - be included in your $PATH
  643. - be set via $%s
  644. - explicitly set via git.refresh(<full-path-to-git-executable>)
  645. """
  646. )
  647. % cls._git_exec_env_var
  648. )
  649. # Revert to whatever the old_git was.
  650. cls.GIT_PYTHON_GIT_EXECUTABLE = old_git
  651. cls._refresh_token = old_refresh_token
  652. if old_git is None:
  653. # On the first refresh (when GIT_PYTHON_GIT_EXECUTABLE is None) we only
  654. # are quiet, warn, or error depending on the GIT_PYTHON_REFRESH value.
  655. # Determine what the user wants to happen during the initial refresh. We
  656. # expect GIT_PYTHON_REFRESH to either be unset or be one of the
  657. # following values:
  658. #
  659. # 0|q|quiet|s|silence|silent|n|none
  660. # 1|w|warn|warning|l|log
  661. # 2|r|raise|e|error|exception
  662. mode = os.environ.get(cls._refresh_env_var, "raise").lower()
  663. quiet = ["quiet", "q", "silence", "s", "silent", "none", "n", "0"]
  664. warn = ["warn", "w", "warning", "log", "l", "1"]
  665. error = ["error", "e", "exception", "raise", "r", "2"]
  666. if mode in quiet:
  667. pass
  668. elif mode in warn or mode in error:
  669. err = dedent(
  670. """\
  671. %s
  672. All git commands will error until this is rectified.
  673. This initial message can be silenced or aggravated in the future by setting the
  674. $%s environment variable. Use one of the following values:
  675. - %s: for no message or exception
  676. - %s: for a warning message (logging level CRITICAL, displayed by default)
  677. - %s: for a raised exception
  678. Example:
  679. export %s=%s
  680. """
  681. ) % (
  682. err,
  683. cls._refresh_env_var,
  684. "|".join(quiet),
  685. "|".join(warn),
  686. "|".join(error),
  687. cls._refresh_env_var,
  688. quiet[0],
  689. )
  690. if mode in warn:
  691. _logger.critical(err)
  692. else:
  693. raise ImportError(err)
  694. else:
  695. err = dedent(
  696. """\
  697. %s environment variable has been set but it has been set with an invalid value.
  698. Use only the following values:
  699. - %s: for no message or exception
  700. - %s: for a warning message (logging level CRITICAL, displayed by default)
  701. - %s: for a raised exception
  702. """
  703. ) % (
  704. cls._refresh_env_var,
  705. "|".join(quiet),
  706. "|".join(warn),
  707. "|".join(error),
  708. )
  709. raise ImportError(err)
  710. # We get here if this was the initial refresh and the refresh mode was
  711. # not error. Go ahead and set the GIT_PYTHON_GIT_EXECUTABLE such that we
  712. # discern the difference between the first refresh at import time
  713. # and subsequent calls to git.refresh or this refresh method.
  714. cls.GIT_PYTHON_GIT_EXECUTABLE = cls.git_exec_name
  715. else:
  716. # After the first refresh (when GIT_PYTHON_GIT_EXECUTABLE is no longer
  717. # None) we raise an exception.
  718. raise GitCommandNotFound(new_git, err)
  719. return has_git
  720. @classmethod
  721. def is_cygwin(cls) -> bool:
  722. return is_cygwin_git(cls.GIT_PYTHON_GIT_EXECUTABLE)
  723. @overload
  724. @classmethod
  725. def polish_url(cls, url: str, is_cygwin: Literal[False] = ...) -> str: ...
  726. @overload
  727. @classmethod
  728. def polish_url(cls, url: str, is_cygwin: Union[None, bool] = None) -> str: ...
  729. @classmethod
  730. def polish_url(cls, url: str, is_cygwin: Union[None, bool] = None) -> PathLike:
  731. """Remove any backslashes from URLs to be written in config files.
  732. Windows might create config files containing paths with backslashes, but git
  733. stops liking them as it will escape the backslashes. Hence we undo the escaping
  734. just to be sure.
  735. """
  736. if is_cygwin is None:
  737. is_cygwin = cls.is_cygwin()
  738. if is_cygwin:
  739. url = cygpath(url)
  740. else:
  741. url = os.path.expandvars(url)
  742. if url.startswith("~"):
  743. url = os.path.expanduser(url)
  744. url = url.replace("\\\\", "\\").replace("\\", "/")
  745. return url
  746. @classmethod
  747. def check_unsafe_protocols(cls, url: str) -> None:
  748. """Check for unsafe protocols.
  749. Apart from the usual protocols (http, git, ssh), Git allows "remote helpers"
  750. that have the form ``<transport>::<address>``. One of these helpers (``ext::``)
  751. can be used to invoke any arbitrary command.
  752. See:
  753. - https://git-scm.com/docs/gitremote-helpers
  754. - https://git-scm.com/docs/git-remote-ext
  755. """
  756. match = cls.re_unsafe_protocol.match(url)
  757. if match:
  758. protocol = match.group(1)
  759. raise UnsafeProtocolError(
  760. f"The `{protocol}::` protocol looks suspicious, use `allow_unsafe_protocols=True` to allow it."
  761. )
  762. @classmethod
  763. def check_unsafe_options(cls, options: List[str], unsafe_options: List[str]) -> None:
  764. """Check for unsafe options.
  765. Some options that are passed to ``git <command>`` can be used to execute
  766. arbitrary commands. These are blocked by default.
  767. """
  768. # Options can be of the form `foo`, `--foo bar`, or `--foo=bar`, so we need to
  769. # check if they start with "--foo" or if they are equal to "foo".
  770. bare_unsafe_options = [option.lstrip("-") for option in unsafe_options]
  771. for option in options:
  772. for unsafe_option, bare_option in zip(unsafe_options, bare_unsafe_options):
  773. if option.startswith(unsafe_option) or option == bare_option:
  774. raise UnsafeOptionError(
  775. f"{unsafe_option} is not allowed, use `allow_unsafe_options=True` to allow it."
  776. )
  777. AutoInterrupt: TypeAlias = _AutoInterrupt
  778. CatFileContentStream: TypeAlias = _CatFileContentStream
  779. def __init__(self, working_dir: Union[None, PathLike] = None) -> None:
  780. """Initialize this instance with:
  781. :param working_dir:
  782. Git directory we should work in. If ``None``, we always work in the current
  783. directory as returned by :func:`os.getcwd`.
  784. This is meant to be the working tree directory if available, or the
  785. ``.git`` directory in case of bare repositories.
  786. """
  787. super().__init__()
  788. self._working_dir = expand_path(working_dir)
  789. self._git_options: Union[List[str], Tuple[str, ...]] = ()
  790. self._persistent_git_options: List[str] = []
  791. # Extra environment variables to pass to git commands
  792. self._environment: Dict[str, str] = {}
  793. # Cached version slots
  794. self._version_info: Union[Tuple[int, ...], None] = None
  795. self._version_info_token: object = None
  796. # Cached command slots
  797. self.cat_file_header: Union[None, TBD] = None
  798. self.cat_file_all: Union[None, TBD] = None
  799. def __getattribute__(self, name: str) -> Any:
  800. if name == "USE_SHELL":
  801. _warn_use_shell(extra_danger=False)
  802. return super().__getattribute__(name)
  803. def __getattr__(self, name: str) -> Any:
  804. """A convenience method as it allows to call the command as if it was an object.
  805. :return:
  806. Callable object that will execute call :meth:`_call_process` with your
  807. arguments.
  808. """
  809. if name.startswith("_"):
  810. return super().__getattribute__(name)
  811. return lambda *args, **kwargs: self._call_process(name, *args, **kwargs)
  812. def set_persistent_git_options(self, **kwargs: Any) -> None:
  813. """Specify command line options to the git executable for subsequent
  814. subcommand calls.
  815. :param kwargs:
  816. A dict of keyword arguments.
  817. These arguments are passed as in :meth:`_call_process`, but will be passed
  818. to the git command rather than the subcommand.
  819. """
  820. self._persistent_git_options = self.transform_kwargs(split_single_char_options=True, **kwargs)
  821. @property
  822. def working_dir(self) -> Union[None, PathLike]:
  823. """:return: Git directory we are working on"""
  824. return self._working_dir
  825. @property
  826. def version_info(self) -> Tuple[int, ...]:
  827. """
  828. :return: Tuple with integers representing the major, minor and additional
  829. version numbers as parsed from :manpage:`git-version(1)`. Up to four fields
  830. are used.
  831. This value is generated on demand and is cached.
  832. """
  833. # Refreshing is global, but version_info caching is per-instance.
  834. refresh_token = self._refresh_token # Copy token in case of concurrent refresh.
  835. # Use the cached version if obtained after the most recent refresh.
  836. if self._version_info_token is refresh_token:
  837. assert self._version_info is not None, "Bug: corrupted token-check state"
  838. return self._version_info
  839. # Run "git version" and parse it.
  840. process_version = self._call_process("version")
  841. version_string = process_version.split(" ")[2]
  842. version_fields = version_string.split(".")[:4]
  843. leading_numeric_fields = itertools.takewhile(str.isdigit, version_fields)
  844. self._version_info = tuple(map(int, leading_numeric_fields))
  845. # This value will be considered valid until the next refresh.
  846. self._version_info_token = refresh_token
  847. return self._version_info
  848. @overload
  849. def execute(
  850. self,
  851. command: Union[str, Sequence[Any]],
  852. *,
  853. as_process: Literal[True],
  854. ) -> "AutoInterrupt": ...
  855. @overload
  856. def execute(
  857. self,
  858. command: Union[str, Sequence[Any]],
  859. *,
  860. as_process: Literal[False] = False,
  861. stdout_as_string: Literal[True],
  862. ) -> Union[str, Tuple[int, str, str]]: ...
  863. @overload
  864. def execute(
  865. self,
  866. command: Union[str, Sequence[Any]],
  867. *,
  868. as_process: Literal[False] = False,
  869. stdout_as_string: Literal[False] = False,
  870. ) -> Union[bytes, Tuple[int, bytes, str]]: ...
  871. @overload
  872. def execute(
  873. self,
  874. command: Union[str, Sequence[Any]],
  875. *,
  876. with_extended_output: Literal[False],
  877. as_process: Literal[False],
  878. stdout_as_string: Literal[True],
  879. ) -> str: ...
  880. @overload
  881. def execute(
  882. self,
  883. command: Union[str, Sequence[Any]],
  884. *,
  885. with_extended_output: Literal[False],
  886. as_process: Literal[False],
  887. stdout_as_string: Literal[False],
  888. ) -> bytes: ...
  889. def execute(
  890. self,
  891. command: Union[str, Sequence[Any]],
  892. istream: Union[None, BinaryIO] = None,
  893. with_extended_output: bool = False,
  894. with_exceptions: bool = True,
  895. as_process: bool = False,
  896. output_stream: Union[None, BinaryIO] = None,
  897. stdout_as_string: bool = True,
  898. kill_after_timeout: Union[None, float] = None,
  899. with_stdout: bool = True,
  900. universal_newlines: bool = False,
  901. shell: Union[None, bool] = None,
  902. env: Union[None, Mapping[str, str]] = None,
  903. max_chunk_size: int = io.DEFAULT_BUFFER_SIZE,
  904. strip_newline_in_stdout: bool = True,
  905. **subprocess_kwargs: Any,
  906. ) -> Union[str, bytes, Tuple[int, Union[str, bytes], str], AutoInterrupt]:
  907. R"""Handle executing the command, and consume and return the returned
  908. information (stdout).
  909. :param command:
  910. The command argument list to execute.
  911. It should be a sequence of program arguments, or a string. The
  912. program to execute is the first item in the args sequence or string.
  913. :param istream:
  914. Standard input filehandle passed to :class:`subprocess.Popen`.
  915. :param with_extended_output:
  916. Whether to return a (status, stdout, stderr) tuple.
  917. :param with_exceptions:
  918. Whether to raise an exception when git returns a non-zero status.
  919. :param as_process:
  920. Whether to return the created process instance directly from which
  921. streams can be read on demand. This will render `with_extended_output`
  922. and `with_exceptions` ineffective - the caller will have to deal with
  923. the details. It is important to note that the process will be placed
  924. into an :class:`AutoInterrupt` wrapper that will interrupt the process
  925. once it goes out of scope. If you use the command in iterators, you
  926. should pass the whole process instance instead of a single stream.
  927. :param output_stream:
  928. If set to a file-like object, data produced by the git command will be
  929. copied to the given stream instead of being returned as a string.
  930. This feature only has any effect if `as_process` is ``False``.
  931. :param stdout_as_string:
  932. If ``False``, the command's standard output will be bytes. Otherwise, it
  933. will be decoded into a string using the default encoding (usually UTF-8).
  934. The latter can fail, if the output contains binary data.
  935. :param kill_after_timeout:
  936. Specifies a timeout in seconds for the git command, after which the process
  937. should be killed. This will have no effect if `as_process` is set to
  938. ``True``. It is set to ``None`` by default and will let the process run
  939. until the timeout is explicitly specified. Uses of this feature should be
  940. carefully considered, due to the following limitations:
  941. 1. This feature is not supported at all on Windows.
  942. 2. Effectiveness may vary by operating system. ``ps --ppid`` is used to
  943. enumerate child processes, which is available on most GNU/Linux systems
  944. but not most others.
  945. 3. Deeper descendants do not receive signals, though they may sometimes
  946. terminate as a consequence of their parent processes being killed.
  947. 4. `kill_after_timeout` uses ``SIGKILL``, which can have negative side
  948. effects on a repository. For example, stale locks in case of
  949. :manpage:`git-gc(1)` could render the repository incapable of accepting
  950. changes until the lock is manually removed.
  951. :param with_stdout:
  952. If ``True``, default ``True``, we open stdout on the created process.
  953. :param universal_newlines:
  954. If ``True``, pipes will be opened as text, and lines are split at all known
  955. line endings.
  956. :param shell:
  957. Whether to invoke commands through a shell
  958. (see :class:`Popen(..., shell=True) <subprocess.Popen>`).
  959. If this is not ``None``, it overrides :attr:`USE_SHELL`.
  960. Passing ``shell=True`` to this or any other GitPython function should be
  961. avoided, as it is unsafe under most circumstances. This is because it is
  962. typically not feasible to fully consider and account for the effect of shell
  963. expansions, especially when passing ``shell=True`` to other methods that
  964. forward it to :meth:`Git.execute`. Passing ``shell=True`` is also no longer
  965. needed (nor useful) to work around any known operating system specific
  966. issues.
  967. :param env:
  968. A dictionary of environment variables to be passed to
  969. :class:`subprocess.Popen`.
  970. :param max_chunk_size:
  971. Maximum number of bytes in one chunk of data passed to the `output_stream`
  972. in one invocation of its ``write()`` method. If the given number is not
  973. positive then the default value is used.
  974. :param strip_newline_in_stdout:
  975. Whether to strip the trailing ``\n`` of the command stdout.
  976. :param subprocess_kwargs:
  977. Keyword arguments to be passed to :class:`subprocess.Popen`. Please note
  978. that some of the valid kwargs are already set by this method; the ones you
  979. specify may not be the same ones.
  980. :return:
  981. * str(output), if `extended_output` is ``False`` (Default)
  982. * tuple(int(status), str(stdout), str(stderr)),
  983. if `extended_output` is ``True``
  984. If `output_stream` is ``True``, the stdout value will be your output stream:
  985. * output_stream, if `extended_output` is ``False``
  986. * tuple(int(status), output_stream, str(stderr)),
  987. if `extended_output` is ``True``
  988. Note that git is executed with ``LC_MESSAGES="C"`` to ensure consistent
  989. output regardless of system language.
  990. :raise git.exc.GitCommandError:
  991. :note:
  992. If you add additional keyword arguments to the signature of this method, you
  993. must update the ``execute_kwargs`` variable housed in this module.
  994. """
  995. # Remove password for the command if present.
  996. redacted_command = remove_password_if_present(command)
  997. if self.GIT_PYTHON_TRACE and (self.GIT_PYTHON_TRACE != "full" or as_process):
  998. _logger.info(" ".join(redacted_command))
  999. # Allow the user to have the command executed in their working dir.
  1000. try:
  1001. cwd = self._working_dir or os.getcwd() # type: Union[None, str]
  1002. if not os.access(str(cwd), os.X_OK):
  1003. cwd = None
  1004. except FileNotFoundError:
  1005. cwd = None
  1006. # Start the process.
  1007. inline_env = env
  1008. env = os.environ.copy()
  1009. # Attempt to force all output to plain ASCII English, which is what some parsing
  1010. # code may expect.
  1011. # According to https://askubuntu.com/a/311796, we are setting LANGUAGE as well
  1012. # just to be sure.
  1013. env["LANGUAGE"] = "C"
  1014. env["LC_ALL"] = "C"
  1015. env.update(self._environment)
  1016. if inline_env is not None:
  1017. env.update(inline_env)
  1018. if sys.platform == "win32":
  1019. if kill_after_timeout is not None:
  1020. raise GitCommandError(
  1021. redacted_command,
  1022. '"kill_after_timeout" feature is not supported on Windows.',
  1023. )
  1024. cmd_not_found_exception = OSError
  1025. else:
  1026. cmd_not_found_exception = FileNotFoundError
  1027. # END handle
  1028. stdout_sink = PIPE if with_stdout else getattr(subprocess, "DEVNULL", None) or open(os.devnull, "wb")
  1029. if shell is None:
  1030. # Get the value of USE_SHELL with no deprecation warning. Do this without
  1031. # warnings.catch_warnings, to avoid a race condition with application code
  1032. # configuring warnings. The value could be looked up in type(self).__dict__
  1033. # or Git.__dict__, but those can break under some circumstances. This works
  1034. # the same as self.USE_SHELL in more situations; see Git.__getattribute__.
  1035. shell = super().__getattribute__("USE_SHELL")
  1036. _logger.debug(
  1037. "Popen(%s, cwd=%s, stdin=%s, shell=%s, universal_newlines=%s)",
  1038. redacted_command,
  1039. cwd,
  1040. "<valid stream>" if istream else "None",
  1041. shell,
  1042. universal_newlines,
  1043. )
  1044. try:
  1045. proc = safer_popen(
  1046. command,
  1047. env=env,
  1048. cwd=cwd,
  1049. bufsize=-1,
  1050. stdin=(istream or DEVNULL),
  1051. stderr=PIPE,
  1052. stdout=stdout_sink,
  1053. shell=shell,
  1054. universal_newlines=universal_newlines,
  1055. encoding=defenc if universal_newlines else None,
  1056. **subprocess_kwargs,
  1057. )
  1058. except cmd_not_found_exception as err:
  1059. raise GitCommandNotFound(redacted_command, err) from err
  1060. else:
  1061. # Replace with a typeguard for Popen[bytes]?
  1062. proc.stdout = cast(BinaryIO, proc.stdout)
  1063. proc.stderr = cast(BinaryIO, proc.stderr)
  1064. if as_process:
  1065. return self.AutoInterrupt(proc, command)
  1066. if sys.platform != "win32" and kill_after_timeout is not None:
  1067. # Help mypy figure out this is not None even when used inside communicate().
  1068. timeout = kill_after_timeout
  1069. def kill_process(pid: int) -> None:
  1070. """Callback to kill a process.
  1071. This callback implementation would be ineffective and unsafe on Windows.
  1072. """
  1073. p = Popen(["ps", "--ppid", str(pid)], stdout=PIPE)
  1074. child_pids = []
  1075. if p.stdout is not None:
  1076. for line in p.stdout:
  1077. if len(line.split()) > 0:
  1078. local_pid = (line.split())[0]
  1079. if local_pid.isdigit():
  1080. child_pids.append(int(local_pid))
  1081. try:
  1082. os.kill(pid, signal.SIGKILL)
  1083. for child_pid in child_pids:
  1084. try:
  1085. os.kill(child_pid, signal.SIGKILL)
  1086. except OSError:
  1087. pass
  1088. # Tell the main routine that the process was killed.
  1089. kill_check.set()
  1090. except OSError:
  1091. # It is possible that the process gets completed in the duration
  1092. # after timeout happens and before we try to kill the process.
  1093. pass
  1094. return
  1095. def communicate() -> Tuple[AnyStr, AnyStr]:
  1096. watchdog.start()
  1097. out, err = proc.communicate()
  1098. watchdog.cancel()
  1099. if kill_check.is_set():
  1100. err = 'Timeout: the command "%s" did not complete in %d secs.' % (
  1101. " ".join(redacted_command),
  1102. timeout,
  1103. )
  1104. if not universal_newlines:
  1105. err = err.encode(defenc)
  1106. return out, err
  1107. # END helpers
  1108. kill_check = threading.Event()
  1109. watchdog = threading.Timer(timeout, kill_process, args=(proc.pid,))
  1110. else:
  1111. communicate = proc.communicate
  1112. # Wait for the process to return.
  1113. status = 0
  1114. stdout_value: Union[str, bytes] = b""
  1115. stderr_value: Union[str, bytes] = b""
  1116. newline = "\n" if universal_newlines else b"\n"
  1117. try:
  1118. if output_stream is None:
  1119. stdout_value, stderr_value = communicate()
  1120. # Strip trailing "\n".
  1121. if stdout_value.endswith(newline) and strip_newline_in_stdout: # type: ignore[arg-type]
  1122. stdout_value = stdout_value[:-1]
  1123. if stderr_value.endswith(newline): # type: ignore[arg-type]
  1124. stderr_value = stderr_value[:-1]
  1125. status = proc.returncode
  1126. else:
  1127. max_chunk_size = max_chunk_size if max_chunk_size and max_chunk_size > 0 else io.DEFAULT_BUFFER_SIZE
  1128. stream_copy(proc.stdout, output_stream, max_chunk_size)
  1129. stdout_value = proc.stdout.read()
  1130. stderr_value = proc.stderr.read()
  1131. # Strip trailing "\n".
  1132. if stderr_value.endswith(newline): # type: ignore[arg-type]
  1133. stderr_value = stderr_value[:-1]
  1134. status = proc.wait()
  1135. # END stdout handling
  1136. finally:
  1137. proc.stdout.close()
  1138. proc.stderr.close()
  1139. if self.GIT_PYTHON_TRACE == "full":
  1140. cmdstr = " ".join(redacted_command)
  1141. def as_text(stdout_value: Union[bytes, str]) -> str:
  1142. return not output_stream and safe_decode(stdout_value) or "<OUTPUT_STREAM>"
  1143. # END as_text
  1144. if stderr_value:
  1145. _logger.info(
  1146. "%s -> %d; stdout: '%s'; stderr: '%s'",
  1147. cmdstr,
  1148. status,
  1149. as_text(stdout_value),
  1150. safe_decode(stderr_value),
  1151. )
  1152. elif stdout_value:
  1153. _logger.info("%s -> %d; stdout: '%s'", cmdstr, status, as_text(stdout_value))
  1154. else:
  1155. _logger.info("%s -> %d", cmdstr, status)
  1156. # END handle debug printing
  1157. if with_exceptions and status != 0:
  1158. raise GitCommandError(redacted_command, status, stderr_value, stdout_value)
  1159. if isinstance(stdout_value, bytes) and stdout_as_string: # Could also be output_stream.
  1160. stdout_value = safe_decode(stdout_value)
  1161. # Allow access to the command's status code.
  1162. if with_extended_output:
  1163. return (status, stdout_value, safe_decode(stderr_value))
  1164. else:
  1165. return stdout_value
  1166. def environment(self) -> Dict[str, str]:
  1167. return self._environment
  1168. def update_environment(self, **kwargs: Any) -> Dict[str, Union[str, None]]:
  1169. """Set environment variables for future git invocations. Return all changed
  1170. values in a format that can be passed back into this function to revert the
  1171. changes.
  1172. Examples::
  1173. old_env = self.update_environment(PWD='/tmp')
  1174. self.update_environment(**old_env)
  1175. :param kwargs:
  1176. Environment variables to use for git processes.
  1177. :return:
  1178. Dict that maps environment variables to their old values
  1179. """
  1180. old_env = {}
  1181. for key, value in kwargs.items():
  1182. # Set value if it is None.
  1183. if value is not None:
  1184. old_env[key] = self._environment.get(key)
  1185. self._environment[key] = value
  1186. # Remove key from environment if its value is None.
  1187. elif key in self._environment:
  1188. old_env[key] = self._environment[key]
  1189. del self._environment[key]
  1190. return old_env
  1191. @contextlib.contextmanager
  1192. def custom_environment(self, **kwargs: Any) -> Iterator[None]:
  1193. """A context manager around the above :meth:`update_environment` method to
  1194. restore the environment back to its previous state after operation.
  1195. Examples::
  1196. with self.custom_environment(GIT_SSH='/bin/ssh_wrapper'):
  1197. repo.remotes.origin.fetch()
  1198. :param kwargs:
  1199. See :meth:`update_environment`.
  1200. """
  1201. old_env = self.update_environment(**kwargs)
  1202. try:
  1203. yield
  1204. finally:
  1205. self.update_environment(**old_env)
  1206. def transform_kwarg(self, name: str, value: Any, split_single_char_options: bool) -> List[str]:
  1207. if len(name) == 1:
  1208. if value is True:
  1209. return ["-%s" % name]
  1210. elif value not in (False, None):
  1211. if split_single_char_options:
  1212. return ["-%s" % name, "%s" % value]
  1213. else:
  1214. return ["-%s%s" % (name, value)]
  1215. else:
  1216. if value is True:
  1217. return ["--%s" % dashify(name)]
  1218. elif value is not False and value is not None:
  1219. return ["--%s=%s" % (dashify(name), value)]
  1220. return []
  1221. def transform_kwargs(self, split_single_char_options: bool = True, **kwargs: Any) -> List[str]:
  1222. """Transform Python-style kwargs into git command line options."""
  1223. args = []
  1224. for k, v in kwargs.items():
  1225. if isinstance(v, (list, tuple)):
  1226. for value in v:
  1227. args += self.transform_kwarg(k, value, split_single_char_options)
  1228. else:
  1229. args += self.transform_kwarg(k, v, split_single_char_options)
  1230. return args
  1231. @classmethod
  1232. def _unpack_args(cls, arg_list: Sequence[str]) -> List[str]:
  1233. outlist = []
  1234. if isinstance(arg_list, (list, tuple)):
  1235. for arg in arg_list:
  1236. outlist.extend(cls._unpack_args(arg))
  1237. else:
  1238. outlist.append(str(arg_list))
  1239. return outlist
  1240. def __call__(self, **kwargs: Any) -> "Git":
  1241. """Specify command line options to the git executable for a subcommand call.
  1242. :param kwargs:
  1243. A dict of keyword arguments.
  1244. These arguments are passed as in :meth:`_call_process`, but will be passed
  1245. to the git command rather than the subcommand.
  1246. Examples::
  1247. git(work_tree='/tmp').difftool()
  1248. """
  1249. self._git_options = self.transform_kwargs(split_single_char_options=True, **kwargs)
  1250. return self
  1251. @overload
  1252. def _call_process(
  1253. self, method: str, *args: None, **kwargs: None
  1254. ) -> str: ... # If no args were given, execute the call with all defaults.
  1255. @overload
  1256. def _call_process(
  1257. self,
  1258. method: str,
  1259. istream: int,
  1260. as_process: Literal[True],
  1261. *args: Any,
  1262. **kwargs: Any,
  1263. ) -> "Git.AutoInterrupt": ...
  1264. @overload
  1265. def _call_process(
  1266. self, method: str, *args: Any, **kwargs: Any
  1267. ) -> Union[str, bytes, Tuple[int, Union[str, bytes], str], "Git.AutoInterrupt"]: ...
  1268. def _call_process(
  1269. self, method: str, *args: Any, **kwargs: Any
  1270. ) -> Union[str, bytes, Tuple[int, Union[str, bytes], str], "Git.AutoInterrupt"]:
  1271. """Run the given git command with the specified arguments and return the result
  1272. as a string.
  1273. :param method:
  1274. The command. Contained ``_`` characters will be converted to hyphens, such
  1275. as in ``ls_files`` to call ``ls-files``.
  1276. :param args:
  1277. The list of arguments. If ``None`` is included, it will be pruned.
  1278. This allows your commands to call git more conveniently, as ``None`` is
  1279. realized as non-existent.
  1280. :param kwargs:
  1281. Contains key-values for the following:
  1282. - The :meth:`execute()` kwds, as listed in ``execute_kwargs``.
  1283. - "Command options" to be converted by :meth:`transform_kwargs`.
  1284. - The ``insert_kwargs_after`` key which its value must match one of
  1285. ``*args``.
  1286. It also contains any command options, to be appended after the matched arg.
  1287. Examples::
  1288. git.rev_list('master', max_count=10, header=True)
  1289. turns into::
  1290. git rev-list max-count 10 --header master
  1291. :return:
  1292. Same as :meth:`execute`. If no args are given, used :meth:`execute`'s
  1293. default (especially ``as_process = False``, ``stdout_as_string = True``) and
  1294. return :class:`str`.
  1295. """
  1296. # Handle optional arguments prior to calling transform_kwargs.
  1297. # Otherwise these'll end up in args, which is bad.
  1298. exec_kwargs = {k: v for k, v in kwargs.items() if k in execute_kwargs}
  1299. opts_kwargs = {k: v for k, v in kwargs.items() if k not in execute_kwargs}
  1300. insert_after_this_arg = opts_kwargs.pop("insert_kwargs_after", None)
  1301. # Prepare the argument list.
  1302. opt_args = self.transform_kwargs(**opts_kwargs)
  1303. ext_args = self._unpack_args([a for a in args if a is not None])
  1304. if insert_after_this_arg is None:
  1305. args_list = opt_args + ext_args
  1306. else:
  1307. try:
  1308. index = ext_args.index(insert_after_this_arg)
  1309. except ValueError as err:
  1310. raise ValueError(
  1311. "Couldn't find argument '%s' in args %s to insert cmd options after"
  1312. % (insert_after_this_arg, str(ext_args))
  1313. ) from err
  1314. # END handle error
  1315. args_list = ext_args[: index + 1] + opt_args + ext_args[index + 1 :]
  1316. # END handle opts_kwargs
  1317. call = [self.GIT_PYTHON_GIT_EXECUTABLE]
  1318. # Add persistent git options.
  1319. call.extend(self._persistent_git_options)
  1320. # Add the git options, then reset to empty to avoid side effects.
  1321. call.extend(self._git_options)
  1322. self._git_options = ()
  1323. call.append(dashify(method))
  1324. call.extend(args_list)
  1325. return self.execute(call, **exec_kwargs)
  1326. def _parse_object_header(self, header_line: str) -> Tuple[str, str, int]:
  1327. """
  1328. :param header_line:
  1329. A line of the form::
  1330. <hex_sha> type_string size_as_int
  1331. :return:
  1332. (hex_sha, type_string, size_as_int)
  1333. :raise ValueError:
  1334. If the header contains indication for an error due to incorrect input sha.
  1335. """
  1336. tokens = header_line.split()
  1337. if len(tokens) != 3:
  1338. if not tokens:
  1339. err_msg = (
  1340. f"SHA is empty, possible dubious ownership in the repository "
  1341. f"""at {self._working_dir}.\n If this is unintended run:\n\n """
  1342. f""" "git config --global --add safe.directory {self._working_dir}" """
  1343. )
  1344. raise ValueError(err_msg)
  1345. else:
  1346. raise ValueError("SHA %s could not be resolved, git returned: %r" % (tokens[0], header_line.strip()))
  1347. # END handle actual return value
  1348. # END error handling
  1349. if len(tokens[0]) != 40:
  1350. raise ValueError("Failed to parse header: %r" % header_line)
  1351. return (tokens[0], tokens[1], int(tokens[2]))
  1352. def _prepare_ref(self, ref: AnyStr) -> bytes:
  1353. # Required for command to separate refs on stdin, as bytes.
  1354. if isinstance(ref, bytes):
  1355. # Assume 40 bytes hexsha - bin-to-ascii for some reason returns bytes, not text.
  1356. refstr: str = ref.decode("ascii")
  1357. elif not isinstance(ref, str):
  1358. refstr = str(ref) # Could be ref-object.
  1359. else:
  1360. refstr = ref
  1361. if not refstr.endswith("\n"):
  1362. refstr += "\n"
  1363. return refstr.encode(defenc)
  1364. def _get_persistent_cmd(self, attr_name: str, cmd_name: str, *args: Any, **kwargs: Any) -> "Git.AutoInterrupt":
  1365. cur_val = getattr(self, attr_name)
  1366. if cur_val is not None:
  1367. return cur_val
  1368. options = {"istream": PIPE, "as_process": True}
  1369. options.update(kwargs)
  1370. cmd = self._call_process(cmd_name, *args, **options)
  1371. setattr(self, attr_name, cmd)
  1372. cmd = cast("Git.AutoInterrupt", cmd)
  1373. return cmd
  1374. def __get_object_header(self, cmd: "Git.AutoInterrupt", ref: AnyStr) -> Tuple[str, str, int]:
  1375. if cmd.stdin and cmd.stdout:
  1376. cmd.stdin.write(self._prepare_ref(ref))
  1377. cmd.stdin.flush()
  1378. return self._parse_object_header(cmd.stdout.readline())
  1379. else:
  1380. raise ValueError("cmd stdin was empty")
  1381. def get_object_header(self, ref: str) -> Tuple[str, str, int]:
  1382. """Use this method to quickly examine the type and size of the object behind the
  1383. given ref.
  1384. :note:
  1385. The method will only suffer from the costs of command invocation once and
  1386. reuses the command in subsequent calls.
  1387. :return:
  1388. (hexsha, type_string, size_as_int)
  1389. """
  1390. cmd = self._get_persistent_cmd("cat_file_header", "cat_file", batch_check=True)
  1391. return self.__get_object_header(cmd, ref)
  1392. def get_object_data(self, ref: str) -> Tuple[str, str, int, bytes]:
  1393. """Similar to :meth:`get_object_header`, but returns object data as well.
  1394. :return:
  1395. (hexsha, type_string, size_as_int, data_string)
  1396. :note:
  1397. Not threadsafe.
  1398. """
  1399. hexsha, typename, size, stream = self.stream_object_data(ref)
  1400. data = stream.read(size)
  1401. del stream
  1402. return (hexsha, typename, size, data)
  1403. def stream_object_data(self, ref: str) -> Tuple[str, str, int, "Git.CatFileContentStream"]:
  1404. """Similar to :meth:`get_object_data`, but returns the data as a stream.
  1405. :return:
  1406. (hexsha, type_string, size_as_int, stream)
  1407. :note:
  1408. This method is not threadsafe. You need one independent :class:`Git`
  1409. instance per thread to be safe!
  1410. """
  1411. cmd = self._get_persistent_cmd("cat_file_all", "cat_file", batch=True)
  1412. hexsha, typename, size = self.__get_object_header(cmd, ref)
  1413. cmd_stdout = cmd.stdout if cmd.stdout is not None else io.BytesIO()
  1414. return (hexsha, typename, size, self.CatFileContentStream(size, cmd_stdout))
  1415. def clear_cache(self) -> "Git":
  1416. """Clear all kinds of internal caches to release resources.
  1417. Currently persistent commands will be interrupted.
  1418. :return:
  1419. self
  1420. """
  1421. for cmd in (self.cat_file_all, self.cat_file_header):
  1422. if cmd:
  1423. cmd.__del__()
  1424. self.cat_file_all = None
  1425. self.cat_file_header = None
  1426. return self