Coverage for /pythoncovmergedfiles/medio/medio/usr/local/lib/python3.11/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

661 statements  

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 

6from __future__ import annotations 

7 

8__all__ = ["GitMeta", "Git"] 

9 

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 

23 

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) 

40 

41# typing --------------------------------------------------------------------------- 

42 

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) 

62 

63if sys.version_info >= (3, 10): 

64 from typing import TypeAlias 

65else: 

66 from typing_extensions import TypeAlias 

67 

68from git.types import Literal, PathLike, TBD 

69 

70if TYPE_CHECKING: 

71 from git.diff import DiffIndex 

72 from git.repo.base import Repo 

73 

74# --------------------------------------------------------------------------------- 

75 

76execute_kwargs = { 

77 "istream", 

78 "with_extended_output", 

79 "with_exceptions", 

80 "as_process", 

81 "output_stream", 

82 "stdout_as_string", 

83 "kill_after_timeout", 

84 "with_stdout", 

85 "universal_newlines", 

86 "shell", 

87 "env", 

88 "max_chunk_size", 

89 "strip_newline_in_stdout", 

90} 

91 

92_logger = logging.getLogger(__name__) 

93 

94 

95# ============================================================================== 

96## @name Utilities 

97# ------------------------------------------------------------------------------ 

98# Documentation 

99## @{ 

100 

101 

102def handle_process_output( 

103 process: "Git.AutoInterrupt" | Popen, 

104 stdout_handler: Union[ 

105 None, 

106 Callable[[AnyStr], None], 

107 Callable[[List[AnyStr]], None], 

108 Callable[[bytes, "Repo", "DiffIndex"], None], 

109 ], 

110 stderr_handler: Union[None, Callable[[AnyStr], None], Callable[[List[AnyStr]], None]], 

111 finalizer: Union[None, Callable[[Union[Popen, "Git.AutoInterrupt"]], None]] = None, 

112 decode_streams: bool = True, 

113 kill_after_timeout: Union[None, float] = None, 

114) -> None: 

115 R"""Register for notifications to learn that process output is ready to read, and 

116 dispatch lines to the respective line handlers. 

117 

118 This function returns once the finalizer returns. 

119 

120 :param process: 

121 :class:`subprocess.Popen` instance. 

122 

123 :param stdout_handler: 

124 f(stdout_line_string), or ``None``. 

125 

126 :param stderr_handler: 

127 f(stderr_line_string), or ``None``. 

128 

129 :param finalizer: 

130 f(proc) - wait for proc to finish. 

131 

132 :param decode_streams: 

133 Assume stdout/stderr streams are binary and decode them before pushing their 

134 contents to handlers. 

135 

136 This defaults to ``True``. Set it to ``False`` if: 

137 

138 - ``universal_newlines == True``, as then streams are in text mode, or 

139 - decoding must happen later, such as for :class:`~git.diff.Diff`\s. 

140 

141 :param kill_after_timeout: 

142 :class:`float` or ``None``, Default = ``None`` 

143 

144 To specify a timeout in seconds for the git command, after which the process 

145 should be killed. 

146 """ 

147 

148 # Use 2 "pump" threads and wait for both to finish. 

149 def pump_stream( 

150 cmdline: List[str], 

151 name: str, 

152 stream: Union[BinaryIO, TextIO], 

153 is_decode: bool, 

154 handler: Union[None, Callable[[Union[bytes, str]], None]], 

155 ) -> None: 

156 try: 

157 for line in stream: 

158 if handler: 

159 if is_decode: 

160 assert isinstance(line, bytes) 

161 line_str = line.decode(defenc) 

162 handler(line_str) 

163 else: 

164 handler(line) 

165 

166 except Exception as ex: 

167 _logger.error(f"Pumping {name!r} of cmd({remove_password_if_present(cmdline)}) failed due to: {ex!r}") 

168 if "I/O operation on closed file" not in str(ex): 

169 # Only reraise if the error was not due to the stream closing. 

170 raise CommandError([f"<{name}-pump>"] + remove_password_if_present(cmdline), ex) from ex 

171 finally: 

172 stream.close() 

173 

174 if hasattr(process, "proc"): 

175 process = cast("Git.AutoInterrupt", process) 

176 cmdline: str | Tuple[str, ...] | List[str] = getattr(process.proc, "args", "") 

177 p_stdout = process.proc.stdout if process.proc else None 

178 p_stderr = process.proc.stderr if process.proc else None 

179 else: 

180 process = cast(Popen, process) # type: ignore[redundant-cast] 

181 cmdline = getattr(process, "args", "") 

182 p_stdout = process.stdout 

183 p_stderr = process.stderr 

184 

185 if not isinstance(cmdline, (tuple, list)): 

186 cmdline = cmdline.split() 

187 

188 pumps: List[Tuple[str, IO, Callable[..., None] | None]] = [] 

189 if p_stdout: 

190 pumps.append(("stdout", p_stdout, stdout_handler)) 

191 if p_stderr: 

192 pumps.append(("stderr", p_stderr, stderr_handler)) 

193 

194 threads: List[threading.Thread] = [] 

195 

196 for name, stream, handler in pumps: 

197 t = threading.Thread(target=pump_stream, args=(cmdline, name, stream, decode_streams, handler)) 

198 t.daemon = True 

199 t.start() 

200 threads.append(t) 

201 

202 # FIXME: Why join? Will block if stdin needs feeding... 

203 for t in threads: 

204 t.join(timeout=kill_after_timeout) 

205 if t.is_alive(): 

206 if isinstance(process, Git.AutoInterrupt): 

207 process._terminate() 

208 else: # Don't want to deal with the other case. 

209 raise RuntimeError( 

210 "Thread join() timed out in cmd.handle_process_output()." 

211 f" kill_after_timeout={kill_after_timeout} seconds" 

212 ) 

213 if stderr_handler: 

214 error_str: Union[str, bytes] = ( 

215 f"error: process killed because it timed out. kill_after_timeout={kill_after_timeout} seconds" 

216 ) 

217 if not decode_streams and isinstance(p_stderr, BinaryIO): 

218 # Assume stderr_handler needs binary input. 

219 error_str = cast(str, error_str) 

220 error_str = error_str.encode() 

221 # We ignore typing on the next line because mypy does not like the way 

222 # we inferred that stderr takes str or bytes. 

223 stderr_handler(error_str) # type: ignore[arg-type] 

224 

225 if finalizer: 

226 finalizer(process) 

227 

228 

229safer_popen: Callable[..., Popen] 

230 

231if sys.platform == "win32": 

232 

233 def _safer_popen_windows( 

234 command: Union[str, Sequence[Any]], 

235 *, 

236 shell: bool = False, 

237 env: Optional[Mapping[str, str]] = None, 

238 **kwargs: Any, 

239 ) -> Popen: 

240 """Call :class:`subprocess.Popen` on Windows but don't include a CWD in the 

241 search. 

242 

243 This avoids an untrusted search path condition where a file like ``git.exe`` in 

244 a malicious repository would be run when GitPython operates on the repository. 

245 The process using GitPython may have an untrusted repository's working tree as 

246 its current working directory. Some operations may temporarily change to that 

247 directory before running a subprocess. In addition, while by default GitPython 

248 does not run external commands with a shell, it can be made to do so, in which 

249 case the CWD of the subprocess, which GitPython usually sets to a repository 

250 working tree, can itself be searched automatically by the shell. This wrapper 

251 covers all those cases. 

252 

253 :note: 

254 This currently works by setting the 

255 :envvar:`NoDefaultCurrentDirectoryInExePath` environment variable during 

256 subprocess creation. It also takes care of passing Windows-specific process 

257 creation flags, but that is unrelated to path search. 

258 

259 :note: 

260 The current implementation contains a race condition on :attr:`os.environ`. 

261 GitPython isn't thread-safe, but a program using it on one thread should 

262 ideally be able to mutate :attr:`os.environ` on another, without 

263 unpredictable results. See comments in: 

264 https://github.com/gitpython-developers/GitPython/pull/1650 

265 """ 

266 # CREATE_NEW_PROCESS_GROUP is needed for some ways of killing it afterwards. 

267 # https://docs.python.org/3/library/subprocess.html#subprocess.Popen.send_signal 

268 # https://docs.python.org/3/library/subprocess.html#subprocess.CREATE_NEW_PROCESS_GROUP 

269 creationflags = subprocess.CREATE_NO_WINDOW | subprocess.CREATE_NEW_PROCESS_GROUP 

270 

271 # When using a shell, the shell is the direct subprocess, so the variable must 

272 # be set in its environment, to affect its search behavior. 

273 if shell: 

274 # The original may be immutable, or the caller may reuse it. Mutate a copy. 

275 env = {} if env is None else dict(env) 

276 env["NoDefaultCurrentDirectoryInExePath"] = "1" # The "1" can be any value. 

277 

278 # When not using a shell, the current process does the search in a 

279 # CreateProcessW API call, so the variable must be set in our environment. With 

280 # a shell, that's unnecessary if https://github.com/python/cpython/issues/101283 

281 # is patched. In Python versions where it is unpatched, in the rare case the 

282 # ComSpec environment variable is unset, the search for the shell itself is 

283 # unsafe. Setting NoDefaultCurrentDirectoryInExePath in all cases, as done here, 

284 # is simpler and protects against that. (As above, the "1" can be any value.) 

285 with patch_env("NoDefaultCurrentDirectoryInExePath", "1"): 

