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,610 @@
1
+ #!/usr/bin/env python3
2
+ # coding=utf-8
3
+
4
+ """
5
+ Git command sessions utilities for long-running commands.
6
+
7
+ Create sessions for long-running commands and communicate with them using their stdin/stdout.
8
+
9
+ Much faster that subprocess creation for each input/output pair.
10
+ """
11
+ import errno
12
+ import subprocess
13
+ from typing import Iterable, IO, cast
14
+
15
+ from vt.utils.errors.error_specs import ERR_INVALID_USAGE, ERR_DATA_FORMAT_ERR
16
+
17
+ from gitbolt.exceptions import GitExitingException
18
+ from gitbolt.subprocess.utils.models import GitRawActor, GitRawSignature, GPGGitRawSignature, SSHGitRawSignature, \
19
+ RawCommitBytesObj, RawBytesValsOfCommit
20
+
21
+
22
+ def _close_session_popen(popen: subprocess.Popen[bytes], exc_type, exc_value, traceback) -> None:
23
+ """
24
+ Close a session ``Popen`` and ignore a broken pipe.
25
+
26
+ A git process started with a bad command can exit before the session does. Closing its stdin
27
+ then raises ``BrokenPipeError`` (common on macOS) or a matching ``OSError``.
28
+ """
29
+ try:
30
+ popen.__exit__(exc_type, exc_value, traceback)
31
+ except BrokenPipeError:
32
+ return
33
+ except OSError as err:
34
+ if err.errno in {errno.EPIPE, errno.ECONNRESET}:
35
+ return
36
+ if getattr(err, "winerror", None) in {109, 232}:
37
+ return
38
+ raise
39
+
40
+
41
+ # region blob
42
+ def cat_file_blob_content(
43
+ cat_file_popen: subprocess.Popen[bytes], blob_hash: bytes, require_type: bytes | None = None
44
+ ) -> bytes:
45
+ """
46
+ Read git blob contents using a long-running batched cat-file process.
47
+
48
+ Spawning new ``git show`` processes can be slower and resource consuming.
49
+
50
+ Note: ``cat_file_popen`` must pipe its ``stdin`` and ``stdout`` and run in ``bytes`` mode.
51
+
52
+ :param cat_file_popen: long-running ``git cat-file --batch`` process in bytes mode and pipes its stdin and stdout.
53
+ :param blob_hash: hash to be read from cat-file.
54
+ :param require_type: Optional git object type for validation.
55
+ :return: contents of blob hash in bytes.
56
+ :raises GitExitingException: when the found object type is not the required type.
57
+ """
58
+ obj_hash, typ, _, blob_content = cat_file_data(cat_file_popen, blob_hash)
59
+ if require_type and typ != require_type:
60
+ raise GitExitingException(f"Required Git object type: '{require_type.decode()}', found: '{typ.decode()}'",
61
+ exit_code=ERR_INVALID_USAGE) from ValueError(obj_hash)
62
+ return blob_content
63
+
64
+
65
+ def cat_file_data(cat_file_popen: subprocess.Popen[bytes], blob_hash: bytes) -> tuple[bytes, bytes, bytes, bytes]:
66
+ """
67
+ Read git contents using a long-running batched cat-file process. Best for programmatic use.
68
+
69
+ Spawning new ``git show`` processes can be slower and resource consuming.
70
+
71
+ Note: ``cat_file_popen`` must pipe its ``stdin`` and ``stdout`` and run in ``bytes`` mode.
72
+
73
+ :param cat_file_popen: long-running ``git cat-file --batch`` process in bytes mode and pipes its stdin and stdout.
74
+ :param blob_hash: hash to be read from cat-file.
75
+ :return: (hash, type, size, content) of the read stream.
76
+ """
77
+ write_obj = blob_hash + b"\n"
78
+ cat_file_popen_stdin: IO[bytes] = cast(IO[bytes], cat_file_popen.stdin) # stdin is assumed to be piped
79
+ cat_file_popen_stdout: IO[bytes] = cast(IO[bytes], cat_file_popen.stdout) # stdout is assumed to be piped
80
+ cat_file_popen_stdin.write(write_obj)
81
+ cat_file_popen_stdin.flush()
82
+ header = cat_file_popen_stdout.readline()
83
+ obj, typ, size, blob_content = cat_file_read(cat_file_popen_stdout, header)
84
+ cat_file_popen_stdout.read(1)
85
+ return obj, typ, size, blob_content
86
+
87
+
88
+ def cat_file_read(stream: IO[bytes], header: bytes) -> tuple[bytes, bytes, bytes, bytes]:
89
+ """
90
+ ``git cat-file`` produces contents by first giving a header that contains:
91
+
92
+ - object hash.
93
+ - type (commit, tree, blob, ..., etc.).
94
+ - size - the actual content is next ``size`` bytes long.
95
+
96
+ :param stream: stream to read ``git cat-file --batch`` bytes from.
97
+ :param header: the header line of ``git cat-file --batch``.
98
+ :returns: (hash, type, size, content) of the read stream.
99
+ """
100
+ obj, typ, size = header.split()
101
+ blob_content: bytes = stream.read(int(size))
102
+ return obj, typ, size, blob_content
103
+ # endregion
104
+
105
+
106
+ # region tree
107
+ # region query tree
108
+ def parse_cat_file_tree(git_cat_file_data: bytes) -> Iterable[tuple[bytes, bytes, bytes]]:
109
+ """
110
+ Parse bytes tree data.
111
+
112
+ Typically best for parsing tree data from the stdout of a long-running cat-file query for tree.
113
+
114
+ :param git_cat_file_data: tree data in bytes format as given by ``git cat-file --batch`` for a tree query.
115
+ :returns: iterable of (mode, sha, filename/filepath).
116
+ """
117
+ i = 0
118
+ n = len(git_cat_file_data)
119
+ while i < n:
120
+ # mode
121
+ j = git_cat_file_data.find(b" ", i)
122
+ mode = git_cat_file_data[i:j]
123
+ # filename
124
+ k = git_cat_file_data.find(b"\x00", j)
125
+ name = git_cat_file_data[j + 1: k]
126
+ # sha (20 bytes binary)
127
+ sha = git_cat_file_data[k + 1: k + 21]
128
+
129
+ yield mode, sha.hex().encode(), name
130
+ i = k + 21
131
+
132
+
133
+ def cat_file_tree_data(
134
+ cat_file_popen: subprocess.Popen[bytes], tree_hash: bytes, recursive: bool = False,
135
+ _prefix: bytes = b"",
136
+ ) -> Iterable[tuple[bytes, bytes, bytes]]:
137
+ """
138
+ Get tree data from the stdout of a long-running cat-file query for tree hash.
139
+
140
+ Note: ``cat_file_popen`` must pipe its ``stdin`` and ``stdout`` and run in ``bytes`` mode.
141
+
142
+ :param cat_file_popen: long-running ``git cat-file --batch`` process in bytes mode and pipes its stdin and stdout.
143
+ :param tree_hash: tree hash to be read from cat-file.
144
+ :param recursive: recursively query the full tree.
145
+ :param _prefix: prefix, useful when doing recursive tree query (only for internal use).
146
+ :return: iterable of (mode, sha, filename).
147
+ :raises GitExitingException: when ``tree_hash`` is not the hash of a valid git tree.
148
+ """
149
+ tree_content = cat_file_blob_content(cat_file_popen, tree_hash)
150
+ if not recursive:
151
+ for mode, sha, name in parse_cat_file_tree(tree_content):
152
+ # leaf node (blob, symlink, submodule)
153
+ yield mode, sha, name
154
+ else:
155
+ for mode, sha, name in parse_cat_file_tree(tree_content):
156
+ full_name = _prefix + name
157
+
158
+ if mode == b"40000": # directory (tree)
159
+ # recurse into subtree
160
+ yield from cat_file_tree_data(
161
+ cat_file_popen,
162
+ sha,
163
+ recursive=True,
164
+ _prefix=full_name + b"/",
165
+ )
166
+ else:
167
+ # leaf node (blob, symlink, submodule)
168
+ yield mode, sha, full_name
169
+
170
+
171
+ def cat_file_tree_content(cat_file_popen: subprocess.Popen[bytes], tree_hash: bytes, recursive: bool = False,
172
+ format_: bytes = b"%(objmode)06o %(objtype)s %(objhash)s\x09%(objpath)s") -> Iterable[bytes]:
173
+ """
174
+ Get tree data from the stdout of a long-running cat-file query for tree hash in the format specified.
175
+
176
+ Note: ``cat_file_popen`` must pipe its ``stdin`` and ``stdout`` and run in ``bytes`` mode.
177
+
178
+ Query format:
179
+
180
+ - objmode: `100644`, `100755`, `120000`, `040000`, `160000`.
181
+ - objtype: `blob`, `tree`, `commit`.
182
+ - objhash: sha hash of the object.
183
+ - objpath: full path of the object from repo root.
184
+
185
+ Default format usage and explanation:
186
+
187
+ - %(objmode)06o: 06-show six-chars left-padded with 0 (zeros), o - octal number.
188
+
189
+ :param cat_file_popen: long-running ``git cat-file --batch`` process in bytes mode and pipes its stdin and stdout.
190
+ :param tree_hash: tree hash to be read from cat-file.
191
+ :param recursive: recursively query the full tree.
192
+ :param format_: the format in which the queried tree data will be formatted. Follows bytes ``%`` operator
193
+ interpolation. Defaults to the typical ``git ls-tree`` format.
194
+ :return: iterable of tree data in the queried ``format_``.
195
+ :raises GitExitingException: when ``tree_hash`` is not the hash of a valid git tree.
196
+ """
197
+ for mode, sha, filename in cat_file_tree_data(cat_file_popen, tree_hash, recursive):
198
+ if mode == b"40000":
199
+ # directory
200
+ objtype = b"tree"
201
+ elif mode == b"160000":
202
+ # submodule
203
+ objtype = b"commit"
204
+ elif mode in (b"100644", b"100755", b"120000"):
205
+ # symlnk, executable, regular files
206
+ objtype = b"blob"
207
+ else:
208
+ raise GitExitingException(f"Invalid object mode: {mode.decode()}") from ValueError(tree_hash)
209
+ objmode = int(mode, 8)
210
+ yield format_ % {b"objmode": objmode, b"objtype": objtype, b"objhash": sha, b"objpath": filename}
211
+ # endregion
212
+
213
+
214
+ # region make tree
215
+ def mktree_tree_make(mktree_popen: subprocess.Popen[bytes], mktree_null_delimited_content: bytes) -> bytes:
216
+ """
217
+ Make a git tree using ``mktree`` Popen and tree data to get a git tree.
218
+
219
+ Natively supports null-terminated tree entries or ``git mktree --batch -z`` mode.
220
+
221
+ :param mktree_popen: long-running ``mktree --batch`` subprocess.Popen.
222
+ :param mktree_null_delimited_content: the tree data content as taken on stdin on ``mktree --batch -z``. These
223
+ contents are null (``\0``) delimited.
224
+ :returns: the created tree hash.
225
+ """
226
+ write_obj = mktree_null_delimited_content + b"\0\0"
227
+ tree_hash = single_shot_command(mktree_popen, write_obj, True)
228
+ return tree_hash.strip()
229
+
230
+
231
+ def single_shot_command(long_running_popen: subprocess.Popen[bytes], write_obj: bytes, readline: bool) -> bytes:
232
+ """
233
+ Make a git tree using ``mktree`` Popen and tree data to get a git tree.
234
+
235
+ Natively supports null-terminated tree entries or ``git mktree --batch -z`` mode.
236
+
237
+ :param long_running_popen: long-running subprocess.Popen.
238
+ :param write_obj: object to write to the stdin of the long-running process.
239
+ :param readline: stop at readline or read the whole stdout.
240
+ :returns: the created tree hash.
241
+ """
242
+ _popen_stdin: IO[bytes] = cast(IO[bytes], long_running_popen.stdin) # stdin is assumed to be piped
243
+ _popen_stdout: IO[bytes] = cast(IO[bytes], long_running_popen.stdout) # stdout is assumed to be piped
244
+ _popen_stdin.write(write_obj)
245
+ _popen_stdin.flush()
246
+ _popen_out = _popen_stdout.readline() if readline else _popen_stdout.read()
247
+ return _popen_out
248
+
249
+
250
+ def mktree_tree_data_make(mktree_popen: subprocess.Popen[bytes], mktree_entries: Iterable[bytes]) -> bytes:
251
+ """
252
+ Make a git tree using ``mktree`` Popen and tree data to get a git tree.
253
+
254
+ Natively supports null-terminated tree entries or ``git mktree --batch -z`` mode.
255
+
256
+ :param mktree_popen: long-running ``mktree --batch`` subprocess.Popen.
257
+ :param mktree_entries: tree entries as required by ``git mktree --batch -z`` or output by ``git ls-tree -z``.
258
+ :returns: the created tree hash.
259
+ """
260
+ return mktree_tree_make(mktree_popen, b"\0".join(mktree_entries))
261
+ # endregion
262
+ # endregion
263
+
264
+ # region commit
265
+ def cat_file_commit_content(cat_file_popen: subprocess.Popen[bytes], commit_hash: bytes) -> bytes:
266
+ """
267
+ Get commit data as produced on stdout of a ``git cat-file --batch`` process for the querying of a particular
268
+ commit hash.
269
+
270
+ Spawning new ``git show`` processes can be slower and resource consuming.
271
+
272
+ Note: ``cat_file_popen`` must pipe its ``stdin`` and ``stdout`` and run in ``bytes`` mode.
273
+
274
+ :param cat_file_popen: long-running ``git cat-file --batch`` process in bytes mode and pipes its stdin and stdout.
275
+ :param commit_hash: commit hash to be read from cat-file.
276
+ :return: contents of blob hash in bytes.
277
+ """
278
+ return cat_file_blob_content(cat_file_popen, commit_hash, b"commit")
279
+
280
+
281
+ def cat_file_commit_data(cat_file_popen: subprocess.Popen[bytes], commit_hash: bytes) -> RawCommitBytesObj:
282
+ """
283
+ Get commit programmatic data as produced on stdout of a ``git cat-file --batch`` process for the querying
284
+ of a particular commit hash.
285
+
286
+ Spawning new ``git show`` processes can be slower and resource consuming.
287
+
288
+ Note: ``cat_file_popen`` must pipe its ``stdin`` and ``stdout`` and run in ``bytes`` mode.
289
+
290
+ :param cat_file_popen: long-running ``git cat-file --batch`` process in bytes mode and pipes its stdin and stdout.
291
+ :param commit_hash: commit hash to be read from cat-file.
292
+ :return: ``RawCommitBytesObj`` for programmatic use.
293
+ """
294
+ commit_cat_file_content = cat_file_commit_content(cat_file_popen, commit_hash)
295
+ return parse_cat_file_commit_data(commit_hash, commit_cat_file_content)
296
+
297
+
298
+ def parse_cat_file_commit_data(commit_hash, commit_cat_file_content) -> RawCommitBytesObj:
299
+ """
300
+ Parser for a commit contents as presented by ``git cat-file --batch`` query for a commit hash.
301
+
302
+ :param commit_hash: hash of the commit to get parsed ``cat-file`` data for.
303
+ :param commit_cat_file_content: the ``cat-file`` commit content.
304
+ :returns: parsed and programmatic ``RawCommitBytesObj``.
305
+ """
306
+ r = parse_cat_file_commit_content(commit_cat_file_content)
307
+ author = GitRawActor.from_commit_bytes(r.author_val)
308
+ committer = GitRawActor.from_commit_bytes(r.committer_val)
309
+ signature = GitRawSignature(r.signature_val) if r.signature_val else None
310
+ return RawCommitBytesObj(commit_hash, r.tree_val, r.commit_parents_vals, author, committer, signature,
311
+ r.commit_message)
312
+
313
+
314
+ def parse_cat_file_commit_content(commit_cat_file_content) -> RawBytesValsOfCommit:
315
+ """
316
+ Parser for a commit contents as presented by ``git cat-file --batch`` query for a commit hash.
317
+
318
+ Examples:
319
+
320
+ Simple commit:
321
+
322
+ >>> _simple_commit_content = b\"\"\"tree df1a4e54e5c3db0fb50b83dfab9750250b6aea1b
323
+ ... parent b0086231746c37e198f4616f09cf697714f2033e
324
+ ... author Suhas Krishna Srivastava <suhasCanDoSo@gmail.com> 1780213058 +0530
325
+ ... committer Suhas Krishna Srivastava <suhasCanDoSo@gmail.com> 1780213152 +0530
326
+ ...
327
+ ... session: add doctests to `Actor.from_commit_bytes()`
328
+ ... \"\"\"
329
+ >>> _parsed_simple_commit_content = parse_cat_file_commit_content(_simple_commit_content)
330
+ >>> assert _parsed_simple_commit_content.tree_val == b"df1a4e54e5c3db0fb50b83dfab9750250b6aea1b"
331
+ >>> assert _parsed_simple_commit_content.commit_parents_vals == [b"b0086231746c37e198f4616f09cf697714f2033e"]
332
+ >>> assert _parsed_simple_commit_content.author_val == b"Suhas Krishna Srivastava <suhasCanDoSo@gmail.com> 1780213058 +0530"
333
+ >>> assert _parsed_simple_commit_content.committer_val == b"Suhas Krishna Srivastava <suhasCanDoSo@gmail.com> 1780213152 +0530"
334
+ >>> assert _parsed_simple_commit_content.signature_val is None
335
+ >>> assert _parsed_simple_commit_content.commit_message == b"session: add doctests to `Actor.from_commit_bytes()`\\n"
336
+
337
+ Multiple parents:
338
+
339
+ >>> _multiple_parent_commit = b\"\"\"tree 9b708a0877812922f43db4ddbc87196754937033
340
+ ... parent 3622f225ac320c9eece4c5319c89a00661cbcb39
341
+ ... parent b6f3199b6866a0522c6fe4eaf07cf4515ac1d8fd
342
+ ... parent deadbeefabcdefbeefdead1234566789beefeedd
343
+ ... author Suhas Krishna Srivastava <suhasCanDoSo@gmail.com> 1779643218 +0530
344
+ ... committer Suhas Krishna Srivastava <suhasCanDoSo@gmail.com> 1779643218 +0530
345
+ ...
346
+ ... Introduce `Popen`
347
+ ...
348
+ ... Merge branch 'feat/run-and-popen/main' into develop
349
+ ...
350
+ ... - Introduced `Popen` interface in runner.
351
+ ... - Introduced `Popen` interface in UncheckedSubcmd.
352
+ ... \"\"\"
353
+ >>> _parsed_multi_parent_commit = parse_cat_file_commit_content(_multiple_parent_commit)
354
+ >>> assert _parsed_multi_parent_commit.tree_val == b"9b708a0877812922f43db4ddbc87196754937033"
355
+ >>> assert _parsed_multi_parent_commit.commit_parents_vals == [b"3622f225ac320c9eece4c5319c89a00661cbcb39", b"b6f3199b6866a0522c6fe4eaf07cf4515ac1d8fd", b"deadbeefabcdefbeefdead1234566789beefeedd"]
356
+ >>> assert _parsed_multi_parent_commit.author_val == b"Suhas Krishna Srivastava <suhasCanDoSo@gmail.com> 1779643218 +0530"
357
+ >>> assert _parsed_multi_parent_commit.committer_val == b"Suhas Krishna Srivastava <suhasCanDoSo@gmail.com> 1779643218 +0530"
358
+ >>> assert _parsed_multi_parent_commit.signature_val is None
359
+ >>> assert _parsed_multi_parent_commit.commit_message == b"Introduce `Popen`\\n\\nMerge branch 'feat/run-and-popen/main' into develop\\n\\n- Introduced `Popen` interface in runner.\\n- Introduced `Popen` interface in UncheckedSubcmd.\\n"
360
+
361
+ GPG Signed commit:
362
+
363
+ >>> _gpg_signed_commit = b\"\"\"tree e26c61179203eea2b5c6a14dfff31621b74654c7
364
+ ... parent d7d8d6f79017c5d574e3c4ac519c855b7cec33e2
365
+ ... author Suhas Krishna Srivastava <suhasCanDoSo@gmail.com> 1779877779 +0530
366
+ ... committer Suhas Krishna Srivastava <suhasCanDoSo@gmail.com> 1779877779 +0530
367
+ ... gpgsig -----BEGIN PGP SIGNATURE-----
368
+ ...
369
+ ... iHUEABYKAB0WIQRBZelV8q2CQXy8Vg8vtl2qydHBMAUCahbHsAAKCRAvtl2qydHB
370
+ ... MNrAAP9ZYoOfzSHJsnNsocCxqdf0K5Dh0mWbo9hUAYtsKlv/HQEAi8J/jYBqY9lz
371
+ ... s6M7/A1YuKWMigDLTbMmjRg6uUgHOAM=
372
+ ... =5rmu
373
+ ... -----END PGP SIGNATURE-----
374
+ ...
375
+ ... Releasing `0.0.0.dev18`
376
+ ...
377
+ ... - `GitSession` improved.
378
+ ... - `GitSession` reexported in `gitbolt`.
379
+ ... - Popen no longer unbuffered.
380
+ ... - Sessions by default are in `bytes` mode and pipe their `stdin` and `stdout`.
381
+ ...
382
+ ... - `GitSession` now returns `Self` on `__enter__()`. Glad caught early.
383
+ ... - Utilities for git subprocess commands and Popen(s).
384
+ ...
385
+ ... Signed-off-by: Suhas Krishna Srivastava <suhas.srivastava@vaastav.tech>
386
+ ... \"\"\"
387
+ >>> _parsed_gpg_sig_commit = parse_cat_file_commit_content(_gpg_signed_commit)
388
+ >>> assert _parsed_gpg_sig_commit.tree_val == b"e26c61179203eea2b5c6a14dfff31621b74654c7"
389
+ >>> assert _parsed_gpg_sig_commit.commit_parents_vals == [b"d7d8d6f79017c5d574e3c4ac519c855b7cec33e2"]
390
+ >>> assert _parsed_gpg_sig_commit.author_val == b"Suhas Krishna Srivastava <suhasCanDoSo@gmail.com> 1779877779 +0530"
391
+ >>> assert _parsed_gpg_sig_commit.committer_val == b"Suhas Krishna Srivastava <suhasCanDoSo@gmail.com> 1779877779 +0530"
392
+ >>> assert _parsed_gpg_sig_commit.signature_val == b"-----BEGIN PGP SIGNATURE-----\\n\\niHUEABYKAB0WIQRBZelV8q2CQXy8Vg8vtl2qydHBMAUCahbHsAAKCRAvtl2qydHB\\nMNrAAP9ZYoOfzSHJsnNsocCxqdf0K5Dh0mWbo9hUAYtsKlv/HQEAi8J/jYBqY9lz\\ns6M7/A1YuKWMigDLTbMmjRg6uUgHOAM=\\n=5rmu\\n-----END PGP SIGNATURE-----"
393
+ >>> assert _parsed_gpg_sig_commit.commit_message == b"Releasing `0.0.0.dev18`\\n\\n- `GitSession` improved.\\n- `GitSession` reexported in `gitbolt`.\\n- Popen no longer unbuffered.\\n- Sessions by default are in `bytes` mode and pipe their `stdin` and `stdout`.\\n\\n- `GitSession` now returns `Self` on `__enter__()`. Glad caught early.\\n- Utilities for git subprocess commands and Popen(s).\\n\\nSigned-off-by: Suhas Krishna Srivastava <suhas.srivastava@vaastav.tech>\\n"
394
+
395
+ No message commit:
396
+
397
+ >>> _no_msg_commit = b\"\"\"tree e26c61179203eea2b5c6a14dfff31621b74654c7
398
+ ... parent d7d8d6f79017c5d574e3c4ac519c855b7cec33e2
399
+ ... author Suhas Krishna Srivastava <suhasCanDoSo@gmail.com> 1779877779 +0530
400
+ ... committer Suhas Krishna Srivastava <suhasCanDoSo@gmail.com> 1779877779 +0530
401
+ ...
402
+ ... \"\"\"
403
+ >>> _parsed_no_msg_commit = parse_cat_file_commit_content(_no_msg_commit)
404
+ >>> assert _parsed_no_msg_commit.tree_val == b"e26c61179203eea2b5c6a14dfff31621b74654c7"
405
+ >>> assert _parsed_no_msg_commit.commit_parents_vals == [b"d7d8d6f79017c5d574e3c4ac519c855b7cec33e2"]
406
+ >>> assert _parsed_no_msg_commit.author_val == b"Suhas Krishna Srivastava <suhasCanDoSo@gmail.com> 1779877779 +0530"
407
+ >>> assert _parsed_no_msg_commit.committer_val == b"Suhas Krishna Srivastava <suhasCanDoSo@gmail.com> 1779877779 +0530"
408
+ >>> assert _parsed_no_msg_commit.signature_val is None
409
+ >>> assert _parsed_no_msg_commit.commit_message == b""
410
+
411
+ No parent commit:
412
+
413
+ >>> _no_parent_commit = b\"\"\"tree 28f8877d1952f06b6e22c2d57522796dfa62e145
414
+ ... author Suhas Krishna Srivastava <suhas.srivastava@vaastav.tech> 1747405354 +0530
415
+ ... committer GitHub <noreply@github.com> 1747405354 +0530
416
+ ... gpgsig -----BEGIN PGP SIGNATURE-----
417
+ ...
418
+ ... wsFcBAABCAAQBQJoJ0oqCRC1aQ7uu5UhlAAABbQQAKnq3HAThX2whGmo4+u5Czg/
419
+ ... AybUlY396eoUd9JMoPF+E8+BVWe4ulVmbnWkPBW4iEUtqJzeNA9ULPNnMYMa1Dtu
420
+ ... iu+IbMt3hh5FuLVtpA+92V9U+0RwpwYjX48dDeVfAWMz9QsI1z4SMUPZmyb7cV2J
421
+ ... oAcStdGLPhZGa0RSRxFm+KuoZRCWSJ65a8HYpR0zI8sKvTZaFrS+ItxtvALkMBL7
422
+ ... dsbdbTNtyPrdqYFhA7BNe7cisd5Avob01CMkV3aPwLFKtFdtS7WPLwwR0fXhOLZV
423
+ ... DiYe7Tu+NrVcQJe1QLjkek4DnaN0ph4Xyi/K0CW4FJZ4vXIUI99Z9FP0QKiEX7bN
424
+ ... XWyBchwwqFiE17PcSkLOLX0VUCIYdF0w6pj4AzNpSn8PY0jEg0FLbnfj+ZDfBhxl
425
+ ... cUvh0obhnxdd4BafqzWSJPpzhCwx3NjkuNA1464BcerCTy7XkNxPtYyTDfLWD12x
426
+ ... PVRKAqhm/z2yHyP93maRYY9R/Qvx7n5XJBFh+5w66e3Gvb+RaQQ8HcyJKbz+I/PJ
427
+ ... tSRRAm1ROTnCLdWzjzimbOT4agKgwG53HqeaRLzqteu+lTr64LH5ZZZkAUd9v+C9
428
+ ... cJb41OV3hHdP0+evTn471JU7YQlCYiQK+Ps04TsUX1MwRgoNq1+znk27PK7B1XUF
429
+ ... 21sfF75JL4q7VsU/dpCU
430
+ ... =0m4k
431
+ ... -----END PGP SIGNATURE-----
432
+ ...
433
+ ...
434
+ ... Initial commit\"\"\"
435
+ >>> _parsed_no_parent_commit = parse_cat_file_commit_content(_no_parent_commit)
436
+ >>> assert _parsed_no_parent_commit.tree_val == b"28f8877d1952f06b6e22c2d57522796dfa62e145"
437
+ >>> assert _parsed_no_parent_commit.commit_parents_vals == []
438
+ >>> assert _parsed_no_parent_commit.author_val == b"Suhas Krishna Srivastava <suhas.srivastava@vaastav.tech> 1747405354 +0530"
439
+ >>> assert _parsed_no_parent_commit.committer_val == b"GitHub <noreply@github.com> 1747405354 +0530"
440
+ >>> assert _parsed_no_parent_commit.commit_message == b"\\nInitial commit"
441
+ >>> assert _parsed_no_parent_commit.signature_val == b"-----BEGIN PGP SIGNATURE-----\\n\\nwsFcBAABCAAQBQJoJ0oqCRC1aQ7uu5UhlAAABbQQAKnq3HAThX2whGmo4+u5Czg/\\nAybUlY396eoUd9JMoPF+E8+BVWe4ulVmbnWkPBW4iEUtqJzeNA9ULPNnMYMa1Dtu\\niu+IbMt3hh5FuLVtpA+92V9U+0RwpwYjX48dDeVfAWMz9QsI1z4SMUPZmyb7cV2J\\noAcStdGLPhZGa0RSRxFm+KuoZRCWSJ65a8HYpR0zI8sKvTZaFrS+ItxtvALkMBL7\\ndsbdbTNtyPrdqYFhA7BNe7cisd5Avob01CMkV3aPwLFKtFdtS7WPLwwR0fXhOLZV\\nDiYe7Tu+NrVcQJe1QLjkek4DnaN0ph4Xyi/K0CW4FJZ4vXIUI99Z9FP0QKiEX7bN\\nXWyBchwwqFiE17PcSkLOLX0VUCIYdF0w6pj4AzNpSn8PY0jEg0FLbnfj+ZDfBhxl\\ncUvh0obhnxdd4BafqzWSJPpzhCwx3NjkuNA1464BcerCTy7XkNxPtYyTDfLWD12x\\nPVRKAqhm/z2yHyP93maRYY9R/Qvx7n5XJBFh+5w66e3Gvb+RaQQ8HcyJKbz+I/PJ\\ntSRRAm1ROTnCLdWzjzimbOT4agKgwG53HqeaRLzqteu+lTr64LH5ZZZkAUd9v+C9\\ncJb41OV3hHdP0+evTn471JU7YQlCYiQK+Ps04TsUX1MwRgoNq1+znk27PK7B1XUF\\n21sfF75JL4q7VsU/dpCU\\n=0m4k\\n-----END PGP SIGNATURE-----"
442
+
443
+ Note: strips commit message.
444
+
445
+ :param commit_cat_file_content: commit content as presented by ``git cat-file -p <commit-hash>``.
446
+ :returns: (tree-hash, commit-parents, author-info, committer-info, commit-signature, commit-message).
447
+ :raises GitExitingException: if required fields like ``tree``, ``author`` and ``committer`` are not found in the
448
+ commit contents.
449
+ """
450
+ # TODO: Make sure commit message and signature new-lines match the original commits.
451
+ # This can be achieved by deliberately creating commits and matching their commit hashes.
452
+ commit_parents: list[bytes] = []
453
+ curr_bytes_ptr = 0
454
+ tree_found, tree_val, curr_bytes_ptr = query_bytes_range(commit_cat_file_content, curr_bytes_ptr, b"tree", b" ",
455
+ b"\n", False)
456
+ if not tree_val:
457
+ raise GitExitingException("No tree found on commit", exit_code=ERR_DATA_FORMAT_ERR) from KeyError("tree")
458
+ # region collect parent commit id(s)
459
+ while True:
460
+ parent_found, parent_val, curr_bytes_ptr = query_bytes_range(commit_cat_file_content, curr_bytes_ptr, b"parent",
461
+ b" ", b"\n", False)
462
+ if not parent_found or not parent_val:
463
+ break
464
+ commit_parents.append(parent_val)
465
+ # endregion
466
+ author_found, author_val, curr_bytes_ptr = query_bytes_range(commit_cat_file_content, curr_bytes_ptr, b"author",
467
+ b" ", b"\n", False)
468
+ if not author_val:
469
+ raise GitExitingException("No author data found in commit", exit_code=ERR_DATA_FORMAT_ERR) \
470
+ from KeyError("author")
471
+ committer_found, committer_val, curr_bytes_ptr = query_bytes_range(commit_cat_file_content, curr_bytes_ptr,
472
+ b"committer", b" ", b"\n", False)
473
+ if not committer_val:
474
+ raise GitExitingException("No committer data found in commit", exit_code=ERR_DATA_FORMAT_ERR) \
475
+ from KeyError("committer")
476
+ gpg_sig_found, gpg_sig_val, curr_bytes_ptr = query_bytes_range(commit_cat_file_content, curr_bytes_ptr, b"gpgsig",
477
+ b" -----BEGIN PGP SIGNATURE-----",
478
+ b"-----END PGP SIGNATURE-----\n", True)
479
+ gpg_sigval = sanitize_sig_bytes(gpg_sig_val) if gpg_sig_val else None
480
+ ssh_sig_found, ssh_sig_val, curr_bytes_ptr = query_bytes_range(commit_cat_file_content, curr_bytes_ptr, b"gpgsig",
481
+ b" -----BEGIN SSH SIGNATURE-----",
482
+ b"-----END SSH SIGNATURE-----\n", True)
483
+ ssh_sigval = sanitize_sig_bytes(ssh_sig_val) if ssh_sig_val else None
484
+ curr_bytes_ptr += 1 # include \n as commit message starts after that.
485
+ commit_message = commit_cat_file_content[curr_bytes_ptr:]
486
+ return RawBytesValsOfCommit(tree_val, commit_parents, author_val, committer_val, gpg_sigval or ssh_sigval,
487
+ commit_message, )
488
+
489
+
490
+ def sanitize_sig_bytes(signature: bytes) -> bytes:
491
+ return b"\n".join(line.strip() for line in signature.splitlines())
492
+
493
+ def sanitize_gpg_signature(gpg_signature: bytes) -> GPGGitRawSignature:
494
+ return GPGGitRawSignature(sanitize_sig_bytes(gpg_signature))
495
+
496
+ def sanitize_ssh_signature(ssh_signature: bytes) -> SSHGitRawSignature:
497
+ return SSHGitRawSignature(sanitize_sig_bytes(ssh_signature))
498
+
499
+
500
+ def query_bytes_range(bytes_content: bytes, curr_bytes_ptr: int, key_to_query: bytes,
501
+ val_begin: bytes, val_end: bytes, keep_ends: bool) -> tuple[bool, bytes | None, int]:
502
+ """
503
+ Query the bytes content for value to a specific key. Is helpful to the caller either when key is found or when
504
+ not found by returning the next-pointer to look for.
505
+
506
+ :param bytes_content: contents to search keys into.
507
+ :param key_to_query: the key to query in the bytes content.
508
+ :param curr_bytes_ptr: integer index (or pointer) to start looking for the ``key_to_query``.
509
+ :param val_begin: the beginning bytes of the value.
510
+ :param val_end: the ending bytes of the value.
511
+ :param keep_ends: include the ``val_begin`` and ``val_end`` bytes in the returned and found value.
512
+ :returns: (found, value, pointer-after-value-ends) or (not-found, null, unchanged-passed-current-bytes-pointer)
513
+ """
514
+ interest_bytes = bytes_content[curr_bytes_ptr:]
515
+ if not interest_bytes.startswith(key_to_query):
516
+ return False, None, curr_bytes_ptr
517
+ interest_bytes = interest_bytes[len(key_to_query):]
518
+ val_start_index = interest_bytes.find(val_begin) # including val start
519
+ val_end_index = interest_bytes.find(val_end) + len(val_end) # including val end
520
+ curr_bytes_ptr += len(key_to_query)+val_end_index
521
+ if not keep_ends:
522
+ val_start_index += len(val_begin) # excluding val start
523
+ val_end_index -= len(val_end) # excluding val end
524
+ value = interest_bytes[val_start_index: val_end_index]
525
+ return True, value, curr_bytes_ptr
526
+
527
+
528
+ def query_line(key: bytes, line: bytes, kv_delim: bytes = b" ") -> tuple[bool, bytes]:
529
+ """
530
+ Query a line from stream for a particular key and return the found value till the line ends.
531
+
532
+ :param key: key to query.
533
+ :param line: line to search key into.
534
+ :param kv_delim: delimiter between the key and the value.
535
+ :returns: (found, found-value) or (not-found, line)
536
+ """
537
+ if line.startswith(key):
538
+ _, value = line.split(kv_delim, 1)
539
+ return True, value
540
+ else:
541
+ return False, line
542
+ # endregion
543
+
544
+
545
+ if __name__ == "__main__":
546
+ import gitbolt
547
+ import time
548
+
549
+ git = gitbolt.get_git_command()
550
+ # region GitSession approach
551
+ start = time.perf_counter()
552
+ with git.session(
553
+ cat_file1=["cat-file", "--batch"],
554
+ cat_file2=["cat-file", "--batch"],
555
+ mktree=["mktree", "--batch", "-z"]
556
+ ) as ses:
557
+ for mode_, sha_, name_ in cat_file_tree_data(ses.commands.cat_file1, b"HEAD^{tree}", True):
558
+ print(mode_, sha_, name_)
559
+ print("+" * 40)
560
+ print(cat_file_blob_content(ses.commands.cat_file2, b"9854cb4d432a881f59d38582791cf2636e7819d9"))
561
+
562
+ print("*"*40)
563
+ tree_of_head: list[bytes] = []
564
+ for tree_line in cat_file_tree_content(ses.commands.cat_file1, b"HEAD^{tree}"):
565
+ print(tree_line.decode())
566
+ tree_of_head.append(tree_line)
567
+ tree_of_head_1: list[bytes] = []
568
+ for tree_line in cat_file_tree_content(ses.commands.cat_file1, b"HEAD~1^{tree}"):
569
+ tree_of_head_1.append(tree_line)
570
+ # make tree
571
+ print("#"*40)
572
+ _tree_hash = mktree_tree_make(ses.commands.mktree, b"\0".join(tree_of_head))
573
+ print("head tree hash: ", _tree_hash)
574
+ print("#"*40)
575
+ _tree_hash_1 = mktree_tree_make(ses.commands.mktree, b"\0".join(tree_of_head_1))
576
+ print("head~1 tree hash: ", _tree_hash_1)
577
+
578
+ end = time.perf_counter()
579
+ print(f"Session Elapsed time: {end - start:0.4f} seconds")
580
+ # endregion
581
+
582
+ print("="*40)
583
+ # region Per-process call approach
584
+ start = time.perf_counter()
585
+ head_tree_out = git.subcmd_unchecked().run(["cat-file", "-p", "HEAD^{tree}"], text=False).stdout.splitlines()
586
+ for head_tree in head_tree_out:
587
+ print(head_tree)
588
+ print("+" * 40)
589
+ print(git.subcmd_unchecked().run(["cat-file", "-p", "9854cb4d432a881f59d38582791cf2636e7819d9"], text=False).stdout)
590
+ end = time.perf_counter()
591
+ print(f"Subcmd Elapsed time: {end - start:0.4f} seconds")
592
+
593
+ session = git.session(
594
+ cat_file=["cat-file", "--batch"],
595
+ for_each_ref_contains=["for-each-ref", "--stdin"],
596
+ rev_list_contains=["rev-list", "--stdin"],
597
+ )
598
+ with session as ses:
599
+ print(cat_file_commit_data(ses.commands.cat_file, b"d7d8d6f79017c5d574e3c4ac519c855b7cec33e2"))
600
+ print(cat_file_commit_data(ses.commands.cat_file, b"HEAD"))
601
+ print(single_shot_command(ses.commands.rev_list_contains, b"develop\n\n", False))
602
+ # print(single_shot_command(ses.commands.rev_list_contains, b"develop\n\n", False))
603
+ print(cat_file_commit_data(ses.commands.cat_file, b"a744fefd4eaf1a0139ae3c85f713a1a963563cc3"))
604
+ print("$"*40)
605
+ with session as ses:
606
+ print(cat_file_commit_data(ses.commands.cat_file, b"d7d8d6f79017c5d574e3c4ac519c855b7cec33e2"))
607
+ print(cat_file_commit_data(ses.commands.cat_file, b"HEAD"))
608
+ print(cat_file_commit_data(ses.commands.cat_file, b"a744fefd4eaf1a0139ae3c85f713a1a963563cc3"))
609
+ print(single_shot_command(ses.commands.rev_list_contains, b"develop\n\n", False))
610
+ # endregion