Coverage for /pythoncovmergedfiles/medio/medio/usr/local/lib/python3.11/site-packages/git/cmd.py: 59%

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

699 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: Union["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 stderr_b = force_bytes(data=stderr, encoding="utf-8") or b"" 

399 status: Union[int, None] 

400 if self.proc is not None: 

401 status = self.proc.wait() 

402 p_stderr = self.proc.stderr 

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

404 status = self.status 

405 p_stderr = None 

406 

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

408 if stream: 

409 try: 

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

411 except (OSError, ValueError): 

412 return stderr_b or b"" 

413 else: 

414 return stderr_b or b"" 

415 

416 # END status handling 

417 

418 if status != 0: 

419 errstr = read_all_from_possibly_closed_stream(p_stderr) 

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

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

422 return status 

423 

424 

425_AutoInterrupt.__name__ = "AutoInterrupt" 

426_AutoInterrupt.__qualname__ = "Git.AutoInterrupt" 

427 

428 

429class _CatFileContentStream: 

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

431 an object. 

432 

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

434 once our sized content region is empty. 

435 

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

437 ensure the underlying stream continues to work. 

438 """ 

439 

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

441 

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

443 self._stream = stream 

444 self._size = size 

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

446 

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

448 # newline right away. 

449 if size == 0: 

450 stream.read(1) 

451 # END handle empty streams 

452 

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

454 bytes_left = self._size - self._nbr 

455 if bytes_left == 0: 

456 return b"" 

457 if size > -1: 

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

459 size = min(bytes_left, size) 

460 else: 

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

462 size = bytes_left 

463 # END check early depletion 

464 data = self._stream.read(size) 

465 self._nbr += len(data) 

466 

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

468 # others. 

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

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

471 # END finish reading 

472 return data 

473 

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

475 if self._nbr == self._size: 

476 return b"" 

477 

478 # Clamp size to lowest allowed value. 

479 bytes_left = self._size - self._nbr 

480 if size > -1: 

481 size = min(bytes_left, size) 

482 else: 

483 size = bytes_left 

484 # END handle size 

485 

486 data = self._stream.readline(size) 

487 self._nbr += len(data) 

488 

489 # Handle final byte. 

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

491 self._stream.read(1) 

492 # END finish reading 

493 

494 return data 

495 

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

497 if self._nbr == self._size: 

498 return [] 

499 

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

501 out = [] 

502 nbr = 0 

503 while True: 

504 line = self.readline() 

505 if not line: 

506 break 

507 out.append(line) 

508 if size > -1: 

509 nbr += len(line) 

510 if nbr > size: 

511 break 

512 # END handle size constraint 

513 # END readline loop 

514 return out 

515 

516 # skipcq: PYL-E0301 

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

518 return self 

519 

520 def __next__(self) -> bytes: 

521 line = self.readline() 

522 if not line: 

523 raise StopIteration 

524 

525 return line 

526 

527 next = __next__ 

528 

529 def __del__(self) -> None: 

530 bytes_left = self._size - self._nbr 

531 if bytes_left: 

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

533 # This includes any terminating newline. 

534 self._stream.read(bytes_left + 1) 

535 # END handle incomplete read 

536 

537 

538_CatFileContentStream.__name__ = "CatFileContentStream" 

539_CatFileContentStream.__qualname__ = "Git.CatFileContentStream" 

540 

541 

542_USE_SHELL_DEFAULT_MESSAGE = ( 

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

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

545) 

546 

547_USE_SHELL_DANGER_MESSAGE = ( 

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

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

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

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

552) 

553 

554 

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

556 warnings.warn( 

557 _USE_SHELL_DANGER_MESSAGE if extra_danger else _USE_SHELL_DEFAULT_MESSAGE, 

558 DeprecationWarning, 

559 stacklevel=3, 

560 ) 

561 

562 

563class _GitMeta(type): 

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

565 

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

567 """ 

568 

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

570 if name == "USE_SHELL": 

571 _warn_use_shell(extra_danger=False) 

572 return super().__getattribute__(name) 

573 

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

575 if name == "USE_SHELL": 

576 _warn_use_shell(extra_danger=value) 

577 super().__setattr__(name, value) 

578 

579 if not TYPE_CHECKING: 

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

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

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

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

584 __getattribute__ = __getattribute 

585 __setattr__ = __setattr 

586 

587 

588GitMeta = _GitMeta 

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

590 

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

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

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

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

595 

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

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

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

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

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

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

602 

603:note: 

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

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

606 

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

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

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

610 explicitly. 

611""" 

612 

613 

614class Git(metaclass=_GitMeta): 

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

616 

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

618 

619 g = Git( git_dir ) 

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

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

622 

623 Debugging: 

624 

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

626 of the command to stdout. 

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

628 """ 

629 

630 __slots__ = ( 

631 "_working_dir", 

632 "cat_file_all", 

633 "cat_file_header", 

634 "_version_info", 

635 "_version_info_token", 

636 "_git_options", 

637 "_persistent_git_options", 

638 "_environment", 

639 ) 

640 

641 _excluded_ = ( 

642 "cat_file_all", 

643 "cat_file_header", 

644 "_version_info", 

645 "_version_info_token", 

646 ) 

647 

648 # Match Git's leading transport selector, including an empty helper name. 

649 # Git also selects the command-executing ext helper for an ext:// URL. 

650 re_unsafe_protocol = re.compile(r"([A-Za-z0-9][A-Za-z0-9+.-]*|)::|ext://") 

651 

652 unsafe_git_ls_remote_options = [ 

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

654 "--upload-pack", 

655 "--exec", 

656 ] 

657 

658 unsafe_git_pathspec_from_file_options = [ 

659 # Reads pathspecs from a caller-controlled file. Some commands include an 

660 # unmatched pathspec in their error output, which can disclose the file. 

661 "--pathspec-from-file", 

662 ] 

663 

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

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

666 

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

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

669 

670 # CONFIGURATION 

671 

672 git_exec_name = "git" 

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

674 

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

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

677 

678 USE_SHELL: bool = False 

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

680 

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

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

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

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

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

686 

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

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

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

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

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

692 contain special shell syntax, leading to inadvertent malfunctions. 

693 

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

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

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

697 

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

699 

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

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

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

703 

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

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

706 

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

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

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

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

711 

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

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

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

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

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

717 

718 Further reading: 

719 

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

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

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

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

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

725 """ 

726 

727 _git_exec_env_var = "GIT_PYTHON_GIT_EXECUTABLE" 

728 _refresh_env_var = "GIT_PYTHON_REFRESH" 

729 

730 GIT_PYTHON_GIT_EXECUTABLE = None 

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

732 executable search path. 

733 

734 :note: 

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

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

737 """ 

738 

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

740 

741 @classmethod 

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

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

744 

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

746 

747 :param path: 

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

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

750 

751 :note: 

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

753 method and may also update other state accordingly. 

754 

755 :note: 

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

757 to be used for git: 

758 

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

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

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

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

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

764 

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

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

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

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

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

770 

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

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

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

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

775 :envvar:`GIT_PYTHON_GIT_EXECUTABLE` environment variable is not 

776 consulted. 

777 

778 :note: 

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

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

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

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

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

784 performed. 

785 """ 

786 # Discern which path to refresh with. 

787 if path is not None: 

788 new_git = os.path.expanduser(path) 

789 new_git = os.path.abspath(new_git) 

790 else: 

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

792 

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

794 old_git = cls.GIT_PYTHON_GIT_EXECUTABLE 

795 old_refresh_token = cls._refresh_token 

796 cls.GIT_PYTHON_GIT_EXECUTABLE = new_git 

797 cls._refresh_token = object() 

798 

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

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

801 # executed for whatever reason. 

802 has_git = False 

803 try: 

804 cls().version() 

805 has_git = True 

806 except (GitCommandNotFound, PermissionError): 

807 pass 

808 

809 # Warn or raise exception if test failed. 

810 if not has_git: 

811 err = ( 

812 dedent( 

813 """\ 

814 Bad git executable. 

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

816 - be included in your $PATH 

817 - be set via $%s 

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

819 """ 

820 ) 

821 % cls._git_exec_env_var 

822 ) 

823 

824 # Revert to whatever the old_git was. 

825 cls.GIT_PYTHON_GIT_EXECUTABLE = old_git 

826 cls._refresh_token = old_refresh_token 

827 

828 if old_git is None: 

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

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

831 

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

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

834 # following values: 

835 # 

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

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

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

839 

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

841 

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

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

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

845 

846 if mode in quiet: 

847 pass 

848 elif mode in warn or mode in error: 

849 err = dedent( 

850 """\ 

851 %s 

852 All git commands will error until this is rectified. 

853 

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

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

856 - %s: for no message or exception 

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

858 - %s: for a raised exception 

859 

860 Example: 

861 export %s=%s 

862 """ 

863 ) % ( 

864 err, 

865 cls._refresh_env_var, 

866 "|".join(quiet), 

867 "|".join(warn), 

868 "|".join(error), 

869 cls._refresh_env_var, 

870 quiet[0], 

871 ) 

872 

873 if mode in warn: 

874 _logger.critical(err) 

875 else: 

876 raise ImportError(err) 

877 else: 

878 err = dedent( 

879 """\ 

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

881 

882 Use only the following values: 

883 - %s: for no message or exception 

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

885 - %s: for a raised exception 

886 """ 

887 ) % ( 

888 cls._refresh_env_var, 

889 "|".join(quiet), 

890 "|".join(warn), 

891 "|".join(error), 

892 ) 

893 raise ImportError(err) 

894 

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

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

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

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

899 cls.GIT_PYTHON_GIT_EXECUTABLE = cls.git_exec_name 

900 else: 

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

902 # None) we raise an exception. 

903 raise GitCommandNotFound(new_git, err) 

904 

905 return has_git 

906 

907 @classmethod 

908 def is_cygwin(cls) -> bool: 

909 return is_cygwin_git(cls.GIT_PYTHON_GIT_EXECUTABLE) 

910 

911 @overload 

912 @classmethod 

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

914 

915 @overload 

916 @classmethod 

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

918 

919 @classmethod 

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

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

922 

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

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

925 just to be sure. 

926 

927 :param expand_vars: 

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

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

930 """ 

931 if is_cygwin is None: 

932 is_cygwin = cls.is_cygwin() 

933 

934 if is_cygwin: 

935 url = cygpath(url, expand_vars=expand_vars) 

936 else: 

937 if expand_vars: 

938 url = os.path.expandvars(url) 

939 if url.startswith("~"): 

940 url = os.path.expanduser(url) 

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

942 return url 

943 

944 @classmethod 

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

946 """Check for unsafe protocols. 

947 

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

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

950 can be used to invoke any arbitrary command. Git also selects that helper 

951 for ``ext://`` URLs and interprets the URL as a command path. 

952 

953 See: 

954 

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

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

957 """ 

958 match = cls.re_unsafe_protocol.match(url) 

959 if match: 

960 protocol = match.group(0) 

961 raise UnsafeProtocolError( 

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

963 ) 

964 

965 def _check_unsafe_protocols_in_args(self, args: Sequence[Any], kwargs: Mapping[str, Any]) -> None: 

966 """Check positional operands and standalone values in rendered command options. 

967 

968 A short flag's split value can become the repository operand before ``--``. 

969 """ 

970 for arg in self._unpack_args(args) + self.transform_kwargs(**kwargs): 

971 self.check_unsafe_protocols(arg) 

972 

973 @classmethod 

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

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

976 

977 Examples: 

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

979 ``"upload_pack"`` -> ``"upload-pack"`` 

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

981 """ 

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

983 option_tokens = option_name.split(None, 1) 

984 if not option_tokens: 

985 return "" 

986 return dashify(option_tokens[0]) 

987 

988 @classmethod 

989 def check_unsafe_options( 

990 cls, options: List[str], unsafe_options: List[str], clusterable_short_options: str = "46flnqsv" 

991 ) -> None: 

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

993 

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

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

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

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

998 

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

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

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

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

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

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

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

1006 

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

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

1009 """ 

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

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

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

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

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

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

1016 # only. 

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

1018 unsafe_short_options = { 

1019 canonical: option 

1020 for canonical, option in canonical_unsafe_options.items() 

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

1022 } 

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

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

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

1026 clusterable_short_options_set = frozenset(clusterable_short_options) 

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

1028 for option in options: 

1029 candidate = cls._canonicalize_option_name(option) 

1030 if not candidate: 

1031 continue 

1032 unsafe_option = canonical_unsafe_options.get(candidate) 

1033 if unsafe_option is not None: 

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

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

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

1037 for option_char in option_token[1:]: 

1038 unsafe_option = unsafe_short_options.get(option_char) 

1039 if unsafe_option is not None: 

1040 raise UnsafeOptionError( 

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

1042 ) 

1043 if option_char not in clusterable_short_options_set: 

1044 break 

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

1046 continue 

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

1048 if canonical.startswith(candidate): 

1049 raise UnsafeOptionError( 

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

1051 ) 

1052 

1053 @classmethod 

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

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

1056 options = [ 

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

1058 ] 

1059 if kwargs: 

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

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

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

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

1064 key = str(key) 

1065 if len(key) != 1: 

1066 options.append(f"--{dashify(key)}") 

1067 elif split_single_char_options: 

1068 options.append(f"-{key}") 

1069 options.extend( 

1070 str(value) 

1071 for value in values 

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

1073 ) 

1074 else: 

1075 options.extend( 

1076 f"-{key}" if value is True else f"-{key}{value}" 

1077 for value in values 

1078 if value is True or (value is not False and value is not None) 

1079 ) 

1080 return options 

1081 

1082 AutoInterrupt: TypeAlias = _AutoInterrupt 

1083 

1084 CatFileContentStream: TypeAlias = _CatFileContentStream 

1085 

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

1087 """Initialize this instance with: 

1088 

1089 :param working_dir: 

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

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

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

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

1094 """ 

1095 super().__init__() 

1096 self._working_dir = expand_path(working_dir) 

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

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

1099 

1100 # Extra environment variables to pass to git commands 

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

1102 

1103 # Cached version slots 

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

1105 self._version_info_token: object = None 

1106 

1107 # Cached command slots 

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

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

1110 

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

1112 if name == "USE_SHELL": 

1113 _warn_use_shell(extra_danger=False) 

1114 return super().__getattribute__(name) 

1115 

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

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

1118 

1119 :return: 

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

1121 arguments. 

1122 """ 

1123 if name.startswith("_"): 

1124 return super().__getattribute__(name) 

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

1126 

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

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

1129 subcommand calls. 

1130 

1131 :param kwargs: 

1132 A dict of keyword arguments. 

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

1134 to the git command rather than the subcommand. 

1135 """ 

1136 

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

1138 

1139 def ls_remote( 

1140 self, 

1141 *args: Any, 

1142 allow_unsafe_options: bool = False, 

1143 allow_unsafe_protocols: bool = False, 

1144 **kwargs: Any, 

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

1146 """List references in a remote repository. 

1147 

1148 :param allow_unsafe_options: 

1149 Allow unsafe options, like ``--upload-pack`` or ``--exec``. 

1150 

1151 :param allow_unsafe_protocols: 

1152 Allow unsafe protocols to be used, like ``ext``. Positional arguments 

1153 and split short-option values are checked. 

1154 """ 

1155 if not allow_unsafe_options: 

1156 candidate_options = self._option_candidates(args, kwargs) 

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

1158 if not allow_unsafe_protocols: 

1159 self._check_unsafe_protocols_in_args(args, kwargs) 

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

1161 

1162 @property 

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

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

1165 return self._working_dir 

1166 

1167 @property 

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

1169 """ 

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

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

1172 are used. 

1173 

1174 This value is generated on demand and is cached. 

1175 """ 

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

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

1178 

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

1180 if self._version_info_token is refresh_token: 

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

1182 return self._version_info 

1183 

1184 # Run "git version" and parse it. 

1185 process_version = self._call_process("version") 

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

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

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

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

1190 

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

1192 self._version_info_token = refresh_token 

1193 return self._version_info 

1194 

1195 @overload 

1196 def execute( 

1197 self, 

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

1199 istream: Union[None, int, BinaryIO] = None, 

1200 *, 

1201 as_process: Literal[True], 

1202 **subprocess_kwargs: Any, 

1203 ) -> "AutoInterrupt": ... 

1204 

1205 @overload 

1206 def execute( 

1207 self, 

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

1209 istream: Union[None, int, BinaryIO] = None, 

1210 *, 

1211 as_process: Literal[False] = False, 

1212 with_extended_output: Literal[False] = False, 

1213 stdout_as_string: Literal[True] = True, 

1214 with_stdout: Literal[True] = True, 

1215 **subprocess_kwargs: Any, 

1216 ) -> str: ... 

1217 

1218 @overload 

1219 def execute( 

1220 self, 

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

1222 istream: Union[None, int, BinaryIO] = None, 

1223 *, 

1224 as_process: Literal[False] = False, 

1225 with_extended_output: Literal[False] = False, 

1226 stdout_as_string: Literal[False], 

1227 universal_newlines: Literal[False] = False, 

1228 with_stdout: Literal[True] = True, 

1229 **subprocess_kwargs: Any, 

1230 ) -> bytes: ... 

1231 

1232 @overload 

1233 def execute( 

1234 self, 

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

1236 istream: Union[None, int, BinaryIO] = None, 

1237 *, 

1238 as_process: Literal[False] = False, 

1239 with_extended_output: Literal[True], 

1240 stdout_as_string: Literal[True] = True, 

1241 with_stdout: Literal[True] = True, 

1242 **subprocess_kwargs: Any, 

1243 ) -> Tuple[int, str, str]: ... 

1244 

1245 @overload 

1246 def execute( 

1247 self, 

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

1249 istream: Union[None, int, BinaryIO] = None, 

1250 *, 

1251 as_process: Literal[False] = False, 

1252 with_extended_output: Literal[True], 

1253 stdout_as_string: Literal[False], 

1254 universal_newlines: Literal[False] = False, 

1255 with_stdout: Literal[True] = True, 

1256 **subprocess_kwargs: Any, 

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

1258 

1259 @overload 

1260 def execute( 

1261 self, 

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

1263 istream: Union[None, int, BinaryIO] = None, 

1264 *, 

1265 as_process: Literal[False] = False, 

1266 with_extended_output: Literal[True], 

1267 **subprocess_kwargs: Any, 

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

1269 

1270 @overload 

1271 def execute( 

1272 self, 

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

1274 istream: Union[None, int, BinaryIO] = None, 

1275 *, 

1276 as_process: Literal[False] = False, 

1277 with_extended_output: Literal[False] = False, 

1278 **subprocess_kwargs: Any, 

1279 ) -> Union[str, bytes, None]: ... 

1280 

1281 @overload 

1282 def execute( 

1283 self, 

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

1285 istream: Union[None, int, BinaryIO] = None, 

1286 with_extended_output: bool = False, 

1287 with_exceptions: bool = True, 

1288 as_process: bool = False, 

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

1290 stdout_as_string: bool = True, 

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

1292 with_stdout: bool = True, 

1293 universal_newlines: bool = False, 

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

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

1296 max_chunk_size: int = io.DEFAULT_BUFFER_SIZE, 

1297 strip_newline_in_stdout: bool = True, 

1298 **subprocess_kwargs: Any, 

1299 ) -> Union[None, str, bytes, Tuple[int, Union[str, bytes, None], str], AutoInterrupt]: ... 

1300 

1301 def execute( 

1302 self, 

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

1304 istream: Union[None, int, BinaryIO] = None, 

1305 with_extended_output: bool = False, 

1306 with_exceptions: bool = True, 

1307 as_process: bool = False, 

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

1309 stdout_as_string: bool = True, 

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

1311 with_stdout: bool = True, 

1312 universal_newlines: bool = False, 

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

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

1315 max_chunk_size: int = io.DEFAULT_BUFFER_SIZE, 

1316 strip_newline_in_stdout: bool = True, 

1317 **subprocess_kwargs: Any, 

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

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

1320 information (stdout). 

1321 

1322 :param command: 

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

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

1325 

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

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

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

1329 work but are not portable. 

1330 

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

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

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

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

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

1336 

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

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

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

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

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

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

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

1344 is fully sanitized. 

1345 

1346 :param istream: 

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

1348 

1349 :param with_extended_output: 

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

1351 

1352 :param with_exceptions: 

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

1354 

1355 :param as_process: 

1356 Whether to return the created process instance directly from which 

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

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

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

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

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

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

1363 

1364 :param output_stream: 

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

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

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

1368 

1369 :param stdout_as_string: 

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

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

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

1373 

1374 :param kill_after_timeout: 

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

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

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

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

1379 carefully considered, due to the following limitations: 

1380 

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

1382 2. Enumerating child processes requires ``pgrep -P``, or a ``ps`` command 

1383 supporting the POSIX ``-A`` and ``-o`` options if ``pgrep`` is not 

1384 installed. Effectiveness may vary on systems without these commands. 

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

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

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

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

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

1390 changes until the lock is manually removed. 

1391 

1392 :param with_stdout: 

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

1394 

1395 :param universal_newlines: 

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

1397 line endings. 

1398 

1399 :param shell: 

1400 Whether to invoke commands through a shell 

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

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

1403 

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

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

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

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

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

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

1410 issues. 

1411 

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

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

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

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

1416 

1417 :param env: 

1418 A dictionary of environment variables to be passed to 

1419 :class:`subprocess.Popen`. 

1420 

1421 :param max_chunk_size: 

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

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

1424 positive then the default value is used. 

1425 

1426 :param strip_newline_in_stdout: 

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

1428 

1429 :param subprocess_kwargs: 

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

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

1432 specify may not be the same ones. 

1433 

1434 :return: 

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

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

1437 if `extended_output` is ``True`` 

1438 

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

1440 

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

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

1443 if `extended_output` is ``True`` 

1444 

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

1446 output regardless of system language. 

1447 

1448 :raise git.exc.GitCommandError: 

1449 

1450 :note: 

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

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

1453 """ 

1454 # Remove password for the command if present. 

1455 redacted_command = remove_password_if_present(command) 

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

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

1458 

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

1460 try: 

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

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

1463 cwd = None 

1464 except FileNotFoundError: 

1465 cwd = None 

1466 

1467 # Start the process. 

1468 inline_env = env 

1469 env = os.environ.copy() 

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

1471 # code may expect. 

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

1473 # just to be sure. 

1474 env["LANGUAGE"] = "C" 

1475 env["LC_ALL"] = "C" 

1476 env.update(self._environment) 

1477 if inline_env is not None: 

1478 env.update(inline_env) 

1479 

1480 if sys.platform == "win32": 

1481 if kill_after_timeout is not None: 

1482 raise GitCommandError( 

1483 redacted_command, 

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

1485 ) 

1486 cmd_not_found_exception = OSError 

1487 else: 

1488 cmd_not_found_exception = FileNotFoundError 

1489 # END handle 

1490 

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

1492 if shell is None: 

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

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

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

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

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

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

1499 _logger.debug( 

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

1501 redacted_command, 

1502 cwd, 

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

1504 shell, 

1505 universal_newlines, 

1506 ) 

1507 try: 

1508 proc = safer_popen( 

1509 command, 

1510 env=env, 

1511 cwd=cwd, 

1512 bufsize=-1, 

1513 stdin=(istream or DEVNULL), 

1514 stderr=PIPE, 

1515 stdout=stdout_sink, 

1516 shell=shell, 

1517 universal_newlines=universal_newlines, 

1518 encoding=defenc if universal_newlines else None, 

1519 **subprocess_kwargs, 

1520 ) 

1521 except cmd_not_found_exception as err: 

1522 raise GitCommandNotFound(redacted_command, err) from err 

1523 else: 

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

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

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

1527 

1528 if as_process: 

1529 return self.AutoInterrupt(proc, command) 

1530 

1531 watchdog: Optional[threading.Timer] = None 

1532 kill_check: Optional[threading.Event] = None 

1533 timeout_error: Optional[Callable[[], Union[str, bytes]]] = None 

1534 

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

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

1537 timeout = kill_after_timeout 

1538 

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

1540 """Callback to kill a process. 

1541 

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

1543 """ 

1544 child_pids = [] 

1545 try: 

1546 p = Popen(["pgrep", "-P", str(pid)], stdout=PIPE) 

1547 except FileNotFoundError: 

1548 # POSIX ps does not support selecting by parent PID. 

1549 with Popen(["ps", "-A", "-o", "pid=", "-o", "ppid="], stdout=PIPE) as p: 

1550 if p.stdout is not None: 

1551 for line in p.stdout: 

1552 fields = line.split() 

1553 if len(fields) == 2 and all(field.isdigit() for field in fields): 

1554 if int(fields[1]) == pid: 

1555 child_pids.append(int(fields[0])) 

1556 else: 

1557 with p: 

1558 if p.stdout is not None: 

1559 for line in p.stdout: 

1560 if line.strip().isdigit(): 

1561 child_pids.append(int(line)) 

1562 try: 

1563 os.kill(pid, signal.SIGKILL) 

1564 for child_pid in child_pids: 

1565 try: 

1566 os.kill(child_pid, signal.SIGKILL) 

1567 except OSError: 

1568 pass 

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

1570 assert kill_check is not None 

1571 kill_check.set() 

1572 except OSError: 

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

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

1575 pass 

1576 return 

1577 

1578 def make_timeout_error() -> Union[str, bytes]: 

1579 err = f'Timeout: the command "{" ".join(redacted_command)}" did not complete in {timeout:g} secs.' 

1580 return err if universal_newlines else err.encode(defenc) 

1581 

1582 def communicate() -> Tuple[Union[str, bytes, None], Union[str, bytes, None]]: 

1583 assert watchdog is not None 

1584 assert kill_check is not None 

1585 watchdog.start() 

1586 out, err = proc.communicate() 

1587 watchdog.cancel() 

1588 if kill_check.is_set(): 

1589 err = make_timeout_error() 

1590 return out, err 

1591 

1592 # END helpers 

1593 

1594 kill_check = threading.Event() 

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

1596 timeout_error = make_timeout_error 

1597 else: 

1598 communicate = proc.communicate 

1599 

1600 # Wait for the process to return. 

1601 status = 0 

1602 stdout_value: Union[str, bytes, None] = b"" 

1603 stderr_value: Union[str, bytes, None] = b"" 

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

1605 try: 

1606 if output_stream is None: 

1607 stdout_value, stderr_value = communicate() 

1608 # Strip trailing "\n". 

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

1610 stdout_value = stdout_value[:-1] 

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

1612 stderr_value = stderr_value[:-1] 

1613 

1614 status = proc.returncode 

1615 else: 

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

1617 if watchdog is not None: 

1618 watchdog.start() 

1619 try: 

1620 if proc.stdout is not None: 

1621 stream_copy(proc.stdout, output_stream, max_chunk_size) 

1622 stdout_value = proc.stdout.read() 

1623 if proc.stderr is not None: 

1624 stderr_value = proc.stderr.read() 

1625 status = proc.wait() 

1626 finally: 

1627 if watchdog is not None: 

1628 watchdog.cancel() 

1629 # Strip trailing "\n". 

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

1631 stderr_value = stderr_value[:-1] 

1632 if kill_check is not None and kill_check.is_set(): 

1633 assert timeout_error is not None 

1634 stderr_value = timeout_error() 

1635 # END stdout handling 

1636 finally: 

1637 if proc.stdout is not None: 

1638 proc.stdout.close() 

1639 if proc.stderr is not None: 

1640 proc.stderr.close() 

1641 

1642 if self.GIT_PYTHON_TRACE == "full": 

1643 cmdstr = " ".join(redacted_command) 

1644 

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

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

1647 

1648 # END as_text 

1649 

1650 if stderr_value: 

1651 _logger.info( 

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

1653 cmdstr, 

1654 status, 

1655 as_text(stdout_value), 

1656 safe_decode(stderr_value), 

1657 ) 

1658 elif stdout_value: 

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

1660 else: 

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

1662 # END handle debug printing 

1663 

1664 if with_exceptions and status != 0: 

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

1666 

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

1668 stdout_value = safe_decode(stdout_value) 

1669 

1670 # stderr is always captured through PIPE. 

1671 assert stderr_value is not None 

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

1673 if with_extended_output: 

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

1675 else: 

1676 return stdout_value 

1677 

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

1679 return self._environment 

1680 

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

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

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

1684 changes. 

1685 

1686 Examples:: 

1687 

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

1689 self.update_environment(**old_env) 

1690 

1691 :param kwargs: 

1692 Environment variables to use for git processes. 

1693 

1694 :return: 

1695 Dict that maps environment variables to their old values 

1696 """ 

1697 old_env = {} 

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

1699 # Set value if it is None. 

1700 if value is not None: 

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

1702 self._environment[key] = value 

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

1704 elif key in self._environment: 

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

1706 del self._environment[key] 

1707 return old_env 

1708 

1709 @contextlib.contextmanager 

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

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

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

1713 

1714 Examples:: 

1715 

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

1717 repo.remotes.origin.fetch() 

1718 

1719 :param kwargs: 

1720 See :meth:`update_environment`. 

1721 """ 

1722 old_env = self.update_environment(**kwargs) 

1723 try: 

1724 yield 

1725 finally: 

1726 self.update_environment(**old_env) 

1727 

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

1729 if len(name) == 1: 

1730 if value is True: 

1731 return ["-%s" % name] 

1732 elif value not in (False, None): 

1733 if split_single_char_options: 

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

1735 else: 

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

1737 else: 

1738 if value is True: 

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

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

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

1742 return [] 

1743 

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

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

1746 args = [] 

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

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

1749 for value in v: 

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

1751 else: 

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

1753 return args 

1754 

1755 @classmethod 

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

1757 outlist = [] 

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

1759 for arg in arg_list: 

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

1761 else: 

1762 outlist.append(str(arg_list)) 

1763 

1764 return outlist 

1765 

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

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

1768 

1769 :param kwargs: 

1770 A dict of keyword arguments. 

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

1772 to the git command rather than the subcommand. 

1773 

1774 Examples:: 

1775 

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

1777 """ 

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

1779 return self 

1780 

1781 @overload 

1782 def _call_process( 

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

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

1785 

1786 @overload 

1787 def _call_process( 

1788 self, 

1789 method: str, 

1790 istream: int, 

1791 as_process: Literal[True], 

1792 *args: Any, 

1793 **kwargs: Any, 

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

1795 

1796 @overload 

1797 def _call_process( 

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

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

1800 

1801 def _call_process( 

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

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

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

1805 as a string. 

1806 

1807 :param method: 

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

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

1810 

1811 :param args: 

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

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

1814 realized as non-existent. 

1815 

1816 Positional arguments may intentionally contain command options. Higher-level 

1817 APIs must separate their operands with ``--`` where the Git command supports 

1818 it, or reject option-shaped operands where Git reparses them internally (for 

1819 example, ``pull`` and ``remote update``). Shell quoting cannot prevent Git 

1820 from interpreting a leading-dash argument as an option. 

1821 

1822 :param kwargs: 

1823 Contains key-values for the following: 

1824 

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

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

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

1828 ``*args``. 

1829 

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

1831 

1832 Examples:: 

1833 

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

1835 

1836 turns into:: 

1837 

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

1839 

1840 :return: 

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

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

1843 return :class:`str`. 

1844 """ 

1845 # Handle optional arguments prior to calling transform_kwargs. 

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

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

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

1849 

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

1851 

1852 # Prepare the argument list. 

1853 

1854 opt_args = self.transform_kwargs(**opts_kwargs) 

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

1856 

1857 if insert_after_this_arg is None: 

1858 args_list = opt_args + ext_args 

1859 else: 

1860 try: 

1861 index = ext_args.index(insert_after_this_arg) 

1862 except ValueError as err: 

1863 raise ValueError( 

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

1865 % (insert_after_this_arg, str(ext_args)) 

1866 ) from err 

1867 # END handle error 

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

1869 # END handle opts_kwargs 

1870 

1871 call = [self.GIT_PYTHON_GIT_EXECUTABLE] 

1872 

1873 # Add persistent git options. 

1874 call.extend(self._persistent_git_options) 

1875 

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

1877 call.extend(self._git_options) 

1878 self._git_options = () 

1879 

1880 call.append(dashify(method)) 

1881 call.extend(args_list) 

1882 

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

1884 

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

1886 """ 

1887 :param header_line: 

1888 A line of the form:: 

1889 

1890 <hex_sha> type_string size_as_int 

1891 

1892 :return: 

1893 (hex_sha, type_string, size_as_int) 

1894 

1895 :raise ValueError: 

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

1897 """ 

1898 tokens = header_line.split() 

1899 if len(tokens) != 3: 

1900 if not tokens: 

1901 err_msg = ( 

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

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

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

1905 ) 

1906 raise ValueError(err_msg) 

1907 else: 

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

1909 # END handle actual return value 

1910 # END error handling 

1911 

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

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

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

1915 

1916 def _prepare_ref(self, ref: object) -> bytes: 

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

1918 if isinstance(ref, bytes): 

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

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

1921 elif not isinstance(ref, str): 

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

1923 else: 

1924 refstr = ref 

1925 

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

1927 refstr += "\n" 

1928 return refstr.encode(defenc) 

1929 

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

1931 cur_val = getattr(self, attr_name) 

1932 if cur_val is not None: 

1933 return cur_val 

1934 

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

1936 options.update(kwargs) 

1937 

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

1939 setattr(self, attr_name, cmd) 

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

1941 return cmd 

1942 

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

1944 if cmd.stdin and cmd.stdout: 

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

1946 cmd.stdin.flush() 

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

1948 else: 

1949 raise ValueError("cmd stdin was empty") 

1950 

1951 def get_object_header(self, ref: Union[str, bytes]) -> Tuple[str, str, int]: 

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

1953 given ref. 

1954 

1955 :note: 

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

1957 reuses the command in subsequent calls. 

1958 

1959 :return: 

1960 (hexsha, type_string, size_as_int) 

1961 """ 

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

1963 return self.__get_object_header(cmd, ref) 

1964 

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

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

1967 

1968 :return: 

1969 (hexsha, type_string, size_as_int, data_string) 

1970 

1971 :note: 

1972 Not threadsafe. 

1973 """ 

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

1975 data = stream.read(size) 

1976 del stream 

1977 return (hexsha, typename, size, data) 

1978 

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

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

1981 

1982 :return: 

1983 (hexsha, type_string, size_as_int, stream) 

1984 

1985 :note: 

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

1987 instance per thread to be safe! 

1988 """ 

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

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

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

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

1993 

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

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

1996 

1997 Currently persistent commands will be interrupted. 

1998 

1999 :return: 

2000 self 

2001 """ 

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

2003 if cmd: 

2004 cmd.__del__() 

2005 

2006 self.cat_file_all = None 

2007 self.cat_file_header = None 

2008 return self