286 return Popen( 

287 command, 

288 shell=shell, 

289 env=env, 

290 creationflags=creationflags, 

291 **kwargs, 

292 ) 

293 

294 safer_popen = _safer_popen_windows 

295else: 

296 safer_popen = Popen 

297 

298 

299def dashify(string: str) -> str: 

300 return string.replace("_", "-") 

301 

302 

303def slots_to_dict(self: "Git", exclude: Sequence[str] = ()) -> Dict[str, Any]: 

304 return {s: getattr(self, s) for s in self.__slots__ if s not in exclude} 

305 

306 

307def dict_to_slots_and__excluded_are_none(self: object, d: Mapping[str, Any], excluded: Sequence[str] = ()) -> None: 

308 for k, v in d.items(): 

309 setattr(self, k, v) 

310 for k in excluded: 

311 setattr(self, k, None) 

312 

313 

314## -- End Utilities -- @} 

315 

316 

317class _AutoInterrupt: 

318 """Process wrapper that terminates the wrapped process on finalization. 

319 

320 This kills/interrupts the stored process instance once this instance goes out of 

321 scope. It is used to prevent processes piling up in case iterators stop reading. 

322 

323 All attributes are wired through to the contained process object. 

324 

325 The wait method is overridden to perform automatic status code checking and possibly 

326 raise. 

327 """ 

328 

329 __slots__ = ("proc", "args", "status") 

330 

331 # If this is non-zero it will override any status code during _terminate, used 

332 # to prevent race conditions in testing. 

333 _status_code_if_terminate: int = 0 

334 

335 def __init__(self, proc: Union[None, subprocess.Popen], args: Any) -> None: 

336 self.proc = proc 

337 self.args = args 

338 self.status: Union[int, None] = None 

339 

340 def _terminate(self) -> None: 

341 """Terminate the underlying process.""" 

342 if self.proc is None: 

343 return 

344 

345 proc = self.proc 

346 self.proc = None 

347 if proc.stdin: 

348 proc.stdin.close() 

349 if proc.stdout: 

350 proc.stdout.close() 

351 if proc.stderr: 

352 proc.stderr.close() 

353 # Did the process finish already so we have a return code? 

354 try: 

355 if proc.poll() is not None: 

356 self.status = self._status_code_if_terminate or proc.poll() 

357 return 

358 except OSError as ex: 

359 _logger.info("Ignored error after process had died: %r", ex) 

360 

361 # It can be that nothing really exists anymore... 

362 if os is None or getattr(os, "kill", None) is None: 

363 return 

364 

365 # Try to kill it. 

366 try: 

367 proc.terminate() 

368 status = proc.wait() # Ensure the process goes away. 

369 

370 self.status = self._status_code_if_terminate or status 

371 except (OSError, AttributeError) as ex: 

372 # On interpreter shutdown (notably on Windows), parts of the stdlib used by 

373 # subprocess can already be torn down (e.g. `subprocess._winapi` becomes None), 

374 # which can cause AttributeError during terminate(). In that case, we prefer 

375 # to silently ignore to avoid noisy "Exception ignored in: __del__" messages. 

376 _logger.info("Ignored error while terminating process: %r", ex) 

377 # END exception handling 

378 

379 def __del__(self) -> None: 

380 self._terminate() 

381 

382 def __getattr__(self, attr: str) -> Any: 

383 return getattr(self.proc, attr) 

384 

385 # TODO: Bad choice to mimic `proc.wait()` but with different args. 

386 def wait(self, stderr: Union[None, str, bytes] = b"") -> int: 

387 """Wait for the process and return its status code. 

388 

389 :param stderr: 

390 Previously read value of stderr, in case stderr is already closed. 

391 

392 :warn: 

393 May deadlock if output or error pipes are used and not handled separately. 

394 

395 :raise git.exc.GitCommandError: 

396 If the return status is not 0. 

397 """ 

398 if stderr is None: 

399 stderr_b = b"" 

400 stderr_b = force_bytes(data=stderr, encoding="utf-8") 

401 status: Union[int, None] 

402 if self.proc is not None: 

403 status = self.proc.wait() 

404 p_stderr = self.proc.stderr 

405 else: # Assume the underlying proc was killed earlier or never existed. 

406 status = self.status 

407 p_stderr = None 

408 

409 def read_all_from_possibly_closed_stream(stream: Union[IO[bytes], None]) -> bytes: 

410 if stream: 

411 try: 

412 return stderr_b + force_bytes(stream.read()) 

413 except (OSError, ValueError): 

414 return stderr_b or b"" 

415 else: 

416 return stderr_b or b"" 

417 

418 # END status handling 

419 

420 if status != 0: 

421 errstr = read_all_from_possibly_closed_stream(p_stderr) 

422 _logger.debug("AutoInterrupt wait stderr: %r" % (errstr,)) 

423 raise GitCommandError(remove_password_if_present(self.args), status, errstr) 

424 return status 

425 

426 

427_AutoInterrupt.__name__ = "AutoInterrupt" 

428_AutoInterrupt.__qualname__ = "Git.AutoInterrupt" 

429 

430 

431class _CatFileContentStream: 

432 """Object representing a sized read-only stream returning the contents of 

433 an object. 

434 

435 This behaves like a stream, but counts the data read and simulates an empty stream 

436 once our sized content region is empty. 

437 

438 If not all data are read to the end of the object's lifetime, we read the rest to 

439 ensure the underlying stream continues to work. 

440 """ 

441 

442 __slots__ = ("_stream", "_nbr", "_size") 

443 

444 def __init__(self, size: int, stream: IO[bytes]) -> None: 

445 self._stream = stream 

446 self._size = size 

447 self._nbr = 0 # Number of bytes read. 

448 

449 # Special case: If the object is empty, has null bytes, get the final 

450 # newline right away. 

451 if size == 0: 

452 stream.read(1) 

453 # END handle empty streams 

454 

455 def read(self, size: int = -1) -> bytes: 

456 bytes_left = self._size - self._nbr 

457 if bytes_left == 0: 

458 return b"" 

459 if size > -1: 

460 # Ensure we don't try to read past our limit. 

461 size = min(bytes_left, size) 

462 else: 

463 # They try to read all, make sure it's not more than what remains. 

464 size = bytes_left 

465 # END check early depletion 

466 data = self._stream.read(size) 

467 self._nbr += len(data) 

468 

469 # Check for depletion, read our final byte to make the stream usable by 

470 # others. 

471 if self._size - self._nbr == 0: 

472 self._stream.read(1) # final newline 

473 # END finish reading 

474 return data 

475 

476 def readline(self, size: int = -1) -> bytes: 

477 if self._nbr == self._size: 

478 return b"" 

479 

480 # Clamp size to lowest allowed value. 

481 bytes_left = self._size - self._nbr 

482 if size > -1: 

483 size = min(bytes_left, size) 

484 else: 

485 size = bytes_left 

486 # END handle size 

487 

488 data = self._stream.readline(size) 

489 self._nbr += len(data) 

490 

491 # Handle final byte. 

492 if self._size - self._nbr == 0: 

493 self._stream.read(1) 

494 # END finish reading 

495 

496 return data 

497 

498 def readlines(self, size: int = -1) -> List[bytes]: 

499 if self._nbr == self._size: 

500 return [] 

501 

502 # Leave all additional logic to our readline method, we just check the size. 

503 out = [] 

504 nbr = 0 

505 while True: 

506 line = self.readline() 

507 if not line: 

508 break 

509 out.append(line) 

510 if size > -1: 

511 nbr += len(line) 

512 if nbr > size: 

513 break 

514 # END handle size constraint 

515 # END readline loop 

516 return out 

517 

518 # skipcq: PYL-E0301 

519 def __iter__(self) -> "Git.CatFileContentStream": 

520 return self 

521 

522 def __next__(self) -> bytes: 

523 line = self.readline() 

524 if not line: 

525 raise StopIteration 

526 

527 return line 

528 

529 next = __next__ 

530 

531 def __del__(self) -> None: 

532 bytes_left = self._size - self._nbr 

533 if bytes_left: 

534 # Read and discard - seeking is impossible within a stream. 

535 # This includes any terminating newline. 

536 self._stream.read(bytes_left + 1) 

537 # END handle incomplete read 

538 

539 

540_CatFileContentStream.__name__ = "CatFileContentStream" 

541_CatFileContentStream.__qualname__ = "Git.CatFileContentStream" 

542 

543 

544_USE_SHELL_DEFAULT_MESSAGE = ( 

545 "Git.USE_SHELL is deprecated, because only its default value of False is safe. " 

546 "It will be removed in a future release." 

547) 

548 

549_USE_SHELL_DANGER_MESSAGE = ( 

550 "Setting Git.USE_SHELL to True is unsafe and insecure, as the effect of special " 

551 "shell syntax cannot usually be accounted for. This can result in a command " 

552 "injection vulnerability and arbitrary code execution. Git.USE_SHELL is deprecated " 

553 "and will be removed in a future release." 

554) 

555 

556 

557def _warn_use_shell(*, extra_danger: bool) -> None: 

558 warnings.warn( 

559 _USE_SHELL_DANGER_MESSAGE if extra_danger else _USE_SHELL_DEFAULT_MESSAGE, 

560 DeprecationWarning, 

561 stacklevel=3, 

562 ) 

563 

564 

565class _GitMeta(type): 

566 """Metaclass for :class:`Git`. 

567 

568 This helps issue :class:`DeprecationWarning` if :attr:`Git.USE_SHELL` is used. 

569 """ 

