gitbolt 0.0.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,1835 @@
1
+ #!/usr/bin/env python3
2
+ # coding=utf-8
3
+
4
+ """
5
+ Git command interfaces with default implementation using subprocess calls.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ import abc
11
+ import sys
12
+ from abc import abstractmethod, ABC
13
+ from collections.abc import Callable
14
+ from contextlib import AbstractContextManager
15
+ from datetime import datetime
16
+ from pathlib import Path
17
+ from subprocess import CompletedProcess, Popen, PIPE
18
+ from types import SimpleNamespace
19
+ from typing import override, Protocol, Unpack, Self, overload, Literal, Any
20
+
21
+ from vt.utils.commons.commons.core_py import is_unset, not_none_not_unset, UNSET, Unset
22
+ from vt.utils.commons.commons.op import RootDirOp
23
+ from vt.utils.errors.error_specs import ERR_INVALID_USAGE
24
+
25
+ from gitbolt import Git, Version, LsTree, GitSubCommand, HasGitUnderneath, Add
26
+ from gitbolt.base import Worktree, HashObject, WritingHashObject
27
+ from gitbolt.exceptions import GitExitingException
28
+ from gitbolt.subprocess.add import AddCLIArgsBuilder, IndividuallyOverridableACAB
29
+ from gitbolt.subprocess.hash_object import (
30
+ HashObjectCLIArgsBuilder,
31
+ IndividuallyOverridableHOCAB,
32
+ )
33
+ from gitbolt.subprocess.hash_object_util import (
34
+ as_hash_list,
35
+ hash_object_stdin_input,
36
+ hashes_from_hash_object_stdout,
37
+ run_in_tmpdir,
38
+ stdin_temp_file_paths,
39
+ stripped_stdout_text,
40
+ )
41
+ from gitbolt.subprocess.ls_tree import (
42
+ LsTreeCLIArgsBuilder,
43
+ IndividuallyOverridableLTCAB,
44
+ )
45
+ from gitbolt.subprocess.runner import GitCommandRunner
46
+ from gitbolt.models import GitOpts, GitLsTreeOpts, GitAddOpts, GitEnvVars
47
+ from gitbolt.subprocess.worktree import WorktreeCLIArgsBuilder
48
+ from gitbolt.utils import merge_git_opts, merge_git_envs
49
+ from gitbolt.subprocess.constants import GIT_CMD, VERSION_CMD, LS_TREE_CMD, ADD_CMD, HASH_OBJECT_CMD, WORKTREE_CMD, WORKTREE_ADD_CMD
50
+ from gitbolt.subprocess.utils.session import _close_session_popen
51
+
52
+
53
+ class GitCommand(Git, ABC):
54
+ """
55
+ Runs git as a command.
56
+ """
57
+
58
+ def __init__(self, runner: GitCommandRunner):
59
+ """
60
+ :param runner: a ``GitCommandRunner`` which eventually runs the cli command in a subprocess.
61
+ """
62
+ self.runner: GitCommandRunner = runner
63
+ self._main_cmd_opts: GitOpts = {}
64
+ self._env_vars: GitEnvVars | None = None
65
+ self._cmd_str_repr: str | None = None
66
+ self._main_cmd_opt_builders: dict[str, Callable[[], list[str]]] = {
67
+ "C": self._main_cmd_cap_c_args,
68
+ "c": self._main_cmd_small_c_args,
69
+ "config_env": self._main_cmd_config_env_args,
70
+ "exec_path": self._main_cmd_exec_path_args,
71
+ "paginate": self._main_cmd_paginate_args,
72
+ "no_pager": self._main_cmd_no_pager_args,
73
+ "git_dir": self._main_cmd_git_dir_args,
74
+ "work_tree": self._main_cmd_work_tree_args,
75
+ "namespace": self._main_cmd_namespace_args,
76
+ "bare": self._main_cmd_bare_args,
77
+ "no_replace_objects": self._main_cmd_no_replace_objects_args,
78
+ "no_lazy_fetch": self._main_cmd_no_lazy_fetch_args,
79
+ "no_optional_locks": self._main_cmd_no_optional_locks_args,
80
+ "no_advice": self._main_cmd_no_advice_args,
81
+ "literal_pathspecs": self._main_cmd_literal_pathspecs_args,
82
+ "glob_pathspecs": self._main_cmd_glob_pathspecs_args,
83
+ "noglob_pathspecs": self._main_cmd_noglob_pathspecs_args,
84
+ "icase_pathspecs": self._main_cmd_icase_pathspecs_args,
85
+ "list_cmds": self._main_cmd_list_cmds_args,
86
+ "attr_source": self._main_cmd_attr_source_args,
87
+ }
88
+
89
+ @override
90
+ def __str__(self) -> str:
91
+ """
92
+ >>> import gitbolt
93
+
94
+ No options and envs:
95
+
96
+ >>> _a_git = gitbolt.get_git_command()
97
+ >>> assert str(_a_git) == GIT_CMD
98
+
99
+ Added main command options:
100
+
101
+ >>> _b_git = _a_git.git_opts_override(C=[Path("a"), Path("b")], no_advice=True, no_replace_objects=True)
102
+ >>> assert str(_a_git) == GIT_CMD # _a_git never changed
103
+ >>> assert str(_b_git) == f"{GIT_CMD} -C a -C b --no-advice --no-replace-objects"
104
+
105
+ Adding git envs:
106
+
107
+ >>> _c_git = _a_git.git_envs_override(GIT_ADVICE=False, GIT_AUTHOR_NAME="Suhas", GIT_PAGER="vi")
108
+ >>> assert str(_a_git) == GIT_CMD # _a_git never changed
109
+ >>> assert str(_c_git) == f"GIT_ADVICE=False GIT_AUTHOR_NAME=Suhas GIT_PAGER=vi {GIT_CMD}"
110
+
111
+ >>> _d_git = _c_git.git_opts_override(C=[Path("a"), Path("b")], no_advice=True, no_replace_objects=True, config_env=dict(conf1="val1", glob1="val2"))
112
+ >>> assert str(_d_git) == f"GIT_ADVICE=False GIT_AUTHOR_NAME=Suhas GIT_PAGER=vi {GIT_CMD} -C a -C b --no-advice --no-replace-objects --config-env conf1=val1 --config-env glob1=val2"
113
+
114
+ Does not affect repr:
115
+
116
+ >>> assert repr(_d_git) != str(_d_git)
117
+ """
118
+ if self._cmd_str_repr:
119
+ return self._cmd_str_repr
120
+ _built_cmd_envs = self.build_git_envs()
121
+ _built_cmd_options = self.build_main_cmd_args()
122
+ envs = [f"{k}={v}" for k, v in _built_cmd_envs.items()] if _built_cmd_envs else []
123
+ opts = _built_cmd_options or []
124
+ self._cmd_str_repr = " ".join(envs+[GIT_CMD]+opts)
125
+ return self._cmd_str_repr
126
+
127
+ # region build_main_cmd_args
128
+ def build_main_cmd_args(self) -> list[str]:
129
+ """
130
+ Terminal operation to build and return CLI args for git main cli command.
131
+
132
+ For example, ``--no-pager --no-advice`` is the git main command in ``git --no-pager --no-advice log master -1``.
133
+
134
+ Examples:
135
+
136
+ - No CLI args to build
137
+
138
+ >>> import gitbolt
139
+ >>> _git = gitbolt.get_git_command()
140
+ >>> assert _git.build_main_cmd_args() == []
141
+
142
+ - One CLI arg to override
143
+
144
+ >>> _git = gitbolt.get_git_command()
145
+ >>> _m_git = _git.git_opts_override(C=[Path("dir/my/dir")])
146
+ >>> _o_git = _m_git.git_opts_override(C=[Path("other/dir")])
147
+ >>> assert _o_git.build_main_cmd_args() == ["-C", str(Path("other/dir"))]
148
+
149
+ - Multiple CLI args to override
150
+
151
+ >>> _git = gitbolt.get_git_command()
152
+ >>> _m_git = _git.git_opts_override(C=[Path("dir/my/dir")], config_env=dict(u1="user1", u2="user2"))
153
+ >>> _o_git = _m_git.git_opts_override(C=[Path("other/dir")])
154
+ >>> assert _o_git.build_main_cmd_args() == ["-C", str(Path("other/dir")), "--config-env", "u1=user1", "--config-env", "u2=user2"]
155
+
156
+ - Multiple CLI args to override when CLI is preferred
157
+
158
+ >>> _git = gitbolt.get_git_command(prefer_cli=True)
159
+ >>> _m_git = _git.git_opts_override(C=[Path("dir/my/dir")], config_env=dict(u1="user1", u2="user2"))
160
+ >>> _o_git = _m_git.git_opts_override(C=[Path("other/dir")])
161
+ >>> assert _o_git.build_main_cmd_args() == ["-C", str(Path("other/dir")), "--config-env", "u1=user1", "--config-env", "u2=user2"]
162
+
163
+ :return: CLI args for git main cli command.
164
+ """
165
+ args: list[str] = []
166
+ for opt_key in self._main_cmd_opts:
167
+ args.extend(self._main_cmd_args_for_opt_key(opt_key))
168
+ return args
169
+
170
+ def _main_cmd_args_for_opt_key(self, opt_key: str) -> list[str]:
171
+ builder = self._main_cmd_opt_builders.get(opt_key)
172
+ return builder() if builder else []
173
+
174
+ @override
175
+ def git_opts_override(self, **overrides: Unpack[GitOpts]) -> Self:
176
+ _git_cmd = self.clone()
177
+ _main_cmd_opts = merge_git_opts(overrides, self._main_cmd_opts)
178
+ _git_cmd._main_cmd_opts = _main_cmd_opts
179
+ _git_cmd._cmd_str_repr = None # make sure that the string representation is recomputed
180
+ return _git_cmd
181
+
182
+ def _main_cmd_cap_c_args(self) -> list[str]:
183
+ val = self._main_cmd_opts.get("C")
184
+ if not_none_not_unset(val):
185
+ return [item for path in val for item in ["-C", str(path)]]
186
+ return []
187
+
188
+ def _main_cmd_small_c_args(self) -> list[str]:
189
+ val = self._main_cmd_opts.get("c")
190
+ if not_none_not_unset(val):
191
+ args = []
192
+ for k, v in val.items():
193
+ if is_unset(v):
194
+ continue # explicitly skip unset keys
195
+ if v is True or v is None: # treat None as True
196
+ args += ["-c", k]
197
+ elif v is False:
198
+ args += ["-c", f"{k}="]
199
+ else:
200
+ args += ["-c", f"{k}={v}"]
201
+ return args
202
+ return []
203
+
204
+ def _main_cmd_config_env_args(self) -> list[str]:
205
+ val = self._main_cmd_opts.get("config_env")
206
+ if not_none_not_unset(val):
207
+ return [
208
+ item for k, v in val.items() for item in ["--config-env", f"{k}={v}"]
209
+ ]
210
+ return []
211
+
212
+ def _main_cmd_exec_path_args(self) -> list[str]:
213
+ val = self._main_cmd_opts.get("exec_path")
214
+ if not_none_not_unset(val):
215
+ return ["--exec-path", str(val)]
216
+ return []
217
+
218
+ def _main_cmd_paginate_args(self) -> list[str]:
219
+ val = self._main_cmd_opts.get("paginate")
220
+ if not_none_not_unset(val):
221
+ return ["--paginate"]
222
+ return []
223
+
224
+ def _main_cmd_no_pager_args(self) -> list[str]:
225
+ val = self._main_cmd_opts.get("no_pager")
226
+ if not_none_not_unset(val):
227
+ return ["--no-pager"]
228
+ return []
229
+
230
+ def _main_cmd_git_dir_args(self) -> list[str]:
231
+ val = self._main_cmd_opts.get("git_dir")
232
+ if not_none_not_unset(val):
233
+ return ["--git-dir", str(val)]
234
+ return []
235
+
236
+ def _main_cmd_work_tree_args(self) -> list[str]:
237
+ val = self._main_cmd_opts.get("work_tree")
238
+ if not_none_not_unset(val):
239
+ return ["--work-tree", str(val)]
240
+ return []
241
+
242
+ def _main_cmd_namespace_args(self) -> list[str]:
243
+ val = self._main_cmd_opts.get("namespace")
244
+ if not_none_not_unset(val):
245
+ return ["--namespace", val]
246
+ return []
247
+
248
+ def _main_cmd_bare_args(self) -> list[str]:
249
+ val = self._main_cmd_opts.get("bare")
250
+ if not_none_not_unset(val):
251
+ return ["--bare"]
252
+ return []
253
+
254
+ def _main_cmd_no_replace_objects_args(self) -> list[str]:
255
+ val = self._main_cmd_opts.get("no_replace_objects")
256
+ if not_none_not_unset(val):
257
+ return ["--no-replace-objects"]
258
+ return []
259
+
260
+ def _main_cmd_no_lazy_fetch_args(self) -> list[str]:
261
+ val = self._main_cmd_opts.get("no_lazy_fetch")
262
+ if not_none_not_unset(val):
263
+ return ["--no-lazy-fetch"]
264
+ return []
265
+
266
+ def _main_cmd_no_optional_locks_args(self) -> list[str]:
267
+ val = self._main_cmd_opts.get("no_optional_locks")
268
+ if not_none_not_unset(val):
269
+ return ["--no-optional-locks"]
270
+ return []
271
+
272
+ def _main_cmd_no_advice_args(self) -> list[str]:
273
+ val = self._main_cmd_opts.get("no_advice")
274
+ if not_none_not_unset(val):
275
+ return ["--no-advice"]
276
+ return []
277
+
278
+ def _main_cmd_literal_pathspecs_args(self) -> list[str]:
279
+ val = self._main_cmd_opts.get("literal_pathspecs")
280
+ if not_none_not_unset(val):
281
+ return ["--literal-pathspecs"]
282
+ return []
283
+
284
+ def _main_cmd_glob_pathspecs_args(self) -> list[str]:
285
+ val = self._main_cmd_opts.get("glob_pathspecs")
286
+ if not_none_not_unset(val):
287
+ return ["--glob-pathspecs"]
288
+ return []
289
+
290
+ def _main_cmd_noglob_pathspecs_args(self) -> list[str]:
291
+ val = self._main_cmd_opts.get("noglob_pathspecs")
292
+ if not_none_not_unset(val):
293
+ return ["--noglob-pathspecs"]
294
+ return []
295
+
296
+ def _main_cmd_icase_pathspecs_args(self) -> list[str]:
297
+ val = self._main_cmd_opts.get("icase_pathspecs")
298
+ if not_none_not_unset(val):
299
+ return ["--icase-pathspecs"]
300
+ return []
301
+
302
+ def _main_cmd_list_cmds_args(self) -> list[str]:
303
+ val = self._main_cmd_opts.get("list_cmds")
304
+ if not_none_not_unset(val):
305
+ return [item for cmd in val for item in ["--list-cmds", cmd]]
306
+ return []
307
+
308
+ def _main_cmd_attr_source_args(self) -> list[str]:
309
+ val = self._main_cmd_opts.get("attr_source")
310
+ if not_none_not_unset(val):
311
+ return ["--attr-source", val]
312
+ return []
313
+
314
+ # endregion
315
+
316
+ # region build_git_envs
317
+ def build_git_envs(self) -> dict[str, str] | None:
318
+ """
319
+ Terminal operation to build and return effective Git environment variables
320
+ from the merged ``GitEnvVars`` object.
321
+
322
+ Skips values that are ``Unset`` or ``None``-like using ``not_none_not_unset()``.
323
+ Converts ``Path`` and ``datetime`` instances to ``str``.
324
+
325
+ :return: A cleaned and normalized GitEnvVars dict suitable for use in subprocesses.
326
+ """
327
+ if self._env_vars is None:
328
+ return None
329
+ else:
330
+ env: dict[str, str] = {}
331
+ for key, val in self._env_vars.items():
332
+ if not_none_not_unset(val):
333
+ env[key] = str(val)
334
+ return env
335
+
336
+ @override
337
+ def git_envs_override(self, **overrides: Unpack[GitEnvVars]) -> Self:
338
+ _git_cmd = self.clone()
339
+ if self._env_vars:
340
+ _env_vars = merge_git_envs(overrides, self._env_vars)
341
+ else:
342
+ _env_vars = overrides
343
+ _git_cmd._env_vars = _env_vars
344
+ _git_cmd._cmd_str_repr = None
345
+ return _git_cmd
346
+
347
+ # endregion
348
+
349
+ @override
350
+ def html_path(self) -> Path:
351
+ html_path_str = "--html-path"
352
+ return self._get_path(html_path_str)
353
+
354
+ @override
355
+ def info_path(self) -> Path:
356
+ info_path_str = "--info-path"
357
+ return self._get_path(info_path_str)
358
+
359
+ @override
360
+ def man_path(self) -> Path:
361
+ man_path_str = "--man-path"
362
+ return self._get_path(man_path_str)
363
+
364
+ @override
365
+ def exec_path(self) -> Path:
366
+ exec_path_str = "--exec-path"
367
+ return self._get_path(exec_path_str)
368
+
369
+ def _get_path(self, path_opt_str: str) -> Path:
370
+ main_opts = self.build_main_cmd_args()
371
+ main_opts.append(path_opt_str)
372
+ _path_str = self.runner.run_git_command(
373
+ main_opts, [], check=True, text=True, capture_output=True
374
+ ).stdout.strip()
375
+ return Path(_path_str)
376
+
377
+ @override
378
+ @abstractmethod
379
+ def version_subcmd(self) -> VersionCommand: ...
380
+
381
+ @override
382
+ @abstractmethod
383
+ def ls_tree_subcmd(self) -> LsTreeCommand: ...
384
+
385
+ @override
386
+ @abstractmethod
387
+ def add_subcmd(self) -> AddCommand: ...
388
+
389
+ @override
390
+ @abstractmethod
391
+ def hash_object_subcmd(self) -> HashObjectCommand: ...
392
+
393
+ @override
394
+ @abstractmethod
395
+ def writing_hash_object_subcmd(self) -> WritingHashObjectCommand: ...
396
+
397
+ @override
398
+ @abstractmethod
399
+ def worktree_subcmd(self) -> WorktreeCommand: ...
400
+
401
+ @abstractmethod
402
+ def subcmd_unchecked(self) -> UncheckedSubcmd:
403
+ """
404
+ Run an unchecked git subcommand using subprocess.
405
+
406
+ :returns: An unchecked subcommand instance that simply runs the asked command in a ``subprocess.run()`` with
407
+ optional ``subprocess.Popen()``.
408
+ """
409
+ ...
410
+
411
+ @abstractmethod
412
+ def session(self, **commands: list[str] | Callable[[], Popen[bytes]]) -> GitSession:
413
+ """
414
+ Run long-running git session with multiple unchecked subcommands using ``subprocess.Popen`` and communicate with them.
415
+
416
+ Client/Caller can communicate with ``GitSession``'s processes with their stdin and stdout.
417
+
418
+ Examples:
419
+
420
+ Obtain a session:
421
+
422
+ >>> import gitbolt
423
+ >>> _git = gitbolt.get_git_command()
424
+ >>> ses = _git.session(ls_tree=["ls-tree", "HEAD"], cat_file=["cat-file", "--batch"])
425
+ >>> with ses: # start the session by ctx mgr
426
+ ... pass # any communication can be done by Popen semantics.
427
+
428
+ Start the session in one go:
429
+
430
+ >>> with _git.session(cat_file=["cat-file", "--batch"]) as ses: # obtain, start and ctx manage the session.
431
+ ... pass # any communication can be done by Popen semantics.
432
+
433
+ Run special Popen:
434
+
435
+ >>> import gitbolt
436
+ >>> _git = gitbolt.get_git_command()
437
+ >>> ses = _git.session(ls_tree=["ls-tree", "HEAD"],
438
+ ... cat_file=lambda : _git.subcmd_unchecked().popen(["cat-file", "--batch"], env=None))
439
+ >>> with ses: # start the session by ctx mgr
440
+ ... pass # any communication can be done by Popen semantics.
441
+
442
+ Is reentrant:
443
+
444
+ >>> import gitbolt
445
+ >>> _git = gitbolt.get_git_command()
446
+ >>> ses = _git.session(cat_file=["cat-file", "--batch-check"])
447
+ >>> with ses: # start the session by ctx mgr
448
+ ... with ses: # reentrant
449
+ ... pass
450
+ ... pass # any communication can be done by Popen semantics.
451
+
452
+
453
+ Note: All commands/processes are assumed:
454
+
455
+ - in bytes mode.
456
+ - pipe their stdin and stdout.
457
+
458
+ :param commands: list of string git commands suppliable to ``subprocess.Popen`` or ``subprocess.Popen`` lambdas.
459
+ :returns: A (not yet started) long-running ``GitSession`` context manager.
460
+ """
461
+ ...
462
+
463
+ @override
464
+ def clone(self) -> Self:
465
+ # region obtain class instance
466
+ cloned = self._subclass_clone()
467
+ # endregion
468
+ # region clone protected members
469
+ cloned._main_cmd_opts = self._main_cmd_opts
470
+ cloned._env_vars = self._env_vars
471
+ cloned._cmd_str_repr = self._cmd_str_repr
472
+ # endregion
473
+ return cloned
474
+
475
+ @abstractmethod
476
+ def _subclass_clone(self) -> Self:
477
+ """
478
+ :returns: clone as defined by the subclass.
479
+ """
480
+ ...
481
+
482
+
483
+ # TODO: extract a base session class from this
484
+ class GitSession(HasGitUnderneath[GitCommand], AbstractContextManager):
485
+ def __init__(self, git: GitCommand, **commands: Callable[[], Popen[bytes]]):
486
+ """
487
+ Reusable and reentrant context Manager to start a git long-running session. Useful when a command is to be
488
+ held in open state and be communicated with its stdin and stdout. This is way faster that spawning multiple
489
+ processes each time.
490
+
491
+ Examples:
492
+
493
+ Obtain a session:
494
+
495
+ >>> import gitbolt
496
+ >>> from gitbolt.subprocess.base import GitSession
497
+ >>> _git = gitbolt.get_git_command()
498
+ >>> ses = GitSession(_git, ls_tree= lambda : _git.subcmd_unchecked().popen(["ls-tree", "HEAD"], text=False),
499
+ ... cat_file= lambda : _git.subcmd_unchecked().popen(["cat-file", "--batch"], text=False))
500
+ >>> with ses: # start the session by ctx mgr
501
+ ... pass # any communication can be done by Popen semantics.
502
+
503
+ Start the session in one go:
504
+
505
+ >>> with GitSession(_git, cat_file= lambda : _git.subcmd_unchecked().popen(["cat-file", "--batch"], text=False)) as ses: # obtain, start and ctx manage the session.
506
+ ... pass # any communication can be done by Popen semantics.
507
+
508
+
509
+ Note: All processes are assumed:
510
+
511
+ - in bytes mode.
512
+ - pipe their stdin and stdout.
513
+
514
+ :param git: ``gitbolt.subprocess.GitCommand`` instance.
515
+ :param commands: commands in kwargs fashion.
516
+ """
517
+ self._git = git
518
+ self.all_supplied_commands: dict[str, Callable[[], Popen[bytes]]] = commands.copy()
519
+ self.started_commands: dict[str, Popen[bytes]] = dict()
520
+ self._commands: SimpleNamespace | None = None
521
+ self.__started = False
522
+ self.__done = False
523
+ self.__depth = 0
524
+ self.__times_reused = -1
525
+
526
+ @override
527
+ def __enter__(self) -> Self:
528
+ if self.depth == 0:
529
+ self.__done = False
530
+ processes_started_keys: list[str] = []
531
+ for unstarted_command_key, unstarted_command in self.all_supplied_commands.items():
532
+ try:
533
+ self.started_commands[unstarted_command_key] = unstarted_command().__enter__()
534
+ except Exception:
535
+ for k in reversed(processes_started_keys):
536
+ _close_session_popen(
537
+ self.started_commands[k], *sys.exc_info()
538
+ )
539
+ raise
540
+ processes_started_keys.append(unstarted_command_key)
541
+ self._commands = SimpleNamespace(**self.started_commands)
542
+ self.__started = True
543
+ self.__times_reused += 1
544
+ self.__depth += 1
545
+ return self
546
+
547
+ @override
548
+ @property
549
+ def git(self) -> GitCommand:
550
+ return self._git
551
+
552
+ @override
553
+ def __exit__(self, exc_type, exc_value, traceback, /) -> Literal[False]:
554
+ self.__depth -= 1
555
+ if self.__depth == 0:
556
+ process_done_keys: list[str] = []
557
+ for started_popen_key, started_popen in self.started_commands.items():
558
+ _close_session_popen(started_popen, exc_type, exc_value, traceback)
559
+ process_done_keys.append(started_popen_key)
560
+ self._commands = None
561
+ for pk in process_done_keys:
562
+ del self.started_commands[pk]
563
+ self.__done = True
564
+ return False
565
+
566
+ @property
567
+ def started(self) -> bool:
568
+ """
569
+ :returns: Whether the session has started.
570
+ """
571
+ return self.__started
572
+
573
+ @property
574
+ def done(self) -> bool:
575
+ """
576
+ :returns: Whether the session has completed and thus exited/closed.
577
+ """
578
+ return self.__done
579
+
580
+ @property
581
+ def active(self) -> bool:
582
+ """
583
+ :returns: Whether the session is currently actively running.
584
+ """
585
+ return self.started and not self.done
586
+
587
+ @property
588
+ def commands(self) -> SimpleNamespace:
589
+ """
590
+ :returns: All the registered commands and these can be accessed by member notations.
591
+ :raises RuntimeError: if commands are queried when the session is inactive.
592
+ """
593
+ if self._commands is None or not self.active:
594
+ raise RuntimeError("GitSession not active")
595
+ return self._commands
596
+
597
+ @property
598
+ def depth(self) -> int:
599
+ """
600
+ :returns: The current session depth. Multilevel context managers increment the depth each y one.
601
+ """
602
+ return self.__depth
603
+
604
+ def is_reused(self) -> bool:
605
+ """
606
+ :returns: The session is reused after being closed once.
607
+ """
608
+ return self.__times_reused > 0
609
+
610
+ @property
611
+ def times_reused(self) -> int:
612
+ return self.__times_reused
613
+
614
+
615
+ class GitSubcmdCommand(GitSubCommand, HasGitUnderneath["GitCommand"], Protocol):
616
+ """
617
+ A ``GitSubCommand`` that holds a reference to ``git`` and provides ``git_opts_override`` by default.
618
+ """
619
+
620
+ @override
621
+ def git_opts_override(self, **overrides: Unpack[GitOpts]) -> Self:
622
+ overridden_git = self.git.git_opts_override(**overrides)
623
+ self._set_underlying_git(overridden_git)
624
+ return self
625
+
626
+ @override
627
+ def git_envs_override(self, **overrides: Unpack[GitEnvVars]) -> Self:
628
+ overridden_git = self.git.git_envs_override(**overrides)
629
+ self._set_underlying_git(overridden_git)
630
+ return self
631
+
632
+ @abstractmethod
633
+ def _set_underlying_git(self, git: "GitCommand") -> None:
634
+ """
635
+ Protected. Designed to be overridden not called publicly.
636
+
637
+ Set the `_underlying_git` in the derived class.
638
+
639
+ :param git: git to override current class's `underlying_git` to.
640
+ """
641
+ ...
642
+
643
+
644
+ class VersionCommand(Version, GitSubcmdCommand, Protocol):
645
+ class _Cache:
646
+ def __init__(self):
647
+ self.version = None
648
+ self.semver = None
649
+ self.build_options = None
650
+
651
+ class VersionInfoForCmd(Version.VersionInfo):
652
+ def __init__(self, rosetta_supplier: Callable[[], str]):
653
+ self.rosetta_supplier = rosetta_supplier
654
+ self.rosetta: str | None = None
655
+ self._cache = VersionCommand._Cache()
656
+
657
+ @override
658
+ def version(self) -> str:
659
+ if self.rosetta is None:
660
+ self.rosetta = self.rosetta_supplier()
661
+ if self._cache.version is not None:
662
+ return self._cache.version
663
+ v_str = self.rosetta.splitlines()[0]
664
+ self._cache.version = v_str
665
+ return v_str
666
+
667
+ @override
668
+ def semver(self) -> tuple:
669
+ if self._cache.semver is not None:
670
+ return self._cache.semver
671
+ t_ver = self.version().split()[-1].split(".")
672
+ return tuple(t_ver)
673
+
674
+ @override
675
+ def __str__(self):
676
+ if self.rosetta is None:
677
+ self.rosetta = self.rosetta_supplier()
678
+ return self.rosetta
679
+
680
+ class VersionWithBuildInfoForCmd(VersionInfoForCmd, Version.VersionWithBuildInfo):
681
+ def __init__(
682
+ self, rosetta_supplier: Callable[[], str], splitter_expr: str = ": "
683
+ ):
684
+ super().__init__(rosetta_supplier)
685
+ self.splitter_expr = splitter_expr
686
+
687
+ @override
688
+ def build_options(self) -> dict[str, str]:
689
+ if self.rosetta is None:
690
+ self.rosetta = self.rosetta_supplier()
691
+ if self._cache.build_options is not None:
692
+ return self._cache.build_options
693
+ if not self.rosetta.splitlines()[1:]:
694
+ errmsg = "Unable to populate build_options as possibly --build-options switch wasn't used."
695
+ raise GitExitingException(
696
+ errmsg, exit_code=ERR_INVALID_USAGE
697
+ ) from ValueError(errmsg)
698
+
699
+ self._cache.build_options = {}
700
+ for b_str in self.rosetta.splitlines()[1:]:
701
+ if self.splitter_expr in b_str:
702
+ b_k, b_v = b_str.split(self.splitter_expr)
703
+ self._cache.build_options[b_k] = b_v
704
+ return self._cache.build_options
705
+
706
+ @override
707
+ def __str__(self) -> str:
708
+ """
709
+ >>> import gitbolt
710
+
711
+ No options and envs:
712
+
713
+ >>> _a_git = gitbolt.get_git_command()
714
+ >>> assert str(_a_git.version_subcmd()) == f"{GIT_CMD} {VERSION_CMD}"
715
+
716
+ Added main command options:
717
+
718
+ >>> _b_git = _a_git.git_opts_override(C=[Path("a"), Path("b")], no_advice=True, no_replace_objects=True)
719
+ >>> assert str(_a_git.version_subcmd()) == f"{GIT_CMD} {VERSION_CMD}" # _a_git never changed
720
+ >>> assert str(_b_git.version_subcmd()) == f"{GIT_CMD} -C a -C b --no-advice --no-replace-objects {VERSION_CMD}"
721
+
722
+ Adding git envs:
723
+
724
+ >>> _c_git = _a_git.git_envs_override(GIT_ADVICE=False, GIT_AUTHOR_NAME="Suhas", GIT_PAGER="vi")
725
+ >>> assert str(_a_git.version_subcmd()) == f"{GIT_CMD} {VERSION_CMD}" # _a_git never changed
726
+ >>> assert str(_c_git.version_subcmd()) == f"GIT_ADVICE=False GIT_AUTHOR_NAME=Suhas GIT_PAGER=vi {GIT_CMD} {VERSION_CMD}"
727
+
728
+ >>> _d_git = _c_git.git_opts_override(C=[Path("a"), Path("b")], no_advice=True, no_replace_objects=True, config_env=dict(conf1="val1", glob1="val2"))
729
+ >>> assert str(_d_git.version_subcmd()) == f"GIT_ADVICE=False GIT_AUTHOR_NAME=Suhas GIT_PAGER=vi {GIT_CMD} -C a -C b --no-advice --no-replace-objects --config-env conf1=val1 --config-env glob1=val2 {VERSION_CMD}"
730
+
731
+ Does not affect repr:
732
+
733
+ >>> assert repr(_d_git) != str(_d_git)
734
+ """
735
+ return " ".join([str(self.git), VERSION_CMD])
736
+
737
+
738
+ class LsTreeCommand(LsTree, GitSubcmdCommand, Protocol):
739
+ """
740
+ A composable class for building arguments for the `git ls-tree` subcommand, which is run later in a subprocess.
741
+
742
+ Intended usage includes CLI tooling, scripting, or Git plumbing automation, especially in
743
+ contexts where it's useful to dynamically generate Git commands.
744
+ """
745
+
746
+ @override
747
+ def ls_tree(self, tree_ish: str, **ls_tree_opts: Unpack[GitLsTreeOpts]) -> str:
748
+ self.args_validator.validate(tree_ish, **ls_tree_opts)
749
+ sub_cmd_args = self.cli_args_builder.build(tree_ish, **ls_tree_opts)
750
+ main_cmd_args = self.git.build_main_cmd_args()
751
+ env_vars = self.git.build_git_envs()
752
+
753
+ # Run the git command
754
+ result = self.git.runner.run_git_command(
755
+ main_cmd_args,
756
+ sub_cmd_args,
757
+ check=True,
758
+ text=True,
759
+ capture_output=True,
760
+ cwd=self.root_dir,
761
+ env=env_vars,
762
+ )
763
+
764
+ return result.stdout.strip()
765
+
766
+ @property
767
+ def cli_args_builder(self) -> LsTreeCLIArgsBuilder:
768
+ """
769
+ The builder assembles the subcommand CLI portion of the git command invocation, such as
770
+ in ``git --no-pager ls-tree -r HEAD``, where ``-r HEAD`` is the subcommand argument list.
771
+
772
+ :return: Builder the complete list of subcommand CLI arguments to be passed to ``git ls-tree`` subprocess.
773
+ """
774
+ return IndividuallyOverridableLTCAB()
775
+
776
+ @override
777
+ def __str__(self) -> str:
778
+ """
779
+ >>> import gitbolt
780
+
781
+ No options and envs:
782
+
783
+ >>> _a_git = gitbolt.get_git_command()
784
+ >>> assert str(_a_git.ls_tree_subcmd()) == f"{GIT_CMD} {LS_TREE_CMD}"
785
+
786
+ Added main command options:
787
+
788
+ >>> _b_git = _a_git.git_opts_override(C=[Path("a"), Path("b")], no_advice=True, no_replace_objects=True)
789
+ >>> assert str(_a_git.ls_tree_subcmd()) == f"{GIT_CMD} {LS_TREE_CMD}" # _a_git never changed
790
+ >>> assert str(_b_git.ls_tree_subcmd()) == f"{GIT_CMD} -C a -C b --no-advice --no-replace-objects {LS_TREE_CMD}"
791
+
792
+ Adding git envs:
793
+
794
+ >>> _c_git = _a_git.git_envs_override(GIT_ADVICE=False, GIT_AUTHOR_NAME="Suhas", GIT_PAGER="vi")
795
+ >>> assert str(_a_git.ls_tree_subcmd()) == f"{GIT_CMD} {LS_TREE_CMD}" # _a_git never changed
796
+ >>> assert str(_c_git.ls_tree_subcmd()) == f"GIT_ADVICE=False GIT_AUTHOR_NAME=Suhas GIT_PAGER=vi {GIT_CMD} {LS_TREE_CMD}"
797
+
798
+ >>> _d_git = _c_git.git_opts_override(C=[Path("a"), Path("b")], no_advice=True, no_replace_objects=True, config_env=dict(conf1="val1", glob1="val2"))
799
+ >>> assert str(_d_git.ls_tree_subcmd()) == f"GIT_ADVICE=False GIT_AUTHOR_NAME=Suhas GIT_PAGER=vi {GIT_CMD} -C a -C b --no-advice --no-replace-objects --config-env conf1=val1 --config-env glob1=val2 {LS_TREE_CMD}"
800
+
801
+ Does not affect repr:
802
+
803
+ >>> assert repr(_d_git) != str(_d_git)
804
+ """
805
+ return " ".join([str(self.git), LS_TREE_CMD])
806
+
807
+
808
+ class AddCommand(Add, GitSubcmdCommand, Protocol):
809
+ # TODO: check why PyCharm says that add() signature is incompatible with base class but mypy says okay.
810
+
811
+ @override
812
+ @overload
813
+ def add(
814
+ self, pathspec: str, *pathspecs: str, **add_opts: Unpack[GitAddOpts]
815
+ ) -> str: ...
816
+
817
+ @override
818
+ @overload
819
+ def add(
820
+ self,
821
+ *,
822
+ pathspec_from_file: Path,
823
+ pathspec_file_nul: bool = False,
824
+ **add_opts: Unpack[GitAddOpts],
825
+ ) -> str: ...
826
+
827
+ @override
828
+ @overload
829
+ def add(
830
+ self,
831
+ *,
832
+ pathspec_from_file: Literal["-"],
833
+ pathspec_stdin: str,
834
+ pathspec_file_nul: bool = False,
835
+ **add_opts: Unpack[GitAddOpts],
836
+ ) -> str: ...
837
+
838
+ @override
839
+ def add(
840
+ self,
841
+ pathspec: str | None = None,
842
+ *pathspecs: str,
843
+ pathspec_from_file: Path | Literal["-"] | None = None,
844
+ pathspec_stdin: str | None = None,
845
+ pathspec_file_nul: bool = False,
846
+ **add_opts: Unpack[GitAddOpts],
847
+ ) -> str:
848
+ self.args_validator.validate(
849
+ pathspec,
850
+ *pathspecs,
851
+ pathspec_from_file=pathspec_from_file,
852
+ pathspec_stdin=pathspec_stdin,
853
+ pathspec_file_nul=pathspec_file_nul,
854
+ **add_opts,
855
+ )
856
+ sub_cmd_args = self.cli_args_builder.build(
857
+ pathspec,
858
+ *pathspecs,
859
+ pathspec_from_file=pathspec_from_file,
860
+ pathspec_file_nul=pathspec_file_nul,
861
+ **add_opts,
862
+ )
863
+ main_cmd_args = self.git.build_main_cmd_args()
864
+ env_vars = self.git.build_git_envs()
865
+
866
+ # Run the git command
867
+ result = self.git.runner.run_git_command(
868
+ main_cmd_args,
869
+ sub_cmd_args,
870
+ _input=pathspec_stdin,
871
+ check=True,
872
+ text=True,
873
+ capture_output=True,
874
+ cwd=self.root_dir,
875
+ env=env_vars,
876
+ )
877
+
878
+ return result.stdout.strip()
879
+
880
+ @property
881
+ def cli_args_builder(self) -> AddCLIArgsBuilder:
882
+ """
883
+ The builder assembles the subcommand CLI portion of the git command invocation, such as
884
+ in ``git --no-pager add --ignore-missing add-file.py``, where ``--ignore-missing add-file.py`` is the
885
+ subcommand argument list.
886
+
887
+ :return: Builder the complete list of subcommand CLI arguments to be passed to ``git add`` subprocess.
888
+ """
889
+ return IndividuallyOverridableACAB()
890
+
891
+ @override
892
+ def __str__(self) -> str:
893
+ """
894
+ >>> import gitbolt
895
+
896
+ No options and envs:
897
+
898
+ >>> _a_git = gitbolt.get_git_command()
899
+ >>> assert str(_a_git.add_subcmd()) == f"{GIT_CMD} {ADD_CMD}"
900
+
901
+ Added main command options:
902
+
903
+ >>> _b_git = _a_git.git_opts_override(C=[Path("a"), Path("b")], no_advice=True, no_replace_objects=True)
904
+ >>> assert str(_a_git.add_subcmd()) == f"{GIT_CMD} {ADD_CMD}" # _a_git never changed
905
+ >>> assert str(_b_git.add_subcmd()) == f"{GIT_CMD} -C a -C b --no-advice --no-replace-objects {ADD_CMD}"
906
+
907
+ Adding git envs:
908
+
909
+ >>> _c_git = _a_git.git_envs_override(GIT_ADVICE=False, GIT_AUTHOR_NAME="Suhas", GIT_PAGER="vi")
910
+ >>> assert str(_a_git.add_subcmd()) == f"{GIT_CMD} {ADD_CMD}" # _a_git never changed
911
+ >>> assert str(_c_git.add_subcmd()) == f"GIT_ADVICE=False GIT_AUTHOR_NAME=Suhas GIT_PAGER=vi {GIT_CMD} {ADD_CMD}"
912
+
913
+ >>> _d_git = _c_git.git_opts_override(C=[Path("a"), Path("b")], no_advice=True, no_replace_objects=True, config_env=dict(conf1="val1", glob1="val2"))
914
+ >>> assert str(_d_git.add_subcmd()) == f"GIT_ADVICE=False GIT_AUTHOR_NAME=Suhas GIT_PAGER=vi {GIT_CMD} -C a -C b --no-advice --no-replace-objects --config-env conf1=val1 --config-env glob1=val2 {ADD_CMD}"
915
+
916
+ Does not affect repr:
917
+
918
+ >>> assert repr(_d_git) != str(_d_git)
919
+ """
920
+ return " ".join([str(self.git), ADD_CMD])
921
+
922
+
923
+ class HashObjectCommand(HashObject, GitSubcmdCommand, Protocol):
924
+ """
925
+ A composable class for building arguments for the `git hash-object` subcommand, which is run later in a subprocess.
926
+ """
927
+
928
+ @override
929
+ @overload
930
+ def hash_object(
931
+ self,
932
+ file_path: Path,
933
+ *,
934
+ t: Literal["commit", "tree", "blob", "tag"] = "blob",
935
+ path: Path | None = None,
936
+ literally: bool = False,
937
+ ) -> str: ...
938
+
939
+ @override
940
+ @overload
941
+ def hash_object(
942
+ self,
943
+ file_path: Path,
944
+ *,
945
+ t: Literal["commit", "tree", "blob", "tag"] = "blob",
946
+ no_filters: bool = False,
947
+ literally: bool = False,
948
+ ) -> str: ...
949
+
950
+ @override
951
+ @overload
952
+ def hash_object(
953
+ self,
954
+ file_path: Path,
955
+ *file_paths: Path,
956
+ t: Literal["commit", "tree", "blob", "tag"] = "blob",
957
+ no_filters: bool = False,
958
+ literally: bool = False,
959
+ stdin: bytes | None = None,
960
+ ) -> list[str]: ...
961
+
962
+ @override
963
+ @overload
964
+ def hash_object(
965
+ self,
966
+ file_path: Path,
967
+ *file_paths: Path,
968
+ t: Literal["commit", "tree", "blob", "tag"] = "blob",
969
+ path: Path | None = None,
970
+ literally: bool = False,
971
+ stdin: bytes | None = None,
972
+ ) -> list[str]: ...
973
+
974
+ @override
975
+ @overload
976
+ def hash_object(
977
+ self,
978
+ *,
979
+ stdin: bytes,
980
+ t: Literal["commit", "tree", "blob", "tag"] = "blob",
981
+ path: Path | None = None,
982
+ literally: bool = False,
983
+ ) -> str: ...
984
+
985
+ @override
986
+ @overload
987
+ def hash_object(
988
+ self,
989
+ *,
990
+ stdin: bytes,
991
+ t: Literal["commit", "tree", "blob", "tag"] = "blob",
992
+ no_filters: bool = False,
993
+ literally: bool = False,
994
+ ) -> str: ...
995
+
996
+ @override
997
+ @overload
998
+ def hash_object(
999
+ self,
1000
+ *,
1001
+ stdin_paths: list[Path],
1002
+ t: Literal["commit", "tree", "blob", "tag"] = "blob",
1003
+ no_filters: bool = False,
1004
+ literally: bool = False,
1005
+ ) -> list[str]: ...
1006
+
1007
+ @override
1008
+ def hash_object(
1009
+ self,
1010
+ file_path: Path | None = None,
1011
+ *file_paths: Path,
1012
+ t: Literal["commit", "tree", "blob", "tag"] = "blob",
1013
+ path: Path | None = None,
1014
+ no_filters: bool = False,
1015
+ literally: bool = False,
1016
+ stdin: bytes | None = None,
1017
+ stdin_paths: list[Path] | None = None,
1018
+ ) -> str | list[str]:
1019
+ return self._execute_hash_object(
1020
+ file_path,
1021
+ *file_paths,
1022
+ t=t,
1023
+ path=path,
1024
+ no_filters=no_filters,
1025
+ literally=literally,
1026
+ stdin=stdin,
1027
+ stdin_paths=stdin_paths,
1028
+ w=False,
1029
+ )
1030
+
1031
+ @override
1032
+ def multi_hash_objects(
1033
+ self,
1034
+ stdin: bytes,
1035
+ *stdins: bytes,
1036
+ t: Literal["commit", "tree", "blob", "tag"] = "blob",
1037
+ no_filters: bool = False,
1038
+ literally: bool = False,
1039
+ tmpdir: Path | None = None,
1040
+ ) -> list[str]:
1041
+ return self._multi_hash_objects(
1042
+ stdin,
1043
+ *stdins,
1044
+ t=t,
1045
+ no_filters=no_filters,
1046
+ literally=literally,
1047
+ w=False,
1048
+ tmpdir=tmpdir,
1049
+ )
1050
+
1051
+ def _execute_hash_object(
1052
+ self,
1053
+ file_path: Path | None = None,
1054
+ *file_paths: Path,
1055
+ t: Literal["commit", "tree", "blob", "tag"] = "blob",
1056
+ path: Path | None = None,
1057
+ no_filters: bool = False,
1058
+ literally: bool = False,
1059
+ stdin: bytes | None = None,
1060
+ stdin_paths: list[Path] | None = None,
1061
+ w: bool = False,
1062
+ ) -> str | list[str]:
1063
+ self.args_validator().validate(
1064
+ file_path,
1065
+ *file_paths,
1066
+ t=t,
1067
+ path=path,
1068
+ no_filters=no_filters,
1069
+ literally=literally,
1070
+ stdin=stdin,
1071
+ stdin_paths=stdin_paths,
1072
+ w=w,
1073
+ )
1074
+ sub_cmd_args = self.cli_args_builder.build(
1075
+ file_path,
1076
+ *file_paths,
1077
+ t=t,
1078
+ path=path,
1079
+ no_filters=no_filters,
1080
+ literally=literally,
1081
+ stdin=stdin,
1082
+ stdin_paths=stdin_paths,
1083
+ w=w,
1084
+ )
1085
+ main_cmd_args = self.git.build_main_cmd_args()
1086
+ env_vars = self.git.build_git_envs()
1087
+ _input = hash_object_stdin_input(stdin=stdin, stdin_paths=stdin_paths)
1088
+ result = self.git.runner.run_git_command(
1089
+ main_cmd_args,
1090
+ sub_cmd_args,
1091
+ _input=_input,
1092
+ check=True,
1093
+ text=False,
1094
+ capture_output=True,
1095
+ cwd=self._hash_object_cwd(),
1096
+ env=env_vars,
1097
+ )
1098
+ return hashes_from_hash_object_stdout(
1099
+ stripped_stdout_text(result.stdout),
1100
+ file_path=file_path,
1101
+ file_paths=file_paths,
1102
+ stdin=stdin,
1103
+ stdin_paths=stdin_paths,
1104
+ )
1105
+
1106
+ def _multi_hash_objects(
1107
+ self,
1108
+ stdin: bytes,
1109
+ *stdins: bytes,
1110
+ t: Literal["commit", "tree", "blob", "tag"] = "blob",
1111
+ no_filters: bool = False,
1112
+ literally: bool = False,
1113
+ w: bool = False,
1114
+ tmpdir: Path | None = None,
1115
+ ) -> list[str]:
1116
+ def hash_in(tmpdir_path: Path) -> list[str]:
1117
+ file_paths = stdin_temp_file_paths(stdin, *stdins, tmpdir=tmpdir_path)
1118
+ return as_hash_list(
1119
+ self._execute_hash_object(
1120
+ file_paths[0],
1121
+ *file_paths[1:],
1122
+ t=t,
1123
+ no_filters=no_filters,
1124
+ literally=literally,
1125
+ w=w,
1126
+ )
1127
+ )
1128
+
1129
+ return run_in_tmpdir(tmpdir, hash_in)
1130
+
1131
+ def _hash_object_cwd(self) -> Path | None:
1132
+ return None
1133
+
1134
+ @override
1135
+ @abstractmethod
1136
+ def clone(self) -> Self: ...
1137
+
1138
+ @property
1139
+ def cli_args_builder(self) -> HashObjectCLIArgsBuilder:
1140
+ """
1141
+ The builder assembles the subcommand CLI portion of the git command invocation, such as
1142
+ in ``git --no-pager hash-object -w file.txt``, where ``-w file.txt`` is the subcommand argument list.
1143
+
1144
+ :return: Builder the complete list of subcommand CLI arguments to be passed to ``git hash-object`` subprocess.
1145
+ """
1146
+ return IndividuallyOverridableHOCAB()
1147
+
1148
+ @override
1149
+ def writing(self) -> WritingHashObject:
1150
+ return self.git.writing_hash_object_subcmd()
1151
+
1152
+ @override
1153
+ def __str__(self) -> str:
1154
+ """
1155
+ >>> import gitbolt
1156
+
1157
+ No options and envs:
1158
+
1159
+ >>> _a_git = gitbolt.get_git_command()
1160
+ >>> assert str(_a_git.hash_object_subcmd()) == f"{GIT_CMD} {HASH_OBJECT_CMD}"
1161
+
1162
+ Added main command options:
1163
+
1164
+ >>> _b_git = _a_git.git_opts_override(C=[Path("a"), Path("b")], no_advice=True, no_replace_objects=True)
1165
+ >>> assert str(_a_git.hash_object_subcmd()) == f"{GIT_CMD} {HASH_OBJECT_CMD}" # _a_git never changed
1166
+ >>> assert str(_b_git.hash_object_subcmd()) == f"{GIT_CMD} -C a -C b --no-advice --no-replace-objects {HASH_OBJECT_CMD}"
1167
+
1168
+ Adding git envs:
1169
+
1170
+ >>> _c_git = _a_git.git_envs_override(GIT_ADVICE=False, GIT_AUTHOR_NAME="Suhas", GIT_PAGER="vi")
1171
+ >>> assert str(_a_git.hash_object_subcmd()) == f"{GIT_CMD} {HASH_OBJECT_CMD}" # _a_git never changed
1172
+ >>> assert str(_c_git.hash_object_subcmd()) == f"GIT_ADVICE=False GIT_AUTHOR_NAME=Suhas GIT_PAGER=vi {GIT_CMD} {HASH_OBJECT_CMD}"
1173
+
1174
+ >>> _d_git = _c_git.git_opts_override(C=[Path("a"), Path("b")], no_advice=True, no_replace_objects=True, config_env=dict(conf1="val1", glob1="val2"))
1175
+ >>> assert str(_d_git.hash_object_subcmd()) == f"GIT_ADVICE=False GIT_AUTHOR_NAME=Suhas GIT_PAGER=vi {GIT_CMD} -C a -C b --no-advice --no-replace-objects --config-env conf1=val1 --config-env glob1=val2 {HASH_OBJECT_CMD}"
1176
+
1177
+ Does not affect repr:
1178
+
1179
+ >>> assert repr(_d_git) != str(_d_git)
1180
+ """
1181
+ return " ".join([str(self.git), HASH_OBJECT_CMD])
1182
+
1183
+
1184
+ class WritingHashObjectCommand(HashObjectCommand, WritingHashObject, Protocol):
1185
+ """
1186
+ ``git hash-object`` subcommand that can write objects to the Git object database.
1187
+ """
1188
+
1189
+ @override
1190
+ @overload
1191
+ def hash_object(
1192
+ self,
1193
+ file_path: Path,
1194
+ *,
1195
+ t: Literal["commit", "tree", "blob", "tag"] = "blob",
1196
+ path: Path | None = None,
1197
+ literally: bool = False,
1198
+ w: bool = False,
1199
+ ) -> str: ...
1200
+
1201
+ @override
1202
+ @overload
1203
+ def hash_object(
1204
+ self,
1205
+ file_path: Path,
1206
+ *,
1207
+ t: Literal["commit", "tree", "blob", "tag"] = "blob",
1208
+ no_filters: bool = False,
1209
+ literally: bool = False,
1210
+ w: bool = False,
1211
+ ) -> str: ...
1212
+
1213
+ @override
1214
+ @overload
1215
+ def hash_object(
1216
+ self,
1217
+ file_path: Path,
1218
+ *file_paths: Path,
1219
+ t: Literal["commit", "tree", "blob", "tag"] = "blob",
1220
+ no_filters: bool = False,
1221
+ literally: bool = False,
1222
+ stdin: bytes | None = None,
1223
+ w: bool = False,
1224
+ ) -> list[str]: ...
1225
+
1226
+ @override
1227
+ @overload
1228
+ def hash_object(
1229
+ self,
1230
+ file_path: Path,
1231
+ *file_paths: Path,
1232
+ t: Literal["commit", "tree", "blob", "tag"] = "blob",
1233
+ path: Path | None = None,
1234
+ literally: bool = False,
1235
+ stdin: bytes | None = None,
1236
+ w: bool = False,
1237
+ ) -> list[str]: ...
1238
+
1239
+ @override
1240
+ @overload
1241
+ def hash_object(
1242
+ self,
1243
+ *,
1244
+ stdin: bytes,
1245
+ t: Literal["commit", "tree", "blob", "tag"] = "blob",
1246
+ path: Path | None = None,
1247
+ literally: bool = False,
1248
+ w: bool = False,
1249
+ ) -> str: ...
1250
+
1251
+ @override
1252
+ @overload
1253
+ def hash_object(
1254
+ self,
1255
+ *,
1256
+ stdin: bytes,
1257
+ t: Literal["commit", "tree", "blob", "tag"] = "blob",
1258
+ no_filters: bool = False,
1259
+ literally: bool = False,
1260
+ w: bool = False,
1261
+ ) -> str: ...
1262
+
1263
+ @override
1264
+ @overload
1265
+ def hash_object(
1266
+ self,
1267
+ *,
1268
+ stdin_paths: list[Path],
1269
+ t: Literal["commit", "tree", "blob", "tag"] = "blob",
1270
+ no_filters: bool = False,
1271
+ literally: bool = False,
1272
+ w: bool = False,
1273
+ ) -> list[str]: ...
1274
+
1275
+ @override
1276
+ def hash_object(
1277
+ self,
1278
+ file_path: Path | None = None,
1279
+ *file_paths: Path,
1280
+ t: Literal["commit", "tree", "blob", "tag"] = "blob",
1281
+ path: Path | None = None,
1282
+ no_filters: bool = False,
1283
+ literally: bool = False,
1284
+ stdin: bytes | None = None,
1285
+ stdin_paths: list[Path] | None = None,
1286
+ w: bool = False,
1287
+ ) -> str | list[str]:
1288
+ return self._execute_hash_object(
1289
+ file_path,
1290
+ *file_paths,
1291
+ t=t,
1292
+ path=path,
1293
+ no_filters=no_filters,
1294
+ literally=literally,
1295
+ stdin=stdin,
1296
+ stdin_paths=stdin_paths,
1297
+ w=w,
1298
+ )
1299
+
1300
+ @override
1301
+ def multi_hash_objects(
1302
+ self,
1303
+ stdin: bytes,
1304
+ *stdins: bytes,
1305
+ t: Literal["commit", "tree", "blob", "tag"] = "blob",
1306
+ no_filters: bool = False,
1307
+ literally: bool = False,
1308
+ w: bool = False,
1309
+ tmpdir: Path | None = None,
1310
+ ) -> list[str]:
1311
+ return self._multi_hash_objects(
1312
+ stdin,
1313
+ *stdins,
1314
+ t=t,
1315
+ no_filters=no_filters,
1316
+ literally=literally,
1317
+ w=w,
1318
+ tmpdir=tmpdir,
1319
+ )
1320
+
1321
+ @override
1322
+ def writing(self) -> WritingHashObject:
1323
+ return self
1324
+
1325
+
1326
+ class WorktreeCommand(Worktree, GitSubcmdCommand, abc.ABC):
1327
+ """
1328
+ Subprocess command running worktree abstract implementation.
1329
+ """
1330
+
1331
+ class WorktreeSubcmdCommand(Worktree.WorktreeSubcmd, HasGitUnderneath[GitCommand], Protocol):
1332
+ """
1333
+ Subprocess worktree subcommand.
1334
+ """
1335
+
1336
+ @override
1337
+ @property
1338
+ @abstractmethod
1339
+ def underlying_worktree(self) -> WorktreeCommand:
1340
+ ...
1341
+
1342
+ @property
1343
+ @abstractmethod
1344
+ def cli_args_builder(self) -> WorktreeCLIArgsBuilder:
1345
+ ...
1346
+
1347
+ @abstractmethod
1348
+ def _set_underlying_worktree(self, worktree: "WorktreeCommand") -> None:
1349
+ """
1350
+ Protected. Designed to be overridden not called publicly.
1351
+
1352
+ Set the `_underlying_worktree` in the derived class.
1353
+
1354
+ :param worktree: worktree to override current class's `underlying_worktree` to.
1355
+ """
1356
+ ...
1357
+
1358
+ # region worktree subcommands
1359
+ class ListCommand(Worktree.List, WorktreeSubcmdCommand, abc.ABC):
1360
+ """
1361
+ Subprocess worktree list subcommand.
1362
+ """
1363
+
1364
+ @override
1365
+ @overload
1366
+ def list(self, *, verbose: bool = False) -> str:
1367
+ ...
1368
+
1369
+ @override
1370
+ @overload
1371
+ def list(self, *, porcelain: Literal[False]) -> str:
1372
+ ...
1373
+
1374
+ @override
1375
+ @overload
1376
+ def list(self, *, porcelain: Literal[True], z: Literal[True] | Unset = UNSET) -> str:
1377
+ ...
1378
+
1379
+ @override
1380
+ def list(self, *, verbose: bool | Unset = UNSET, porcelain: Literal[True, False] | Unset = UNSET,
1381
+ z: Literal[True] | Unset = UNSET) -> str:
1382
+ sub_cmd_args = self.cli_args_builder.build_list_cli_args(
1383
+ verbose=verbose,
1384
+ porcelain=porcelain,
1385
+ z=z,
1386
+ )
1387
+ main_cmd_args = self.git.build_main_cmd_args()
1388
+ env_vars = self.git.build_git_envs()
1389
+
1390
+ # Run the git command
1391
+ result = self.git.runner.run_git_command(
1392
+ main_cmd_args,
1393
+ sub_cmd_args,
1394
+ check=True,
1395
+ text=True,
1396
+ capture_output=True,
1397
+ cwd=self.root_dir,
1398
+ env=env_vars,
1399
+ )
1400
+
1401
+ return result.stdout.strip()
1402
+
1403
+ @override
1404
+ @abstractmethod
1405
+ def clone(self) -> "WorktreeCommand.ListCommand":
1406
+ ...
1407
+
1408
+ class LockCommand(Worktree.Lock, WorktreeSubcmdCommand, abc.ABC):
1409
+
1410
+ @override
1411
+ def lock(self, worktree: Path, reason: str | Literal[False] | Unset = UNSET) -> str:
1412
+ sub_cmd_args = self.cli_args_builder.build_lock_cli_args(
1413
+ worktree, reason,)
1414
+ main_cmd_args = self.git.build_main_cmd_args()
1415
+ env_vars = self.git.build_git_envs()
1416
+
1417
+ # Run the git command
1418
+ result = self.git.runner.run_git_command(
1419
+ main_cmd_args,
1420
+ sub_cmd_args,
1421
+ check=True,
1422
+ text=True,
1423
+ capture_output=True,
1424
+ cwd=self.root_dir,
1425
+ env=env_vars,
1426
+ )
1427
+
1428
+ return result.stdout.strip()
1429
+
1430
+ @override
1431
+ @abstractmethod
1432
+ def clone(self) -> "WorktreeCommand.LockCommand":
1433
+ ...
1434
+
1435
+ class UnLockCommand(Worktree.UnLock, WorktreeSubcmdCommand, abc.ABC):
1436
+
1437
+ @override
1438
+ def unlock(self, worktree: Path) -> str:
1439
+ sub_cmd_args = self.cli_args_builder.build_unlock_cli_args(worktree)
1440
+ main_cmd_args = self.git.build_main_cmd_args()
1441
+ env_vars = self.git.build_git_envs()
1442
+
1443
+ # Run the git command
1444
+ result = self.git.runner.run_git_command(
1445
+ main_cmd_args,
1446
+ sub_cmd_args,
1447
+ check=True,
1448
+ text=True,
1449
+ capture_output=True,
1450
+ cwd=self.root_dir,
1451
+ env=env_vars,
1452
+ )
1453
+
1454
+ return result.stdout.strip()
1455
+
1456
+ @override
1457
+ @abstractmethod
1458
+ def clone(self) -> "WorktreeCommand.UnLockCommand":
1459
+ ...
1460
+
1461
+ class MoveCommand(Worktree.Move, WorktreeSubcmdCommand, abc.ABC):
1462
+
1463
+ @override
1464
+ def move(self, worktree: Path, new_path: Path, *, force: bool | Unset = UNSET, reforce: bool | Unset = UNSET,
1465
+ relative_paths: bool | Unset = UNSET) -> str:
1466
+ sub_cmd_args = self.cli_args_builder.build_move_cli_args(
1467
+ worktree, new_path, force=force, reforce=reforce, relative_paths=relative_paths)
1468
+ main_cmd_args = self.git.build_main_cmd_args()
1469
+ env_vars = self.git.build_git_envs()
1470
+
1471
+ # Run the git command
1472
+ result = self.git.runner.run_git_command(
1473
+ main_cmd_args,
1474
+ sub_cmd_args,
1475
+ check=True,
1476
+ text=True,
1477
+ capture_output=True,
1478
+ cwd=self.root_dir,
1479
+ env=env_vars,
1480
+ )
1481
+
1482
+ return result.stdout.strip()
1483
+
1484
+ @override
1485
+ @abstractmethod
1486
+ def clone(self) -> "WorktreeCommand.MoveCommand":
1487
+ ...
1488
+
1489
+ class PruneCommand(Worktree.Prune, WorktreeSubcmdCommand, abc.ABC):
1490
+
1491
+ @override
1492
+ def prune(self, *, dry_run: bool | Unset = UNSET, verbose: bool | Unset = UNSET,
1493
+ expire: Literal[False] | int | datetime | Unset = UNSET) -> str:
1494
+ sub_cmd_args = self.cli_args_builder.build_prune_cli_args(dry_run, verbose, expire)
1495
+ main_cmd_args = self.git.build_main_cmd_args()
1496
+ env_vars = self.git.build_git_envs()
1497
+
1498
+ # Run the git command
1499
+ result = self.git.runner.run_git_command(
1500
+ main_cmd_args,
1501
+ sub_cmd_args,
1502
+ check=True,
1503
+ text=True,
1504
+ capture_output=True,
1505
+ cwd=self.root_dir,
1506
+ env=env_vars,
1507
+ )
1508
+
1509
+ return result.stdout.strip()
1510
+
1511
+ @override
1512
+ @abstractmethod
1513
+ def clone(self) -> "WorktreeCommand.PruneCommand":
1514
+ ...
1515
+
1516
+ class RemoveCommand(Worktree.Remove, WorktreeSubcmdCommand, abc.ABC):
1517
+
1518
+ @override
1519
+ def remove(self, worktree: Path, *, force: bool | Unset = UNSET, reforce: bool | Unset = UNSET) -> str:
1520
+ sub_cmd_args = self.cli_args_builder.build_remove_cli_args(worktree, force=force, reforce=reforce)
1521
+ main_cmd_args = self.git.build_main_cmd_args()
1522
+ env_vars = self.git.build_git_envs()
1523
+
1524
+ # Run the git command
1525
+ result = self.git.runner.run_git_command(
1526
+ main_cmd_args,
1527
+ sub_cmd_args,
1528
+ check=True,
1529
+ text=True,
1530
+ capture_output=True,
1531
+ cwd=self.root_dir,
1532
+ env=env_vars,
1533
+ )
1534
+
1535
+ return result.stdout.strip()
1536
+
1537
+ @override
1538
+ @abstractmethod
1539
+ def clone(self) -> "WorktreeCommand.RemoveCommand":
1540
+ ...
1541
+
1542
+ class RepairCommand(Worktree.Repair, WorktreeSubcmdCommand, abc.ABC):
1543
+
1544
+ @override
1545
+ def repair(self, *worktrees: Path, relative_paths: Unset | bool = UNSET) -> str:
1546
+ sub_cmd_args = self.cli_args_builder.build_repair_cli_args(*worktrees,
1547
+ relative_paths=relative_paths)
1548
+ main_cmd_args = self.git.build_main_cmd_args()
1549
+ env_vars = self.git.build_git_envs()
1550
+
1551
+ # Run the git command
1552
+ result = self.git.runner.run_git_command(
1553
+ main_cmd_args,
1554
+ sub_cmd_args,
1555
+ check=True,
1556
+ text=True,
1557
+ capture_output=True,
1558
+ cwd=self.root_dir,
1559
+ env=env_vars,
1560
+ )
1561
+
1562
+ return result.stdout.strip()
1563
+
1564
+ @override
1565
+ @abstractmethod
1566
+ def clone(self) -> "WorktreeCommand.RepairCommand":
1567
+ ...
1568
+
1569
+ class AddCommand(Worktree.Add, WorktreeSubcmdCommand, abc.ABC):
1570
+
1571
+ @override
1572
+ def add(self, worktree: Path, commit_ish: str | None = None, *, force: bool | Unset = UNSET,
1573
+ reforce: bool | Unset = UNSET, new_branch: str | Unset = UNSET, new_branch_force: str | Unset = UNSET,
1574
+ orphan: Literal[True] | Unset = UNSET, detach: Literal[True] | Unset = UNSET,
1575
+ checkout: bool | Unset = UNSET, lock: bool | Unset = UNSET,
1576
+ reason: str | Literal[False] | Unset = UNSET, quiet: bool | Unset = UNSET,
1577
+ track: bool | Unset = UNSET, guess_remote: bool | Unset = UNSET,
1578
+ relative_paths: bool | Unset = UNSET) -> str:
1579
+ sub_cmd_args = self.cli_args_builder.build_add_cli_args(
1580
+ worktree, commit_ish, force=force, reforce=reforce, new_branch=new_branch,
1581
+ new_branch_force=new_branch_force, orphan=orphan, detach=detach, checkout=checkout, lock=lock,
1582
+ reason=reason, quiet=quiet, track=track, guess_remote=guess_remote, relative_paths=relative_paths)
1583
+ main_cmd_args = self.git.build_main_cmd_args()
1584
+ env_vars = self.git.build_git_envs()
1585
+
1586
+ # Run the git command
1587
+ result = self.git.runner.run_git_command(
1588
+ main_cmd_args,
1589
+ sub_cmd_args,
1590
+ check=True,
1591
+ text=True,
1592
+ capture_output=True,
1593
+ cwd=self.root_dir,
1594
+ env=env_vars,
1595
+ )
1596
+
1597
+ return result.stdout.strip()
1598
+
1599
+ @override
1600
+ def __str__(self) -> str:
1601
+ return " ".join([str(self.underlying_worktree), WORKTREE_ADD_CMD])
1602
+
1603
+ @override
1604
+ @abstractmethod
1605
+ def clone(self) -> "WorktreeCommand.AddCommand":
1606
+ ...
1607
+ # endregion
1608
+
1609
+ @property
1610
+ def cli_args_builder(self) -> WorktreeCLIArgsBuilder:
1611
+ """
1612
+ :return: Builder the complete list of subcommand CLI arguments to be passed to ``git worktree`` subprocess.
1613
+ """
1614
+ return WorktreeCLIArgsBuilder()
1615
+
1616
+ @override
1617
+ def __str__(self) -> str:
1618
+ """
1619
+ >>> import gitbolt
1620
+
1621
+ No options and envs:
1622
+
1623
+ >>> _a_git = gitbolt.get_git_command()
1624
+ >>> assert str(_a_git.worktree_subcmd()) == f"{GIT_CMD} {WORKTREE_CMD}"
1625
+
1626
+ Added main command options:
1627
+
1628
+ >>> _b_git = _a_git.git_opts_override(C=[Path("a"), Path("b")], no_advice=True, no_replace_objects=True)
1629
+ >>> assert str(_a_git.worktree_subcmd()) == f"{GIT_CMD} {WORKTREE_CMD}" # _a_git never changed
1630
+ >>> assert str(_b_git.worktree_subcmd()) == f"{GIT_CMD} -C a -C b --no-advice --no-replace-objects {WORKTREE_CMD}"
1631
+
1632
+ Adding git envs:
1633
+
1634
+ >>> _c_git = _a_git.git_envs_override(GIT_ADVICE=False, GIT_AUTHOR_NAME="Suhas", GIT_PAGER="vi")
1635
+ >>> assert str(_a_git.worktree_subcmd()) == f"{GIT_CMD} {WORKTREE_CMD}" # _a_git never changed
1636
+ >>> assert str(_c_git.worktree_subcmd()) == f"GIT_ADVICE=False GIT_AUTHOR_NAME=Suhas GIT_PAGER=vi {GIT_CMD} {WORKTREE_CMD}"
1637
+
1638
+ >>> _d_git = _c_git.git_opts_override(C=[Path("a"), Path("b")], no_advice=True, no_replace_objects=True, config_env=dict(conf1="val1", glob1="val2"))
1639
+ >>> assert str(_d_git.worktree_subcmd()) == f"GIT_ADVICE=False GIT_AUTHOR_NAME=Suhas GIT_PAGER=vi {GIT_CMD} -C a -C b --no-advice --no-replace-objects --config-env conf1=val1 --config-env glob1=val2 {WORKTREE_CMD}"
1640
+
1641
+ Does not affect repr:
1642
+
1643
+ >>> assert repr(_d_git) != str(_d_git)
1644
+ """
1645
+ return " ".join([str(self.git), WORKTREE_CMD])
1646
+
1647
+
1648
+
1649
+ class UncheckedSubcmd(GitSubcmdCommand, RootDirOp, Protocol):
1650
+ """
1651
+ Unchecked git subcommand. Runs subcommands directly in subprocess.
1652
+ """
1653
+
1654
+ @override
1655
+ def _subcmd_from_git(self, git: "Git") -> Self:
1656
+ return self
1657
+
1658
+ # TODO: the static type-safety of `run()` is not correct.
1659
+ # `run([..], text=True, _input=b'<some-str>')` is incorrect
1660
+ # as this should raise static-type check safety issue because text=True and _input is bytes. Similarly
1661
+ # `run([..], text=False, _input='<some-bytes>')` does not raise issue as well.
1662
+ @overload
1663
+ def run(
1664
+ self,
1665
+ subcommand_args: list[str],
1666
+ *subprocess_run_args: Any,
1667
+ _input: str,
1668
+ text: Literal[True],
1669
+ **subprocess_run_kwargs: Any,
1670
+ ) -> CompletedProcess[str]: ...
1671
+
1672
+ @overload
1673
+ def run(
1674
+ self,
1675
+ subcommand_args: list[str],
1676
+ *subprocess_run_args: Any,
1677
+ _input: bytes,
1678
+ text: Literal[False],
1679
+ **subprocess_run_kwargs: Any,
1680
+ ) -> CompletedProcess[bytes]: ...
1681
+
1682
+ @overload
1683
+ def run(
1684
+ self,
1685
+ subcommand_args: list[str],
1686
+ *subprocess_run_args: Any,
1687
+ text: Literal[True],
1688
+ **subprocess_run_kwargs: Any,
1689
+ ) -> CompletedProcess[str]: ...
1690
+
1691
+ @overload
1692
+ def run(
1693
+ self,
1694
+ subcommand_args: list[str],
1695
+ *subprocess_run_args: Any,
1696
+ text: Literal[False] = ...,
1697
+ **subprocess_run_kwargs: Any,
1698
+ ) -> CompletedProcess[bytes]: ...
1699
+
1700
+ def run(
1701
+ self,
1702
+ subcommand_args: list[str],
1703
+ *subprocess_run_args: Any,
1704
+ _input: str | bytes | None = None,
1705
+ text: Literal[True, False] = False,
1706
+ **subprocess_run_kwargs,
1707
+ ) -> CompletedProcess[str] | CompletedProcess[bytes]:
1708
+ """
1709
+ Run unchecked git subcommand using subprocess
1710
+
1711
+ :param subcommand_args: the full subcommand argument list.
1712
+ :param subprocess_run_args: additional subprocess positionals.
1713
+ :param _input: any stdin to be passed to the subprocess.
1714
+ :param text: ``_input`` and returns both are str if this value is ``True``. Else, bytes are considered.
1715
+ :param subprocess_run_kwargs: additional subprocess keyword arguments.
1716
+
1717
+ :return: ``CompletedProcess`` capturing all the required stdout, stderr, return-code etc.
1718
+ """
1719
+ main_cmd_args = self.git_main_cmd_args()
1720
+ envs_vars = self.git_envs(subprocess_run_kwargs.pop("env", None))
1721
+ cwd = subprocess_run_kwargs.pop("cwd", self.root_dir)
1722
+ capture_output = subprocess_run_kwargs.pop("capture_output", True)
1723
+ check = subprocess_run_kwargs.pop("check", True)
1724
+ # Run the git command
1725
+ result = self.git.runner.run_git_command(
1726
+ main_cmd_args,
1727
+ subcommand_args,
1728
+ *subprocess_run_args,
1729
+ _input=_input,
1730
+ text=text,
1731
+ env=envs_vars,
1732
+ cwd=cwd,
1733
+ capture_output=capture_output,
1734
+ check=check,
1735
+ **subprocess_run_kwargs,
1736
+ )
1737
+ return result
1738
+
1739
+ @overload
1740
+ def popen(
1741
+ self,
1742
+ subcommand_args: list[str],
1743
+ *popen_args: Any,
1744
+ text: Literal[False] = False,
1745
+ **popen_kwargs: Any,
1746
+ ) -> Popen[bytes]: ...
1747
+
1748
+ @overload
1749
+ def popen(
1750
+ self,
1751
+ subcommand_args: list[str],
1752
+ *popen_args: Any,
1753
+ text: Literal[True] = True,
1754
+ **popen_kwargs: Any,
1755
+ ) -> Popen[str]: ...
1756
+
1757
+ def popen(
1758
+ self,
1759
+ subcommand_args: list[str],
1760
+ *popen_args: Any,
1761
+ text: Literal[False, True] = False,
1762
+ **popen_kwargs: Any,
1763
+ ) -> Popen[str] | Popen[bytes]:
1764
+ """
1765
+ Open unchecked git subcommand communicable process, using ``subprocess.Popen``.
1766
+
1767
+ All the arguments are congruent to ``subprocess.Popen`` and mostly pass as-is.
1768
+
1769
+ :param subcommand_args: the full subcommand argument list.
1770
+ :param popen_args: additional subprocess positionals.
1771
+ :param text: ``_input`` and returns both are str if this value is ``True``. Else, bytes are considered.
1772
+ :param popen_kwargs: additional subprocess keyword arguments.
1773
+
1774
+ :return: ``Popen`` capturing all the required stdout, stderr etc and streaming stdin.
1775
+ """
1776
+ main_cmd_args = self.git_main_cmd_args()
1777
+ envs_vars = self.git_envs(popen_kwargs.pop("env", None))
1778
+ cwd = popen_kwargs.pop("cwd", self.root_dir)
1779
+ stdin = popen_kwargs.pop("stdin", PIPE)
1780
+ stdout = popen_kwargs.pop("stdout", PIPE)
1781
+ stderr = popen_kwargs.pop("stderr", PIPE)
1782
+ # Popen the git command
1783
+ result = self.git.runner.popen_git_command(
1784
+ main_cmd_args,
1785
+ subcommand_args,
1786
+ *popen_args,
1787
+ text=text,
1788
+ env=envs_vars,
1789
+ cwd=cwd,
1790
+ stdin=stdin,
1791
+ stdout=stdout,
1792
+ stderr=stderr,
1793
+ **popen_kwargs,
1794
+ )
1795
+ return result
1796
+
1797
+ def make_cmd(self, subcommand_args: list[str]) -> list[str]:
1798
+ """
1799
+ Make full runnable command for execution from the supplied ``subcommand_args``.
1800
+
1801
+ As knowledge of the git program and the main command is encapsulated within this ``UncheckedSubcmd`` thus,
1802
+ this is a convenience method for any external entities that want to run commands in their own subprocess.
1803
+
1804
+ :param subcommand_args: arguments for subcommand.
1805
+ :returns: a fully made and runnable command for some external ``subprocess`` call.
1806
+ """
1807
+ return self.git.runner.make_cmd(self.git.build_main_cmd_args(), subcommand_args)
1808
+
1809
+ def git_main_cmd_args(self) -> list[str]:
1810
+ """
1811
+ Get CLI args for git main cli command.
1812
+
1813
+ For example, ``--no-pager --no-advice`` is the git main command in ``git --no-pager --no-advice log master -1``.
1814
+
1815
+ :return: CLI args for git main cli command.
1816
+ """
1817
+ return self.git.build_main_cmd_args()
1818
+
1819
+ def git_envs(
1820
+ self, extra_git_envs: dict[str, str] | None = None
1821
+ ) -> dict[str, str] | None:
1822
+ """
1823
+ Get Git environment variables from the merged ``GitEnvVars`` object.
1824
+
1825
+ Skips values that are ``Unset`` or ``None``-like using ``not_none_not_unset()``.
1826
+ Converts ``Path`` and ``datetime`` instances to ``str``.
1827
+
1828
+ :param extra_git_envs: extraneous git envs supplied by the caller. These will be merged into the resultant
1829
+ git envs and then returned.
1830
+ :return: A cleaned and normalized GitEnvVars dict suitable for use in subprocesses.
1831
+ """
1832
+ env_vars = self.git.build_git_envs()
1833
+ if extra_git_envs and env_vars is not None:
1834
+ env_vars.update(extra_git_envs)
1835
+ return env_vars