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,23 @@
1
+ #!/usr/bin/env python3
2
+ # coding=utf-8
3
+
4
+ """
5
+ constants wrt of git commands using subprocess.
6
+ """
7
+
8
+ from typing import Final
9
+
10
+ GIT_CMD: Final[str] = "git"
11
+ VERSION_CMD: Final[str] = "version"
12
+ LS_TREE_CMD: Final[str] = "ls-tree"
13
+ ADD_CMD: Final[str] = "add"
14
+ HASH_OBJECT_CMD: Final[str] = "hash-object"
15
+ WORKTREE_CMD: Final[str] = "worktree"
16
+ WORKTREE_LIST_CMD: Final[str] = "list"
17
+ WORKTREE_ADD_CMD: Final[str] = "add"
18
+ WORKTREE_MOVE_CMD: Final[str] = "move"
19
+ WORKTREE_REMOVE_CMD: Final[str] = "remove"
20
+ WORKTREE_REPAIR_CMD: Final[str] = "repair"
21
+ WORKTREE_PRUNE_CMD: Final[str] = "prune"
22
+ WORKTREE_LOCK_CMD: Final[str] = "lock"
23
+ WORKTREE_UNLOCK_CMD: Final[str] = "unlock"
@@ -0,0 +1,110 @@
1
+ #!/usr/bin/env python3
2
+ # coding=utf-8
3
+
4
+ """
5
+ Exceptions specific to git using subprocess.
6
+ """
7
+
8
+ from vt.utils.errors.error_specs.exceptions import VTCmdException
9
+
10
+ from gitbolt.exceptions import GitException
11
+
12
+
13
+ class GitCmdException(GitException, VTCmdException):
14
+ """
15
+ A ``GitException`` that is also a ``VTCmdException``.
16
+
17
+ Examples:
18
+
19
+ >>> from subprocess import CalledProcessError
20
+
21
+ * raise without message:
22
+
23
+ >>> raise GitCmdException(called_process_error=CalledProcessError(1, ['git', 'status'])) # always use `from` clause.
24
+ Traceback (most recent call last):
25
+ gitbolt.subprocess.exceptions.GitCmdException: CalledProcessError: Command '['git', 'status']' returned non-zero exit status 1.
26
+
27
+ * raise with a message:
28
+
29
+ >>> raise GitCmdException('Git failed', called_process_error=CalledProcessError(1, ['git', 'push'])) # always use `from` clause.
30
+ Traceback (most recent call last):
31
+ gitbolt.subprocess.exceptions.GitCmdException: CalledProcessError: Git failed
32
+
33
+ * raise with overridden exit code:
34
+
35
+ >>> raise GitCmdException('Git push failed', called_process_error=CalledProcessError(1, ['git', 'push']), exit_code=42) # always use `from` clause.
36
+ Traceback (most recent call last):
37
+ gitbolt.subprocess.exceptions.GitCmdException: CalledProcessError: Git push failed
38
+
39
+ * raise without message, override with stderr inside CalledProcessError:
40
+
41
+ >>> err = CalledProcessError(128, ['git', 'fetch'], stderr='fatal: not a git repository')
42
+ >>> raise GitCmdException(called_process_error=err) # always use `from` clause.
43
+ Traceback (most recent call last):
44
+ gitbolt.subprocess.exceptions.GitCmdException: CalledProcessError: Command '['git', 'fetch']' returned non-zero exit status 128.
45
+
46
+ * raise exception using `from` clause (chaining):
47
+
48
+ >>> try:
49
+ ... raise CalledProcessError(129, ['git', 'clone'], stderr='fatal: repo not found')
50
+ ... except CalledProcessError as e:
51
+ ... raise GitCmdException('Clone failed', called_process_error=e) from e
52
+ Traceback (most recent call last):
53
+ gitbolt.subprocess.exceptions.GitCmdException: CalledProcessError: Clone failed
54
+
55
+ * cause reflects original CalledProcessError when chained:
56
+
57
+ >>> try:
58
+ ... raise CalledProcessError(2, ['git', 'commit'])
59
+ ... except CalledProcessError as e:
60
+ ... try:
61
+ ... raise GitCmdException('Commit failed', called_process_error=e) from e
62
+ ... except GitCmdException as g:
63
+ ... isinstance(g.cause, CalledProcessError)
64
+ True
65
+
66
+ * cause falls back to `called_process_error` when not chained:
67
+
68
+ >>> e = CalledProcessError(3, ['git', 'diff'])
69
+ >>> g = GitCmdException('Diff fail', called_process_error=e)
70
+ >>> g.cause is g.called_process_error
71
+ True
72
+
73
+ * access exit code:
74
+
75
+ >>> e = CalledProcessError(100, ['git', 'log'])
76
+ >>> ex = GitCmdException('Failure', called_process_error=e)
77
+ >>> ex.exit_code
78
+ 100
79
+
80
+ * override exit code manually:
81
+
82
+ >>> GitCmdException('Overridden', called_process_error=e, exit_code=77).exit_code
83
+ 77
84
+
85
+ * access structured information:
86
+
87
+ >>> g = GitCmdException('Git structured', called_process_error=e)
88
+ >>> info = g.to_dict()
89
+ >>> info['type'], 'Git structured' in info['message']
90
+ ('GitCmdException', True)
91
+
92
+ * raise exception with extra metadata:
93
+
94
+ >>> e = CalledProcessError(4, ['git', 'tag'])
95
+ >>> x = GitCmdException('Failed tagging', called_process_error=e, context='tagging-op')
96
+ >>> x.kwargs['context']
97
+ 'tagging-op'
98
+
99
+ * demonstrate subclass relationship:
100
+
101
+ >>> isinstance(GitCmdException('x', called_process_error=e), VTCmdException)
102
+ True
103
+
104
+ >>> isinstance(GitCmdException('x', called_process_error=e), GitException)
105
+ True
106
+
107
+ ... rest examples mimic ``VTCmdException``.
108
+ """
109
+
110
+ pass
@@ -0,0 +1,227 @@
1
+ #!/usr/bin/env python3
2
+ # coding=utf-8
3
+
4
+ """
5
+ Helper interfaces for ``git hash-object`` subcommand with default implementation for subprocess calls.
6
+ """
7
+
8
+ from abc import abstractmethod
9
+ from pathlib import Path
10
+ from typing import Protocol, override, Literal
11
+
12
+ from gitbolt.subprocess.constants import HASH_OBJECT_CMD
13
+
14
+
15
+ class HashObjectCLIArgsBuilder(Protocol):
16
+ """
17
+ Interface to facilitate building of cli arguments for ``git hash-object`` subcommand.
18
+ """
19
+
20
+ @abstractmethod
21
+ def build(
22
+ self,
23
+ file_path: Path | None = None,
24
+ *file_paths: Path,
25
+ t: Literal["commit", "tree", "blob", "tag"] = "blob",
26
+ path: Path | None = None,
27
+ no_filters: bool = False,
28
+ literally: bool = False,
29
+ stdin: bytes | None = None,
30
+ stdin_paths: list[Path] | None = None,
31
+ w: bool = False,
32
+ ) -> list[str]:
33
+ """
34
+ Build the complete list of subcommand arguments to be passed to ``git hash-object``.
35
+
36
+ This method assembles the subcommand portion of the git command invocation, such as
37
+ in ``git --no-pager hash-object -w file.txt``, where ``-w file.txt`` is the
38
+ subcommand argument list.
39
+
40
+ It delegates the formation of each argument to protected helper methods to allow
41
+ easier overriding and testing of individual components.
42
+
43
+ :return: Complete list of subcommand arguments.
44
+ :raises GitExitingException: if undesired argument type or argument combination is supplied.
45
+ """
46
+ ...
47
+
48
+
49
+ class IndividuallyOverridableHOCAB(HashObjectCLIArgsBuilder):
50
+ """
51
+ Individually Overridable Hash Object CLI Args Builder.
52
+
53
+ Build CLI args to run ``git hash-object`` subcommand in a subprocess. This class is independent in its working and
54
+ provides interface to individually override each arg former for fine-grained control.
55
+ """
56
+
57
+ @override
58
+ def build(
59
+ self,
60
+ file_path: Path | None = None,
61
+ *file_paths: Path,
62
+ t: Literal["commit", "tree", "blob", "tag"] = "blob",
63
+ path: Path | None = None,
64
+ no_filters: bool = False,
65
+ literally: bool = False,
66
+ stdin: bytes | None = None,
67
+ stdin_paths: list[Path] | None = None,
68
+ w: bool = False,
69
+ ) -> list[str]:
70
+ """
71
+ Build the full list of arguments to be passed to ``git hash-object``.
72
+
73
+ >>> builder = IndividuallyOverridableHOCAB()
74
+
75
+ Basic usage with one file:
76
+
77
+ >>> builder.build(Path("file.txt"))
78
+ ['hash-object', '-t', 'blob', 'file.txt']
79
+
80
+ Using boolean flags:
81
+
82
+ >>> builder.build(Path("file.txt"), no_filters=True, literally=True)
83
+ ['hash-object', '-t', 'blob', '--no-filters', '--literally', 'file.txt']
84
+
85
+ Using type and write:
86
+
87
+ >>> builder.build(Path("file.txt"), t="commit", w=True)
88
+ ['hash-object', '-w', '-t', 'commit', 'file.txt']
89
+
90
+ Using --path:
91
+
92
+ >>> _path = Path("filters/file.txt")
93
+ >>> builder.build(Path("file.txt"), path=_path) == [
94
+ ... "hash-object", "-t", "blob", f"--path={_path}", "file.txt"]
95
+ True
96
+
97
+ Using multiple files:
98
+
99
+ >>> builder.build(Path("a.txt"), Path("b.txt"))
100
+ ['hash-object', '-t', 'blob', 'a.txt', 'b.txt']
101
+
102
+ Using --stdin:
103
+
104
+ >>> builder.build(Path("a.txt"), stdin=b"extra")
105
+ ['hash-object', '-t', 'blob', '--stdin', 'a.txt']
106
+
107
+ Using --stdin only:
108
+
109
+ >>> builder.build(stdin=b"blob-bytes")
110
+ ['hash-object', '-t', 'blob', '--stdin']
111
+
112
+ Using --stdin-paths:
113
+
114
+ >>> builder.build(stdin_paths=[Path("a.txt"), Path("b.txt")])
115
+ ['hash-object', '-t', 'blob', '--stdin-paths']
116
+ """
117
+ sub_cmd_args = [HASH_OBJECT_CMD]
118
+ sub_cmd_args.extend(self.w_arg(w))
119
+ sub_cmd_args.extend(self.type_arg(t))
120
+ sub_cmd_args.extend(self.path_arg(path))
121
+ sub_cmd_args.extend(self.no_filters_arg(no_filters))
122
+ sub_cmd_args.extend(self.literally_arg(literally))
123
+ sub_cmd_args.extend(self.stdin_arg(stdin))
124
+ sub_cmd_args.extend(self.stdin_paths_arg(stdin_paths))
125
+ sub_cmd_args.extend(self.file_path_args(file_path, *file_paths))
126
+ return sub_cmd_args
127
+
128
+ def w_arg(self, w: bool | None) -> list[str]:
129
+ """
130
+ Return ``-w`` if `w` is True.
131
+
132
+ >>> IndividuallyOverridableHOCAB().w_arg(True)
133
+ ['-w']
134
+ >>> IndividuallyOverridableHOCAB().w_arg(False)
135
+ []
136
+ >>> IndividuallyOverridableHOCAB().w_arg(None)
137
+ []
138
+ """
139
+ return ["-w"] if w else []
140
+
141
+ def type_arg(self, t: Literal["commit", "tree", "blob", "tag"] | None) -> list[str]:
142
+ """
143
+ Return ``-t <type>`` if `t` is provided.
144
+
145
+ >>> IndividuallyOverridableHOCAB().type_arg("blob")
146
+ ['-t', 'blob']
147
+ >>> IndividuallyOverridableHOCAB().type_arg("commit")
148
+ ['-t', 'commit']
149
+ >>> IndividuallyOverridableHOCAB().type_arg(None)
150
+ []
151
+ """
152
+ return ["-t", t] if t else []
153
+
154
+ def path_arg(self, path: Path | None) -> list[str]:
155
+ """
156
+ Return ``--path=<path>`` if `path` is provided.
157
+
158
+ >>> _path = Path("filters/file.txt")
159
+ >>> IndividuallyOverridableHOCAB().path_arg(_path) == [f"--path={_path}"]
160
+ True
161
+ >>> IndividuallyOverridableHOCAB().path_arg(None)
162
+ []
163
+ """
164
+ return [f"--path={path}"] if path is not None else []
165
+
166
+ def no_filters_arg(self, no_filters: bool | None) -> list[str]:
167
+ """
168
+ Return ``--no-filters`` if `no_filters` is True.
169
+
170
+ >>> IndividuallyOverridableHOCAB().no_filters_arg(True)
171
+ ['--no-filters']
172
+ >>> IndividuallyOverridableHOCAB().no_filters_arg(False)
173
+ []
174
+ >>> IndividuallyOverridableHOCAB().no_filters_arg(None)
175
+ []
176
+ """
177
+ return ["--no-filters"] if no_filters else []
178
+
179
+ def literally_arg(self, literally: bool | None) -> list[str]:
180
+ """
181
+ Return ``--literally`` if `literally` is True.
182
+
183
+ >>> IndividuallyOverridableHOCAB().literally_arg(True)
184
+ ['--literally']
185
+ >>> IndividuallyOverridableHOCAB().literally_arg(False)
186
+ []
187
+ >>> IndividuallyOverridableHOCAB().literally_arg(None)
188
+ []
189
+ """
190
+ return ["--literally"] if literally else []
191
+
192
+ def stdin_arg(self, stdin: bytes | None) -> list[str]:
193
+ """
194
+ Return ``--stdin`` if stdin bytes are provided.
195
+
196
+ >>> IndividuallyOverridableHOCAB().stdin_arg(b"blob")
197
+ ['--stdin']
198
+ >>> IndividuallyOverridableHOCAB().stdin_arg(None)
199
+ []
200
+ """
201
+ return ["--stdin"] if stdin is not None else []
202
+
203
+ def stdin_paths_arg(self, stdin_paths: list[Path] | None) -> list[str]:
204
+ """
205
+ Return ``--stdin-paths`` if `stdin_paths` is provided.
206
+
207
+ >>> IndividuallyOverridableHOCAB().stdin_paths_arg([Path("a.txt")])
208
+ ['--stdin-paths']
209
+ >>> IndividuallyOverridableHOCAB().stdin_paths_arg(None)
210
+ []
211
+ """
212
+ return ["--stdin-paths"] if stdin_paths is not None else []
213
+
214
+ def file_path_args(self, file_path: Path | None, *file_paths: Path) -> list[str]:
215
+ """
216
+ Return file path operands.
217
+
218
+ >>> IndividuallyOverridableHOCAB().file_path_args(Path("a.txt"), Path("b.txt"))
219
+ ['a.txt', 'b.txt']
220
+ >>> IndividuallyOverridableHOCAB().file_path_args(None)
221
+ []
222
+ """
223
+ paths: list[str] = []
224
+ if file_path is not None:
225
+ paths.append(str(file_path))
226
+ paths.extend(str(p) for p in file_paths)
227
+ return paths
@@ -0,0 +1,90 @@
1
+ #!/usr/bin/env python3
2
+ # coding=utf-8
3
+
4
+ """
5
+ Utility helpers for ``git hash-object`` that do not belong on the command Protocol.
6
+
7
+ These functions have no instance state. Keep command Protocols free of loops and
8
+ conditionals; call these from the subprocess implementation instead.
9
+ """
10
+
11
+ from __future__ import annotations
12
+
13
+ import tempfile
14
+ from collections.abc import Callable
15
+ from pathlib import Path
16
+ from typing import TypeVar
17
+
18
+ _T = TypeVar("_T")
19
+
20
+
21
+ def hash_object_stdin_input(
22
+ *,
23
+ stdin: bytes | None,
24
+ stdin_paths: list[Path] | None,
25
+ ) -> bytes | None:
26
+ """
27
+ Bytes piped to ``git hash-object`` for ``--stdin`` or ``--stdin-paths``.
28
+ """
29
+ if stdin_paths is not None:
30
+ return b"\n".join(str(p).encode() for p in stdin_paths) + b"\n"
31
+ return stdin
32
+
33
+
34
+ def stdin_temp_file_paths(stdin: bytes, *stdins: bytes, tmpdir: Path) -> list[Path]:
35
+ """
36
+ Write each stdin payload to a file under ``tmpdir`` and return those paths.
37
+
38
+ >>> from pathlib import Path
39
+ >>> import tempfile
40
+ >>> with tempfile.TemporaryDirectory() as created:
41
+ ... paths = stdin_temp_file_paths(b"a", b"b", tmpdir=Path(created))
42
+ ... assert [p.read_bytes() for p in paths] == [b"a", b"b"]
43
+ """
44
+ file_paths: list[Path] = []
45
+ for index, data in enumerate((stdin, *stdins)):
46
+ path = tmpdir / f"stdin-{index}"
47
+ path.write_bytes(data)
48
+ file_paths.append(path)
49
+ return file_paths
50
+
51
+
52
+ def hashes_from_hash_object_stdout(
53
+ stdout: str,
54
+ *,
55
+ file_path: Path | None,
56
+ file_paths: tuple[Path, ...],
57
+ stdin: bytes | None,
58
+ stdin_paths: list[Path] | None,
59
+ ) -> str | list[str]:
60
+ """
61
+ Turn ``git hash-object`` stdout into a single hash or a list of hashes.
62
+ """
63
+ hashes = stdout.splitlines() if stdout else []
64
+ if stdin_paths is not None or file_paths or (file_path is not None and stdin is not None):
65
+ return hashes
66
+ return hashes[0]
67
+
68
+
69
+ def stripped_stdout_text(stdout: bytes) -> str:
70
+ """
71
+ Decode captured ``git hash-object`` bytes and strip surrounding whitespace.
72
+ """
73
+ return stdout.decode().strip()
74
+
75
+
76
+ def as_hash_list(hashed: str | list[str]) -> list[str]:
77
+ """
78
+ Normalize a single hash or a list of hashes to ``list[str]``.
79
+ """
80
+ return hashed if isinstance(hashed, list) else [hashed]
81
+
82
+
83
+ def run_in_tmpdir(tmpdir: Path | None, action: Callable[[Path], _T]) -> _T:
84
+ """
85
+ Run ``action`` with ``tmpdir``, or with a created temporary directory when omitted.
86
+ """
87
+ if tmpdir is None:
88
+ with tempfile.TemporaryDirectory() as created:
89
+ return action(Path(created))
90
+ return action(tmpdir)
@@ -0,0 +1,6 @@
1
+ #!/usr/bin/env python3
2
+ # coding=utf-8
3
+
4
+ """
5
+ implementations of git commands using subprocess.
6
+ """