570 

571 def __getattribute(cls, name: str) -> Any: 

572 if name == "USE_SHELL": 

573 _warn_use_shell(extra_danger=False) 

574 return super().__getattribute__(name) 

575 

576 def __setattr(cls, name: str, value: Any) -> Any: 

577 if name == "USE_SHELL": 

578 _warn_use_shell(extra_danger=value) 

579 super().__setattr__(name, value) 

580 

581 if not TYPE_CHECKING: 

582 # To preserve static checking for undefined/misspelled attributes while letting 

583 # the methods' bodies be type-checked, these are defined as non-special methods, 

584 # then bound to special names out of view of static type checkers. (The original 

585 # names invoke name mangling (leading "__") to avoid confusion in other scopes.) 

586 __getattribute__ = __getattribute 

587 __setattr__ = __setattr 

588 

589 

590GitMeta = _GitMeta 

591"""Alias of :class:`Git`'s metaclass, whether it is :class:`type` or a custom metaclass. 

592 

593Whether the :class:`Git` class has the default :class:`type` as its metaclass or uses a 

594custom metaclass is not documented and may change at any time. This statically checkable 

595metaclass alias is equivalent at runtime to ``type(Git)``. This should almost never be 

596used. Code that benefits from it is likely to be remain brittle even if it is used. 

597 

598In view of the :class:`Git` class's intended use and :class:`Git` objects' dynamic 

599callable attributes representing git subcommands, it rarely makes sense to inherit from 

600:class:`Git` at all. Using :class:`Git` in multiple inheritance can be especially tricky 

601to do correctly. Attempting uses of :class:`Git` where its metaclass is relevant, such 

602as when a sibling class has an unrelated metaclass and a shared lower bound metaclass 

603might have to be introduced to solve a metaclass conflict, is not recommended. 

604 

605:note: 

606 The correct static type of the :class:`Git` class itself, and any subclasses, is 

607 ``Type[Git]``. (This can be written as ``type[Git]`` in Python 3.9 later.) 

608 

609 :class:`GitMeta` should never be used in any annotation where ``Type[Git]`` is 

610 intended or otherwise possible to use. This alias is truly only for very rare and 

611 inherently precarious situations where it is necessary to deal with the metaclass 

612 explicitly. 

613""" 

614 

615 

616class Git(metaclass=_GitMeta): 

617 """The Git class manages communication with the Git binary. 

618 

619 It provides a convenient interface to calling the Git binary, such as in:: 

620 

621 g = Git( git_dir ) 

622 g.init() # calls 'git init' program 

623 rval = g.ls_files() # calls 'git ls-files' program 

624 

625 Debugging: 

626 

627 * Set the :envvar:`GIT_PYTHON_TRACE` environment variable to print each invocation 

628 of the command to stdout. 

629 * Set its value to ``full`` to see details about the returned values. 

630 """ 

631 

632 __slots__ = ( 

633 "_working_dir", 

634 "cat_file_all", 

635 "cat_file_header", 

636 "_version_info", 

637 "_version_info_token", 

638 "_git_options", 

639 "_persistent_git_options", 

640 "_environment", 

641 ) 

642 

643 _excluded_ = ( 

644 "cat_file_all", 

645 "cat_file_header", 

646 "_version_info", 

647 "_version_info_token", 

648 ) 

649 

650 re_unsafe_protocol = re.compile(r"(.+)::.+") 

651 

652 unsafe_git_ls_remote_options = [ 

653 # This option allows arbitrary command execution in git-ls-remote. 

654 "--upload-pack", 

655 ] 

656 

657 def __getstate__(self) -> Dict[str, Any]: 

658 return slots_to_dict(self, exclude=self._excluded_) 

659 

660 def __setstate__(self, d: Dict[str, Any]) -> None: 

661 dict_to_slots_and__excluded_are_none(self, d, excluded=self._excluded_) 

662 

663 # CONFIGURATION 

664 

665 git_exec_name = "git" 

666 """Default git command that should work on Linux, Windows, and other systems.""" 

667 

668 GIT_PYTHON_TRACE = os.environ.get("GIT_PYTHON_TRACE", False) 

669 """Enables debugging of GitPython's git commands.""" 

670 

671 USE_SHELL: bool = False 

672 """Deprecated. If set to ``True``, a shell will be used when executing git commands. 

673 

674 Code that uses ``USE_SHELL = True`` or that passes ``shell=True`` to any GitPython 

675 functions should be updated to use the default value of ``False`` instead. ``True`` 

676 is unsafe unless the effect of syntax treated specially by the shell is fully 

677 considered and accounted for, which is not possible under most circumstances. As 

678 detailed below, it is also no longer needed, even where it had been in the past. 

679 

680 It is in many if not most cases a command injection vulnerability for an application 

681 to set :attr:`USE_SHELL` to ``True``. Any attacker who can cause a specially crafted 

682 fragment of text to make its way into any part of any argument to any git command 

683 (including paths, branch names, etc.) can cause the shell to read and write 

684 arbitrary files and execute arbitrary commands. Innocent input may also accidentally 

685 contain special shell syntax, leading to inadvertent malfunctions. 

686 

687 In addition, how a value of ``True`` interacts with some aspects of GitPython's 

688 operation is not precisely specified and may change without warning, even before 

689 GitPython 4.0.0 when :attr:`USE_SHELL` may be removed. This includes: 

690 

691 * Whether or how GitPython automatically customizes the shell environment. 

692 

693 * Whether, outside of Windows (where :class:`subprocess.Popen` supports lists of 

694 separate arguments even when ``shell=True``), this can be used with any GitPython 

695 functionality other than direct calls to the :meth:`execute` method. 

696 

697 * Whether any GitPython feature that runs git commands ever attempts to partially 

698 sanitize data a shell may treat specially. Currently this is not done. 

699 

700 Prior to GitPython 2.0.8, this had a narrow purpose in suppressing console windows 

701 in graphical Windows applications. In 2.0.8 and higher, it provides no benefit, as 

702 GitPython solves that problem more robustly and safely by using the 

703 ``CREATE_NO_WINDOW`` process creation flag on Windows. 

704 

705 Because Windows path search differs subtly based on whether a shell is used, in rare 

706 cases changing this from ``True`` to ``False`` may keep an unusual git "executable", 

707 such as a batch file, from being found. To fix this, set the command name or full 

708 path in the :envvar:`GIT_PYTHON_GIT_EXECUTABLE` environment variable or pass the 

709 full path to :func:`git.refresh` (or invoke the script using a ``.exe`` shim). 

710 

711 Further reading: 

712 

713 * :meth:`Git.execute` (on the ``shell`` parameter). 

714 * https://github.com/gitpython-developers/GitPython/commit/0d9390866f9ce42870d3116094cd49e0019a970a 

715 * https://learn.microsoft.com/en-us/windows/win32/procthread/process-creation-flags 

716 * https://github.com/python/cpython/issues/91558#issuecomment-1100942950 

717 * https://learn.microsoft.com/en-us/windows/win32/api/processthreadsapi/nf-processthreadsapi-createprocessw 

718 """ 

719 

720 _git_exec_env_var = "GIT_PYTHON_GIT_EXECUTABLE" 

721 _refresh_env_var = "GIT_PYTHON_REFRESH" 

722 

723 GIT_PYTHON_GIT_EXECUTABLE = None 

724 """Provide the full path to the git executable. Otherwise it assumes git is in the 

725 executable search path. 

726 

727 :note: 

728 The git executable is actually found during the refresh step in the top level 

729 ``__init__``. It can also be changed by explicitly calling :func:`git.refresh`. 

730 """ 

731 

732 _refresh_token = object() # Since None would match an initial _version_info_token. 

733 

734 @classmethod 

735 def refresh(cls, path: Union[None, PathLike] = None) -> bool: 

736 """Update information about the git executable :class:`Git` objects will use. 

737 

738 Called by the :func:`git.refresh` function in the top level ``__init__``. 

739 

740 :param path: 

741 Optional path to the git executable. If not absolute, it is resolved 

742 immediately, relative to the current directory. (See note below.) 

743 

744 :note: 

745 The top-level :func:`git.refresh` should be preferred because it calls this 

746 method and may also update other state accordingly. 

747 

748 :note: 

749 There are three different ways to specify the command that refreshing causes 

750 to be used for git: 

751 

752 1. Pass no `path` argument and do not set the 

753 :envvar:`GIT_PYTHON_GIT_EXECUTABLE` environment variable. The command 

754 name ``git`` is used. It is looked up in a path search by the system, in 

755 each command run (roughly similar to how git is found when running 

756 ``git`` commands manually). This is usually the desired behavior. 

757 

758 2. Pass no `path` argument but set the :envvar:`GIT_PYTHON_GIT_EXECUTABLE` 

759 environment variable. The command given as the value of that variable is 

760 used. This may be a simple command or an arbitrary path. It is looked up 

761 in each command run. Setting :envvar:`GIT_PYTHON_GIT_EXECUTABLE` to 

762 ``git`` has the same effect as not setting it. 

763 

764 3. Pass a `path` argument. This path, if not absolute, is immediately 

765 resolved, relative to the current directory. This resolution occurs at 

766 the time of the refresh. When git commands are run, they are run using 

767 that previously resolved path. If a `path` argument is passed, the 

768 :envvar:`GIT_PYTHON_GIT_EXECUTABLE` environment variable is not 

769 consulted. 

770 

771 :note: 

772 Refreshing always sets the :attr:`Git.GIT_PYTHON_GIT_EXECUTABLE` class 

773 attribute, which can be read on the :class:`Git` class or any of its 

774 instances to check what command is used to run git. This attribute should 

775 not be confused with the related :envvar:`GIT_PYTHON_GIT_EXECUTABLE` 

776 environment variable. The class attribute is set no matter how refreshing is 

777 performed. 

778 """ 

