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