779 # Discern which path to refresh with. 

780 if path is not None: 

781 new_git = os.path.expanduser(path) 

782 new_git = os.path.abspath(new_git) 

783 else: 

784 new_git = os.environ.get(cls._git_exec_env_var, cls.git_exec_name) 

785 

786 # Keep track of the old and new git executable path. 

787 old_git = cls.GIT_PYTHON_GIT_EXECUTABLE 

788 old_refresh_token = cls._refresh_token 

789 cls.GIT_PYTHON_GIT_EXECUTABLE = new_git 

790 cls._refresh_token = object() 

791 

792 # Test if the new git executable path is valid. A GitCommandNotFound error is 

793 # raised by us. A PermissionError is raised if the git executable cannot be 

794 # executed for whatever reason. 

795 has_git = False 

796 try: 

797 cls().version() 

798 has_git = True 

799 except (GitCommandNotFound, PermissionError): 

800 pass 

801 

802 # Warn or raise exception if test failed. 

803 if not has_git: 

804 err = ( 

805 dedent( 

806 """\ 

807 Bad git executable. 

808 The git executable must be specified in one of the following ways: 

809 - be included in your $PATH 

810 - be set via $%s 

811 - explicitly set via git.refresh(<full-path-to-git-executable>) 

812 """ 

813 ) 

814 % cls._git_exec_env_var 

815 ) 

816 

817 # Revert to whatever the old_git was. 

818 cls.GIT_PYTHON_GIT_EXECUTABLE = old_git 

819 cls._refresh_token = old_refresh_token 

820 

821 if old_git is None: 

822 # On the first refresh (when GIT_PYTHON_GIT_EXECUTABLE is None) we only 

823 # are quiet, warn, or error depending on the GIT_PYTHON_REFRESH value. 

824 

825 # Determine what the user wants to happen during the initial refresh. We 

826 # expect GIT_PYTHON_REFRESH to either be unset or be one of the 

827 # following values: 

828 # 

829 # 0|q|quiet|s|silence|silent|n|none 

830 # 1|w|warn|warning|l|log 

831 # 2|r|raise|e|error|exception 

832 

833 mode = os.environ.get(cls._refresh_env_var, "raise").lower() 

834 

835 quiet = ["quiet", "q", "silence", "s", "silent", "none", "n", "0"] 

836 warn = ["warn", "w", "warning", "log", "l", "1"] 

837 error = ["error", "e", "exception", "raise", "r", "2"] 

838 

839 if mode in quiet: 

840 pass 

841 elif mode in warn or mode in error: 

842 err = dedent( 

843 """\ 

844 %s 

845 All git commands will error until this is rectified. 

846 

847 This initial message can be silenced or aggravated in the future by setting the 

848 $%s environment variable. Use one of the following values: 

849 - %s: for no message or exception 

850 - %s: for a warning message (logging level CRITICAL, displayed by default) 

851 - %s: for a raised exception 

852 

853 Example: 

854 export %s=%s 

855 """ 

856 ) % ( 

857 err, 

858 cls._refresh_env_var, 

859 "|".join(quiet), 

860 "|".join(warn), 

861 "|".join(error), 

862 cls._refresh_env_var, 

863 quiet[0], 

864 ) 

865 

866 if mode in warn: 

867 _logger.critical(err) 

868 else: 

869 raise ImportError(err) 

870 else: 

871 err = dedent( 

872 """\ 

873 %s environment variable has been set but it has been set with an invalid value. 

874 

875 Use only the following values: 

876 - %s: for no message or exception 

877 - %s: for a warning message (logging level CRITICAL, displayed by default) 

878 - %s: for a raised exception 

879 """ 

880 ) % ( 

881 cls._refresh_env_var, 

882 "|".join(quiet), 

883 "|".join(warn), 

884 "|".join(error), 

885 ) 

886 raise ImportError(err) 

887 

888 # We get here if this was the initial refresh and the refresh mode was 

889 # not error. Go ahead and set the GIT_PYTHON_GIT_EXECUTABLE such that we 

890 # discern the difference between the first refresh at import time 

891 # and subsequent calls to git.refresh or this refresh method. 

892 cls.GIT_PYTHON_GIT_EXECUTABLE = cls.git_exec_name 

893 else: 

894 # After the first refresh (when GIT_PYTHON_GIT_EXECUTABLE is no longer 

895 # None) we raise an exception. 

896 raise GitCommandNotFound(new_git, err) 

897 

898 return has_git 

899 

900 @classmethod 

901 def is_cygwin(cls) -> bool: 

902 return is_cygwin_git(cls.GIT_PYTHON_GIT_EXECUTABLE) 

903 

904 @overload 

905 @classmethod 

906 def polish_url(cls, url: str, is_cygwin: Literal[False] = ..., expand_vars: bool = ...) -> str: ... 

907 

908 @overload 

909 @classmethod 

910 def polish_url(cls, url: str, is_cygwin: Union[None, bool] = None, expand_vars: bool = True) -> str: ... 

911 

912 @classmethod 

913 def polish_url(cls, url: str, is_cygwin: Union[None, bool] = None, expand_vars: bool = True) -> PathLike: 

914 """Remove any backslashes from URLs to be written in config files. 

915 

916 Windows might create config files containing paths with backslashes, but git 

917 stops liking them as it will escape the backslashes. Hence we undo the escaping 

918 just to be sure. 

919 

920 :param expand_vars: 

921 Expand environment variables and an initial ``~``. Disable this for values 

922 obtained from an untrusted source, such as remote URLs. 

923 """ 

924 if is_cygwin is None: 

925 is_cygwin = cls.is_cygwin() 

926 

927 if is_cygwin: 

928 url = cygpath(url, expand_vars=expand_vars) 

929 else: 

930 if expand_vars: 

931 url = os.path.expandvars(url) 

932 if url.startswith("~"): 

933 url = os.path.expanduser(url) 

934 url = url.replace("\\\\", "\\").replace("\\", "/") 

935 return url 

936 

937 @classmethod 

938 def check_unsafe_protocols(cls, url: str) -> None: 

939 """Check for unsafe protocols. 

940 

941 Apart from the usual protocols (http, git, ssh), Git allows "remote helpers" 

942 that have the form ``<transport>::<address>``. One of these helpers (``ext::``) 

943 can be used to invoke any arbitrary command. 

944 

945 See: 

946 

947 - https://git-scm.com/docs/gitremote-helpers 

948 - https://git-scm.com/docs/git-remote-ext 

949 """ 

950 match = cls.re_unsafe_protocol.match(url) 

951 if match: 

952 protocol = match.group(1) 

953 raise UnsafeProtocolError( 

954 f"The `{protocol}::` protocol looks suspicious, use `allow_unsafe_protocols=True` to allow it." 

955 ) 

956 

957 @classmethod 

958 def _canonicalize_option_name(cls, option: str) -> str: 

959 """Return the option name used for unsafe-option checks. 

960 

961 Examples: 

962 ``"--upload-pack=/tmp/helper"`` -> ``"upload-pack"`` 

963 ``"upload_pack"`` -> ``"upload-pack"`` 

964 ``"--config core.filemode=false"`` -> ``"config"`` 

965 """ 

966 option_name = option.lstrip("-").split("=", 1)[0] 

967 option_tokens = option_name.split(None, 1) 

968 if not option_tokens: 

969 return "" 

970 return dashify(option_tokens[0]) 

971 

972 @classmethod 

973 def check_unsafe_options(cls, options: List[str], unsafe_options: List[str]) -> None: 

974 """Raise :class:`~git.exc.UnsafeOptionError` for blocked option spellings. 

975 

976 In addition to exact matches, this rejects abbreviated long options accepted 

977 by Git (for example, ``--upl`` for ``--upload-pack``) and unsafe short options 

978 whose values are joined to the same token, including after clusterable flags 

979 (for example, ``-uVALUE`` and ``-fuVALUE``). 

980 

981 A list containing only bare names is treated as normalized keyword arguments, 

982 so multi-character names such as ``upload_p`` are checked as long-option 

983 abbreviations. If any item starts with ``-``, the list is treated as tokenized 

984 command-line input: bare items can be option values and are not checked as 

985 abbreviations. Thus ``["--origin", "upload"]`` is allowed. Single-dash options 

986 use short-option parsing rather than broad prefix matching, preserving safe 

987 attached values such as ``-oupstream`` and ``-bcurrent``. 

988 

989 Some options passed to ``git <command>`` can execute arbitrary commands and 

990 are therefore blocked by default unless the caller explicitly allows them. 

991 """ 

992 # Options can be of the form `foo`, `--foo`, `--foo bar`, or `--foo=bar`. 

993 # Git accepts any unambiguous prefix of a long option, so an abbreviated 

994 # spelling such as `--upl` for `--upload-pack` must be rejected too. An 

995 # option is unsafe if its canonical name is a prefix of any blocked 

996 # option's canonical name. Only long options and multi-character kwargs 

997 # can be abbreviations; single-character short options remain exact-match 

998 # only. 

999 canonical_unsafe_options = {cls._canonicalize_option_name(option): option for option in unsafe_options} 

1000 unsafe_short_options = { 

1001 canonical: option 

1002 for canonical, option in canonical_unsafe_options.items() 

1003 if option.startswith("-") and not option.startswith("--") and len(canonical) == 1 

1004 } 

1005 # These value-less Git flags can be clustered before another short option 

1006 # (for example, ``-fuVALUE``). Stop at any other character because it may 

1007 # begin an attached value, as ``o`` does in the safe option ``-oupstream``. 

1008 clusterable_short_options = frozenset("46flnqsv") 

1009 options_are_kwargs = all(not option.startswith("-") for option in options) 

1010 for option in options: 

1011 candidate = cls._canonicalize_option_name(option) 

1012 if not candidate: 

1013 continue 

1014 unsafe_option = canonical_unsafe_options.get(candidate) 

1015 if unsafe_option is not None: 

1016 raise UnsafeOptionError(f"{unsafe_option} is not allowed, use `allow_unsafe_options=True` to allow it.") 

1017 option_token = option.split("=", 1)[0].split(None, 1)[0] 

1018 if option_token.startswith("-") and not option_token.startswith("--"): 

1019 for option_char in option_token[1:]: 

1020 unsafe_option = unsafe_short_options.get(option_char) 

1021 if unsafe_option is not None: 

1022 raise UnsafeOptionError( 

1023 f"{unsafe_option} is not allowed, use `allow_unsafe_options=True` to allow it." 

1024 ) 

1025 if option_char not in clusterable_short_options: 

1026 break 

1027 if not (option.startswith("--") or (options_are_kwargs and len(candidate) > 1)): 

1028 continue 

1029 for canonical, unsafe_option in canonical_unsafe_options.items(): 

1030 if canonical.startswith(candidate): 

1031 raise UnsafeOptionError( 

1032 f"{unsafe_option} is not allowed, use `allow_unsafe_options=True` to allow it." 

1033 ) 

1034 

1035 @classmethod 

1036 def _option_candidates(cls, args: Sequence[Any] = (), kwargs: Optional[Mapping[str, Any]] = None) -> List[str]: 

1037 """Collect possible option spellings before command-line transformation.""" 

1038 options = [ 

1039 option for option in cls._unpack_args([arg for arg in args if arg is not None]) if option.startswith("-") 

1040 ] 

1041 if kwargs: 

1042 split_single_char_options = kwargs.get("split_single_char_options", True) 

1043 for key, value in kwargs.items(): 

1044 values = value if isinstance(value, (list, tuple)) else (value,) 

1045 if any(value is True or (value is not False and value is not None) for value in values): 

1046 key = str(key) 

1047 options.append(f"-{key}" if len(key) == 1 else f"--{dashify(key)}") 

1048 if len(key) == 1 and split_single_char_options: 

1049 options.extend( 

1050 str(value) 

1051 for value in values 

1052 if value is not True and value not in (False, None) and str(value).startswith("-") 

1053 ) 

1054 return options 

1055 

1056 AutoInterrupt: TypeAlias = _AutoInterrupt 

1057 

1058 CatFileContentStream: TypeAlias = _CatFileContentStream 

1059 

1060 def __init__(self, working_dir: Union[None, PathLike] = None) -> None: 

1061 """Initialize this instance with: 

1062 

1063 :param working_dir: 

1064 Git directory we should work in. If ``None``, we always work in the current 

1065 directory as returned by :func:`os.getcwd`. 

1066 This is meant to be the working tree directory if available, or the 

1067 ``.git`` directory in case of bare repositories. 

1068 """ 

1069 super().__init__() 

1070 self._working_dir = expand_path(working_dir) 

1071 self._git_options: Union[List[str], Tuple[str, ...]] = () 

1072 self._persistent_git_options: List[str] = [] 

1073 

1074 # Extra environment variables to pass to git commands 

1075 self._environment: Dict[str, str] = {} 

1076 

1077 # Cached version slots 

1078 self._version_info: Union[Tuple[int, ...], None] = None 

1079 self._version_info_token: object = None 

1080 

1081 # Cached command slots 

1082 self.cat_file_header: Union[None, TBD] = None 

1083 self.cat_file_all: Union[None, TBD] = None 

1084 

1085 def __getattribute__(self, name: str) -> Any: 

1086 if name == "USE_SHELL": 

1087 _warn_use_shell(extra_danger=False) 

1088 return super().__getattribute__(name) 

1089 

1090 def __getattr__(self, name: str) -> Any: 

1091 """A convenience method as it allows to call the command as if it was an object. 

1092 

1093 :return: 

1094 Callable object that will execute call :meth:`_call_process` with your 

1095 arguments. 

1096 """ 

1097 if name.startswith("_"): 

1098 return super().__getattribute__(name) 

1099 return lambda *args, **kwargs: self._call_process(name, *args, **kwargs) 

1100 

1101 def set_persistent_git_options(self, **kwargs: Any) -> None: 

1102 """Specify command line options to the git executable for subsequent 

1103 subcommand calls. 

1104 

1105 :param kwargs: 

1106 A dict of keyword arguments. 

1107 These arguments are passed as in :meth:`_call_process`, but will be passed 

1108 to the git command rather than the subcommand. 

1109 """ 

1110 

1111 self._persistent_git_options = self.transform_kwargs(split_single_char_options=True, **kwargs) 

1112 

1113 def ls_remote( 

1114 self, 

1115 *args: Any, 

1116 allow_unsafe_options: bool = False, 

1117 **kwargs: Any, 

1118 ) -> Union[str, bytes, Tuple[int, Union[str, bytes], str], "Git.AutoInterrupt"]: 

1119 """List references in a remote repository. 

1120 

1121 :param allow_unsafe_options: 

1122 Allow unsafe options, like ``--upload-pack``. 

1123 """ 

1124 if not allow_unsafe_options: 

1125 candidate_options = self._option_candidates(args, kwargs) 

1126 Git.check_unsafe_options(options=candidate_options, unsafe_options=self.unsafe_git_ls_remote_options) 

1127 return self._call_process("ls_remote", *args, **kwargs) 

1128 

1129 @property 

1130 def working_dir(self) -> Union[None, PathLike]: 

1131 """:return: Git directory we are working on""" 

1132 return self._working_dir 

1133 

1134 @property 

1135 def version_info(self) -> Tuple[int, ...]: 

1136 """ 

1137 :return: Tuple with integers representing the major, minor and additional 

1138 version numbers as parsed from :manpage:`git-version(1)`. Up to four fields 

1139 are used. 

1140 

1141 This value is generated on demand and is cached. 

1142 """ 

1143 # Refreshing is global, but version_info caching is per-instance. 

1144 refresh_token = self._refresh_token # Copy token in case of concurrent refresh. 

1145 

1146 # Use the cached version if obtained after the most recent refresh. 

1147 if self._version_info_token is refresh_token: 

1148 assert self._version_info is not None, "Bug: corrupted token-check state" 

1149 return self._version_info 

1150 

1151 # Run "git version" and parse it. 

1152 process_version = self._call_process("version") 

1153 version_string = process_version.split(" ")[2] 

1154 version_fields = version_string.split(".")[:4] 

1155 leading_numeric_fields = itertools.takewhile(str.isdigit, version_fields) 

1156 self._version_info = tuple(map(int, leading_numeric_fields)) 

1157 

1158 # This value will be considered valid until the next refresh. 

1159 self._version_info_token = refresh_token 

1160 return self._version_info 

1161 

1162 @overload 

1163 def execute( 

1164 self, 

1165 command: Union[str, Sequence[Any]], 

1166 *, 

1167 as_process: Literal[True], 

1168 ) -> "AutoInterrupt": ... 

1169 

1170 @overload 

1171 def execute( 

1172 self, 

1173 command: Union[str, Sequence[Any]], 

1174 *, 

1175 as_process: Literal[False] = False, 

1176 stdout_as_string: Literal[True], 

1177 ) -> Union[str, Tuple[int, str, str]]: ... 

1178 

1179 @overload 

1180 def execute( 

1181 self, 

1182 command: Union[str, Sequence[Any]], 

1183 *, 

1184 as_process: Literal[False] = False, 

1185 stdout_as_string: Literal[False] = False, 

1186 ) -> Union[bytes, Tuple[int, bytes, str]]: ... 

1187 

1188 @overload 

1189 def execute( 

1190 self, 

1191 command: Union[str, Sequence[Any]], 

1192 *, 

1193 with_extended_output: Literal[False], 

1194 as_process: Literal[False], 

1195 stdout_as_string: Literal[True], 

1196 ) -> str: ... 

1197 

1198 @overload 

1199 def execute( 

1200 self, 

1201 command: Union[str, Sequence[Any]], 

1202 *, 

1203 with_extended_output: Literal[False], 

1204 as_process: Literal[False], 

1205 stdout_as_string: Literal[False], 

1206 ) -> bytes: ... 

1207 

1208 def execute( 

1209 self, 

1210 command: Union[str, Sequence[Any]], 

1211 istream: Union[None, BinaryIO] = None, 

1212 with_extended_output: bool = False, 

1213 with_exceptions: bool = True, 

1214 as_process: bool = False, 

1215 output_stream: Union[None, BinaryIO] = None, 

1216 stdout_as_string: bool = True, 

1217 kill_after_timeout: Union[None, float] = None, 

1218 with_stdout: bool = True, 

1219 universal_newlines: bool = False, 

1220 shell: Union[None, bool] = None, 

1221 env: Union[None, Mapping[str, str]] = None, 

1222 max_chunk_size: int = io.DEFAULT_BUFFER_SIZE, 

1223 strip_newline_in_stdout: bool = True, 

1224 **subprocess_kwargs: Any, 

1225 ) -> Union[str, bytes, Tuple[int, Union[str, bytes], str], AutoInterrupt]: 

1226 R"""Handle executing the command, and consume and return the returned 

1227 information (stdout). 

1228 

1229 :param command: 

1230 The command to execute. A sequence of program arguments is recommended. 

1231 A string is also accepted, but its meaning is strongly platform-dependent. 

1232 

1233 By default, a shell is not used. On Unix-like systems, a string is the whole 

1234 program name (so ``"git log -n 1"`` raises :class:`GitCommandNotFound`). On 

1235 Windows, the program parses the arguments itself, so multi-word strings can 

1236 work but are not portable. 

1237 

1238 Avoid ``shell=True`` (and :attr:`Git.USE_SHELL`): this runs the command in 

1239 a shell, which is generally unsafe. The shell interprets metacharacters 

1240 such as ``;``, ``|``, ``&``, ``$(...)``, ``$VAR``, ``%VAR%``, and ``^`` 

1241 (depending on the platform) as syntax. Any untrusted text in the command 

1242 can then execute arbitrary OS commands. See :attr:`Git.USE_SHELL`. 

1243 

1244 Producing a sequence automatically by :func:`shlex.split` and passing it 

1245 as the command is far safer than ``shell=True``. But :func:`shlex.split` 

1246 parses POSIX shell syntax on all systems, and the result is still unsafe 

1247 for anything but *fixed, fully trusted* strings. Do not use it on strings 

1248 built by interpolating values: whitespace or quoting in an untrusted value 

1249 can still inject arguments. For input derived in any way from untrusted 

1250 data, build the argument sequence yourself, while ensuring each argument 

1251 is fully sanitized. 

1252 

1253 :param istream: 

1254 Standard input filehandle passed to :class:`subprocess.Popen`. 

1255 

1256 :param with_extended_output: 

1257 Whether to return a (status, stdout, stderr) tuple. 

1258 

1259 :param with_exceptions: 

1260 Whether to raise an exception when git returns a non-zero status. 

1261 

1262 :param as_process: 

1263 Whether to return the created process instance directly from which 

1264 streams can be read on demand. This will render `with_extended_output` 

1265 and `with_exceptions` ineffective - the caller will have to deal with 

1266 the details. It is important to note that the process will be placed 

1267 into an :class:`AutoInterrupt` wrapper that will interrupt the process 

1268 once it goes out of scope. If you use the command in iterators, you 

1269 should pass the whole process instance instead of a single stream. 

1270 

1271 :param output_stream: 

1272 If set to a file-like object, data produced by the git command will be 

1273 copied to the given stream instead of being returned as a string. 

1274 This feature only has any effect if `as_process` is ``False``. 

1275 

1276 :param stdout_as_string: 

1277 If ``False``, the command's standard output will be bytes. Otherwise, it 

1278 will be decoded into a string using the default encoding (usually UTF-8). 

1279 The latter can fail, if the output contains binary data. 

1280 

1281 :param kill_after_timeout: 

1282 Specifies a timeout in seconds for the git command, after which the process 

1283 should be killed. This will have no effect if `as_process` is set to 

1284 ``True``. It is set to ``None`` by default and will let the process run 

1285 until the timeout is explicitly specified. Uses of this feature should be 

1286 carefully considered, due to the following limitations: 

1287 

1288 1. This feature is not supported at all on Windows. 

1289 2. Effectiveness may vary by operating system. ``ps --ppid`` is used to 

1290 enumerate child processes, which is available on most GNU/Linux systems 

1291 but not most others. 

1292 3. Deeper descendants do not receive signals, though they may sometimes 

1293 terminate as a consequence of their parent processes being killed. 

1294 4. `kill_after_timeout` uses ``SIGKILL``, which can have negative side 

1295 effects on a repository. For example, stale locks in case of 

1296 :manpage:`git-gc(1)` could render the repository incapable of accepting 

1297 changes until the lock is manually removed. 

1298 

1299 :param with_stdout: 

1300 If ``True``, default ``True``, we open stdout on the created process. 

1301 

1302 :param universal_newlines: 

1303 If ``True``, pipes will be opened as text, and lines are split at all known 

1304 line endings. 

1305 

1306 :param shell: 

1307 Whether to invoke commands through a shell 

1308 (see :class:`Popen(..., shell=True) <subprocess.Popen>`). 

1309 If this is not ``None``, it overrides :attr:`USE_SHELL`. 

1310 

1311 Passing ``shell=True`` to this or any other GitPython function should be 

1312 avoided, as it is unsafe under most circumstances. This is because it is 

1313 typically not feasible to fully consider and account for the effect of shell 

1314 expansions, especially when passing ``shell=True`` to other methods that 

1315 forward it to :meth:`Git.execute`. Passing ``shell=True`` is also no longer 

1316 needed (nor useful) to work around any known operating system specific 

1317 issues. 

1318 

1319 On Unix-like systems, when migrating away from passing string commands with 

1320 ``shell=True``, :func:`shlex.split` may serve as a transitional step in rare 

1321 cases, with extreme care. (Drop ``shell=True`` and pass the resulting 

1322 sequence as the command.) See the `command` parameter above on the risks. 

1323 

1324 :param env: 

1325 A dictionary of environment variables to be passed to 

1326 :class:`subprocess.Popen`. 

1327 

1328 :param max_chunk_size: 

1329 Maximum number of bytes in one chunk of data passed to the `output_stream` 

1330 in one invocation of its ``write()`` method. If the given number is not 

1331 positive then the default value is used. 

1332 

1333 :param strip_newline_in_stdout: 

1334 Whether to strip the trailing ``\n`` of the command stdout. 

1335 

1336 :param subprocess_kwargs: 

1337 Keyword arguments to be passed to :class:`subprocess.Popen`. Please note 

1338 that some of the valid kwargs are already set by this method; the ones you 

1339 specify may not be the same ones. 

1340 

1341 :return: 

1342 * str(output), if `extended_output` is ``False`` (Default) 

1343 * tuple(int(status), str(stdout), str(stderr)), 

1344 if `extended_output` is ``True`` 

1345 

1346 If `output_stream` is ``True``, the stdout value will be your output stream: 

1347 

1348 * output_stream, if `extended_output` is ``False`` 

1349 * tuple(int(status), output_stream, str(stderr)), 

1350 if `extended_output` is ``True`` 

1351 

1352 Note that git is executed with ``LC_MESSAGES="C"`` to ensure consistent 

1353 output regardless of system language. 

1354 

1355 :raise git.exc.GitCommandError: 

1356 

1357 :note: 

1358 If you add additional keyword arguments to the signature of this method, you 

1359 must update the ``execute_kwargs`` variable housed in this module. 

1360 """ 

1361 # Remove password for the command if present. 

1362 redacted_command = remove_password_if_present(command) 

1363 if self.GIT_PYTHON_TRACE and (self.GIT_PYTHON_TRACE != "full" or as_process): 

1364 _logger.info(" ".join(redacted_command)) 

1365 

1366 # Allow the user to have the command executed in their working dir. 

1367 try: 

1368 cwd = self._working_dir or os.getcwd() # type: Optional[PathLike] 

1369 if not os.access(str(cwd), os.X_OK): 

1370 cwd = None 

1371 except FileNotFoundError: 

1372 cwd = None 

1373 

1374 # Start the process. 

1375 inline_env = env 

1376 env = os.environ.copy() 

1377 # Attempt to force all output to plain ASCII English, which is what some parsing 

1378 # code may expect. 

1379 # According to https://askubuntu.com/a/311796, we are setting LANGUAGE as well 

1380 # just to be sure. 

1381 env["LANGUAGE"] = "C" 

1382 env["LC_ALL"] = "C" 

1383 env.update(self._environment) 

1384 if inline_env is not None: 

1385 env.update(inline_env) 

1386 

1387 if sys.platform == "win32": 

1388 if kill_after_timeout is not None: 

1389 raise GitCommandError( 

1390 redacted_command, 

1391 '"kill_after_timeout" feature is not supported on Windows.', 

1392 ) 

1393 cmd_not_found_exception = OSError 

1394 else: 

1395 cmd_not_found_exception = FileNotFoundError 

1396 # END handle 

1397 

1398 stdout_sink = PIPE if with_stdout else getattr(subprocess, "DEVNULL", None) or open(os.devnull, "wb") 

1399 if shell is None: 

1400 # Get the value of USE_SHELL with no deprecation warning. Do this without 

1401 # warnings.catch_warnings, to avoid a race condition with application code 

1402 # configuring warnings. The value could be looked up in type(self).__dict__ 

1403 # or Git.__dict__, but those can break under some circumstances. This works 

1404 # the same as self.USE_SHELL in more situations; see Git.__getattribute__. 

1405 shell = super().__getattribute__("USE_SHELL") 

1406 _logger.debug( 

1407 "Popen(%s, cwd=%s, stdin=%s, shell=%s, universal_newlines=%s)", 

1408 redacted_command, 

1409 cwd, 

1410 "<valid stream>" if istream else "None", 

1411 shell, 

1412 universal_newlines, 

1413 ) 

1414 try: 

1415 proc = safer_popen( 

1416 command, 

1417 env=env, 

1418 cwd=cwd, 

1419 bufsize=-1, 

1420 stdin=(istream or DEVNULL), 

1421 stderr=PIPE, 

1422 stdout=stdout_sink, 

1423 shell=shell, 

1424 universal_newlines=universal_newlines, 

1425 encoding=defenc if universal_newlines else None, 

1426 **subprocess_kwargs, 

1427 ) 

1428 except cmd_not_found_exception as err: 

1429 raise GitCommandNotFound(redacted_command, err) from err 

1430 else: 

1431 # Replace with a typeguard for Popen[bytes]? 

1432 proc.stdout = cast(BinaryIO, proc.stdout) 

1433 proc.stderr = cast(BinaryIO, proc.stderr) 

1434 

1435 if as_process: 

1436 return self.AutoInterrupt(proc, command) 

1437 

1438 if sys.platform != "win32" and kill_after_timeout is not None: 

1439 # Help mypy figure out this is not None even when used inside communicate(). 

1440 timeout = kill_after_timeout 

1441 

1442 def kill_process(pid: int) -> None: 

1443 """Callback to kill a process. 

1444 

1445 This callback implementation would be ineffective and unsafe on Windows. 

1446 """ 

1447 p = Popen(["ps", "--ppid", str(pid)], stdout=PIPE) 

1448 child_pids = [] 

1449 if p.stdout is not None: 

1450 for line in p.stdout: 

1451 if len(line.split()) > 0: 

1452 local_pid = (line.split())[0] 

1453 if local_pid.isdigit(): 

1454 child_pids.append(int(local_pid)) 

1455 try: 

1456 os.kill(pid, signal.SIGKILL) 

1457 for child_pid in child_pids: 

1458 try: 

1459 os.kill(child_pid, signal.SIGKILL) 

1460 except OSError: 

1461 pass 

1462 # Tell the main routine that the process was killed. 

1463 kill_check.set() 

1464 except OSError: 

1465 # It is possible that the process gets completed in the duration 

1466 # after timeout happens and before we try to kill the process. 

1467 pass 

1468 return 

1469 

1470 def communicate() -> Tuple[AnyStr, AnyStr]: 

1471 watchdog.start() 

1472 out, err = proc.communicate() 

1473 watchdog.cancel() 

1474 if kill_check.is_set(): 

1475 err = 'Timeout: the command "%s" did not complete in %d secs.' % ( 

1476 " ".join(redacted_command), 

1477 timeout, 

1478 ) 

1479 if not universal_newlines: 

1480 err = err.encode(defenc) 

1481 return out, err 

1482 

1483 # END helpers 

1484 

1485 kill_check = threading.Event() 

1486 watchdog = threading.Timer(timeout, kill_process, args=(proc.pid,)) 

1487 else: 

1488 communicate = proc.communicate 

1489 

1490 # Wait for the process to return. 

1491 status = 0 

1492 stdout_value: Union[str, bytes] = b"" 

1493 stderr_value: Union[str, bytes] = b"" 

1494 newline = "\n" if universal_newlines else b"\n" 

1495 try: 

1496 if output_stream is None: 

1497 stdout_value, stderr_value = communicate() 

1498 # Strip trailing "\n". 

1499 if stdout_value is not None and stdout_value.endswith(newline) and strip_newline_in_stdout: # type: ignore[arg-type] 

1500 stdout_value = stdout_value[:-1] 

1501 if stderr_value is not None and stderr_value.endswith(newline): # type: ignore[arg-type] 

1502 stderr_value = stderr_value[:-1] 

1503 

1504 status = proc.returncode 

1505 else: 

1506 max_chunk_size = max_chunk_size if max_chunk_size and max_chunk_size > 0 else io.DEFAULT_BUFFER_SIZE 

1507 if proc.stdout is not None: 

1508 stream_copy(proc.stdout, output_stream, max_chunk_size) 

1509 stdout_value = proc.stdout.read() 

1510 if proc.stderr is not None: 

1511 stderr_value = proc.stderr.read() 

1512 # Strip trailing "\n". 

1513 if stderr_value is not None and stderr_value.endswith(newline): # type: ignore[arg-type] 

1514 stderr_value = stderr_value[:-1] 

1515 status = proc.wait() 

1516 # END stdout handling 

1517 finally: 

1518 if proc.stdout is not None: 

1519 proc.stdout.close() 

1520 if proc.stderr is not None: 

1521 proc.stderr.close() 

1522 

1523 if self.GIT_PYTHON_TRACE == "full": 

1524 cmdstr = " ".join(redacted_command) 

1525 

1526 def as_text(stdout_value: Union[bytes, str]) -> str: 

1527 return not output_stream and safe_decode(stdout_value) or "<OUTPUT_STREAM>" 

1528 

1529 # END as_text 

1530 

1531 if stderr_value: 

1532 _logger.info( 

1533 "%s -> %d; stdout: '%s'; stderr: '%s'", 

1534 cmdstr, 

1535 status, 

1536 as_text(stdout_value), 

1537 safe_decode(stderr_value), 

1538 ) 

1539 elif stdout_value: 

1540 _logger.info("%s -> %d; stdout: '%s'", cmdstr, status, as_text(stdout_value)) 

1541 else: 

1542 _logger.info("%s -> %d", cmdstr, status) 

1543 # END handle debug printing 

1544 

1545 if with_exceptions and status != 0: 

1546 raise GitCommandError(redacted_command, status, stderr_value, stdout_value) 

1547 

1548 if isinstance(stdout_value, bytes) and stdout_as_string: # Could also be output_stream. 

1549 stdout_value = safe_decode(stdout_value) 

1550 

1551 # Allow access to the command's status code. 

1552 if with_extended_output: 

1553 return (status, stdout_value, safe_decode(stderr_value)) 

1554 else: 

1555 return stdout_value 

1556 

1557 def environment(self) -> Dict[str, str]: 

1558 return self._environment 

1559 

1560 def update_environment(self, **kwargs: Any) -> Dict[str, Union[str, None]]: 

1561 """Set environment variables for future git invocations. Return all changed 

1562 values in a format that can be passed back into this function to revert the 

1563 changes. 

1564 

1565 Examples:: 

1566 

1567 old_env = self.update_environment(PWD='/tmp') 

1568 self.update_environment(**old_env) 

1569 

1570 :param kwargs: 

1571 Environment variables to use for git processes. 

1572 

1573 :return: 

1574 Dict that maps environment variables to their old values 

1575 """ 

1576 old_env = {} 

1577 for key, value in kwargs.items(): 

1578 # Set value if it is None. 

1579 if value is not None: 

1580 old_env[key] = self._environment.get(key) 

1581 self._environment[key] = value 

1582 # Remove key from environment if its value is None. 

1583 elif key in self._environment: 

1584 old_env[key] = self._environment[key] 

1585 del self._environment[key] 

1586 return old_env 

1587 

1588 @contextlib.contextmanager 

1589 def custom_environment(self, **kwargs: Any) -> Iterator[None]: 

1590 """A context manager around the above :meth:`update_environment` method to 

1591 restore the environment back to its previous state after operation. 

1592 

1593 Examples:: 

1594 

1595 with self.custom_environment(GIT_SSH='/bin/ssh_wrapper'): 

1596 repo.remotes.origin.fetch() 

1597 

1598 :param kwargs: 

1599 See :meth:`update_environment`. 

1600 """ 

1601 old_env = self.update_environment(**kwargs) 

1602 try: 

1603 yield 

1604 finally: 

1605 self.update_environment(**old_env) 

1606 

1607 def transform_kwarg(self, name: str, value: Any, split_single_char_options: bool) -> List[str]: 

1608 if len(name) == 1: 

1609 if value is True: 

1610 return ["-%s" % name] 

1611 elif value not in (False, None): 

1612 if split_single_char_options: 

1613 return ["-%s" % name, "%s" % value] 

1614 else: 

1615 return ["-%s%s" % (name, value)] 

1616 else: 

1617 if value is True: 

1618 return ["--%s" % dashify(name)] 

1619 elif value is not False and value is not None: 

1620 return ["--%s=%s" % (dashify(name), value)] 

1621 return [] 

1622 

1623 def transform_kwargs(self, split_single_char_options: bool = True, **kwargs: Any) -> List[str]: 

1624 """Transform Python-style kwargs into git command line options.""" 

1625 args = [] 

1626 for k, v in kwargs.items(): 

1627 if isinstance(v, (list, tuple)): 

1628 for value in v: 

1629 args += self.transform_kwarg(k, value, split_single_char_options) 

1630 else: 

1631 args += self.transform_kwarg(k, v, split_single_char_options) 

1632 return args 

1633 

1634 @classmethod 

1635 def _unpack_args(cls, arg_list: Sequence[Any]) -> List[str]: 

1636 outlist = [] 

1637 if isinstance(arg_list, (list, tuple)): 

1638 for arg in arg_list: 

1639 outlist.extend(cls._unpack_args(arg)) 

1640 else: 

1641 outlist.append(str(arg_list)) 

1642 

1643 return outlist 

1644 

1645 def __call__(self, **kwargs: Any) -> "Git": 

1646 """Specify command line options to the git executable for a subcommand call. 

1647 

1648 :param kwargs: 

1649 A dict of keyword arguments. 

1650 These arguments are passed as in :meth:`_call_process`, but will be passed 

1651 to the git command rather than the subcommand. 

1652 

1653 Examples:: 

1654 

1655 git(work_tree='/tmp').difftool() 

1656 """ 

1657 self._git_options = self.transform_kwargs(split_single_char_options=True, **kwargs) 

1658 return self 

1659 

1660 @overload 

1661 def _call_process( 

1662 self, method: str, *args: None, **kwargs: None 

1663 ) -> str: ... # If no args were given, execute the call with all defaults. 

1664 

1665 @overload 

1666 def _call_process( 

1667 self, 

1668 method: str, 

1669 istream: int, 

1670 as_process: Literal[True], 

1671 *args: Any, 

1672 **kwargs: Any, 

1673 ) -> "Git.AutoInterrupt": ... 

1674 

1675 @overload 

1676 def _call_process( 

1677 self, method: str, *args: Any, **kwargs: Any 

1678 ) -> Union[str, bytes, Tuple[int, Union[str, bytes], str], "Git.AutoInterrupt"]: ... 

1679 

1680 def _call_process( 

1681 self, method: str, *args: Any, **kwargs: Any 

1682 ) -> Union[str, bytes, Tuple[int, Union[str, bytes], str], "Git.AutoInterrupt"]: 

1683 """Run the given git command with the specified arguments and return the result 

1684 as a string. 

1685 

1686 :param method: 

1687 The command. Contained ``_`` characters will be converted to hyphens, such 

1688 as in ``ls_files`` to call ``ls-files``. 

1689 

1690 :param args: 

1691 The list of arguments. If ``None`` is included, it will be pruned. 

1692 This allows your commands to call git more conveniently, as ``None`` is 

1693 realized as non-existent. 

1694 

1695 :param kwargs: 

1696 Contains key-values for the following: 

1697 

1698 - The :meth:`execute()` kwds, as listed in ``execute_kwargs``. 

1699 - "Command options" to be converted by :meth:`transform_kwargs`. 

1700 - The ``insert_kwargs_after`` key which its value must match one of 

1701 ``*args``. 

1702 

1703 It also contains any command options, to be appended after the matched arg. 

1704 

1705 Examples:: 

1706 

1707 git.rev_list('master', max_count=10, header=True) 

1708 

1709 turns into:: 

1710 

1711 git rev-list --max-count=10 --header master 

1712 

1713 :return: 

1714 Same as :meth:`execute`. If no args are given, used :meth:`execute`'s 

1715 default (especially ``as_process = False``, ``stdout_as_string = True``) and 

1716 return :class:`str`. 

1717 """ 

1718 # Handle optional arguments prior to calling transform_kwargs. 

1719 # Otherwise these'll end up in args, which is bad. 

1720 exec_kwargs = {k: v for k, v in kwargs.items() if k in execute_kwargs} 

1721 opts_kwargs = {k: v for k, v in kwargs.items() if k not in execute_kwargs} 

1722 

1723 insert_after_this_arg = opts_kwargs.pop("insert_kwargs_after", None) 

1724 

1725 # Prepare the argument list. 

1726 

1727 opt_args = self.transform_kwargs(**opts_kwargs) 

1728 ext_args = self._unpack_args([a for a in args if a is not None]) 

1729 

1730 if insert_after_this_arg is None: 

1731 args_list = opt_args + ext_args 

1732 else: 

1733 try: 

1734 index = ext_args.index(insert_after_this_arg) 

1735 except ValueError as err: 

1736 raise ValueError( 

1737 "Couldn't find argument '%s' in args %s to insert cmd options after" 

1738 % (insert_after_this_arg, str(ext_args)) 

1739 ) from err 

1740 # END handle error 

1741 args_list = ext_args[: index + 1] + opt_args + ext_args[index + 1 :] 

1742 # END handle opts_kwargs 

1743 

1744 call = [self.GIT_PYTHON_GIT_EXECUTABLE] 

1745 

1746 # Add persistent git options. 

1747 call.extend(self._persistent_git_options) 

1748 

1749 # Add the git options, then reset to empty to avoid side effects. 

1750 call.extend(self._git_options) 

1751 self._git_options = () 

1752 

1753 call.append(dashify(method)) 

1754 call.extend(args_list) 

1755 

1756 return self.execute(call, **exec_kwargs) 

1757 

1758 def _parse_object_header(self, header_line: str) -> Tuple[str, str, int]: 

1759 """ 

1760 :param header_line: 

1761 A line of the form:: 

1762 

1763 <hex_sha> type_string size_as_int 

1764 

1765 :return: 

1766 (hex_sha, type_string, size_as_int) 

1767 

1768 :raise ValueError: 

1769 If the header contains indication for an error due to incorrect input sha. 

1770 """ 

1771 tokens = header_line.split() 

1772 if len(tokens) != 3: 

1773 if not tokens: 

1774 err_msg = ( 

1775 f"SHA is empty, possible dubious ownership in the repository " 

1776 f"""at {self._working_dir}.\n If this is unintended run:\n\n """ 

1777 f""" "git config --global --add safe.directory {self._working_dir}" """ 

1778 ) 

1779 raise ValueError(err_msg) 

1780 else: 

1781 raise ValueError("SHA %s could not be resolved, git returned: %r" % (tokens[0], header_line.strip())) 

1782 # END handle actual return value 

1783 # END error handling 

1784 

1785 if len(tokens[0]) != 40: 

1786 raise ValueError("Failed to parse header: %r" % header_line) 

1787 return (tokens[0], tokens[1], int(tokens[2])) 

1788 

1789 def _prepare_ref(self, ref: AnyStr) -> bytes: 

1790 # Required for command to separate refs on stdin, as bytes. 

1791 if isinstance(ref, bytes): 

1792 # Assume 40 bytes hexsha - bin-to-ascii for some reason returns bytes, not text. 

1793 refstr: str = ref.decode("ascii") 

1794 elif not isinstance(ref, str): 

1795 refstr = str(ref) # Could be ref-object. 

1796 else: 

1797 refstr = ref 

1798 

1799 if not refstr.endswith("\n"): 

1800 refstr += "\n" 

1801 return refstr.encode(defenc) 

1802 

1803 def _get_persistent_cmd(self, attr_name: str, cmd_name: str, *args: Any, **kwargs: Any) -> "Git.AutoInterrupt": 

1804 cur_val = getattr(self, attr_name) 

1805 if cur_val is not None: 

1806 return cur_val 

1807 

1808 options = {"istream": PIPE, "as_process": True} 

1809 options.update(kwargs) 

1810 

1811 cmd = self._call_process(cmd_name, *args, **options) 

1812 setattr(self, attr_name, cmd) 

1813 cmd = cast("Git.AutoInterrupt", cmd) 

1814 return cmd 

1815 

1816 def __get_object_header(self, cmd: "Git.AutoInterrupt", ref: AnyStr) -> Tuple[str, str, int]: 

1817 if cmd.stdin and cmd.stdout: 

1818 cmd.stdin.write(self._prepare_ref(ref)) 

1819 cmd.stdin.flush() 

1820 return self._parse_object_header(cmd.stdout.readline()) 

1821 else: 

1822 raise ValueError("cmd stdin was empty") 

1823 

1824 def get_object_header(self, ref: str) -> Tuple[str, str, int]: 

1825 """Use this method to quickly examine the type and size of the object behind the 

1826 given ref. 

1827 

1828 :note: 

1829 The method will only suffer from the costs of command invocation once and 

1830 reuses the command in subsequent calls. 

1831 

1832 :return: 

1833 (hexsha, type_string, size_as_int) 

1834 """ 

1835 cmd = self._get_persistent_cmd("cat_file_header", "cat_file", batch_check=True) 

1836 return self.__get_object_header(cmd, ref) 

1837 

1838 def get_object_data(self, ref: str) -> Tuple[str, str, int, bytes]: 

1839 """Similar to :meth:`get_object_header`, but returns object data as well. 

1840 

1841 :return: 

1842 (hexsha, type_string, size_as_int, data_string) 

1843 

1844 :note: 

1845 Not threadsafe. 

1846 """ 

1847 hexsha, typename, size, stream = self.stream_object_data(ref) 

1848 data = stream.read(size) 

1849 del stream 

1850 return (hexsha, typename, size, data) 

1851 

1852 def stream_object_data(self, ref: str) -> Tuple[str, str, int, "Git.CatFileContentStream"]: 

1853 """Similar to :meth:`get_object_data`, but returns the data as a stream. 

1854 

1855 :return: 

1856 (hexsha, type_string, size_as_int, stream) 

1857 

1858 :note: 

1859 This method is not threadsafe. You need one independent :class:`Git` 

1860 instance per thread to be safe! 

1861 """ 

1862 cmd = self._get_persistent_cmd("cat_file_all", "cat_file", batch=True) 

1863 hexsha, typename, size = self.__get_object_header(cmd, ref) 

1864 cmd_stdout = cmd.stdout if cmd.stdout is not None else io.BytesIO() 

1865 return (hexsha, typename, size, self.CatFileContentStream(size, cmd_stdout)) 

1866 

1867 def clear_cache(self) -> "Git": 

1868 """Clear all kinds of internal caches to release resources. 

1869 

1870 Currently persistent commands will be interrupted. 

1871 

1872 :return: 

1873 self 

1874 """ 

1875 for cmd in (self.cat_file_all, self.cat_file_header): 

1876 if cmd: 

1877 cmd.__del__() 

1878 

1879 self.cat_file_all = None 

1880 self.cat_file_header = None 

1881 return self