git-asgi 0.1__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.
git_asgi/pktline.py ADDED
@@ -0,0 +1,242 @@
1
+ from enum import Enum, StrEnum
2
+ from warnings import warn
3
+
4
+ PREFIX = 4
5
+ """
6
+ Length of the pkt-line prefix.
7
+ """
8
+
9
+
10
+ def prefix(length: int) -> bytes:
11
+ """
12
+ Format a given length into a pkt-len, i.e. a 4-byte long hexadecimal prefix
13
+ for a Git pkt-line.
14
+
15
+ Arguments:
16
+ length: the length to format.
17
+
18
+ Raises:
19
+ TypeError: if `length` is not an integer.
20
+ ValueError: if `length` is outside the range 0 - 65520.
21
+
22
+ Returns:
23
+ the 4-byte hexadecimal length prefix for a Git pkt-line.
24
+ """
25
+ if not isinstance(length, int):
26
+ raise TypeError("length must be an integer")
27
+
28
+ if length < 0:
29
+ raise ValueError("length must be positive")
30
+
31
+ # Implementations MUST NOT send pkt-line whose length exceeds 65520
32
+ # (65516 bytes of payload + 4 bytes of length data);
33
+ # https://git-scm.com/docs/protocol-common#_pkt_line_format
34
+ if length > 65520:
35
+ raise ValueError("length must not exceed 65520")
36
+
37
+ # the first four bytes indicates the total length of the line in hexadecimal,
38
+ # the pkt-len includes the 4 bytes used to contain the length’s hexadecimal representation;
39
+ # https://git-scm.com/docs/protocol-common#_pkt_line_format
40
+ # https://docs.python.org/3/library/string.html#format-specification-mini-language
41
+ template = f"{{:0>{PREFIX}x}}"
42
+
43
+ return template.format(length).encode()
44
+
45
+
46
+ def pktline(payload: bytes) -> bytes:
47
+ """
48
+ Serialize a payload into the Git pkt-line format.
49
+
50
+ Arguments:
51
+ payload: the payload of the pkt-line.
52
+
53
+ Warns:
54
+ RuntimeWarning:
55
+ when an empty pkt-line `0004` is returned, as implementations
56
+ SHOULD NOT send them.
57
+
58
+ - https://git-scm.com/docs/protocol-common#_pkt_line_format
59
+
60
+ Raises:
61
+ ValueError: if the payload is empty.
62
+
63
+ Returns:
64
+ the payload prefixed with a 4-byte hexadecimal length prefix.
65
+ """
66
+ if (length := len(payload)) == 0:
67
+ # empty pkt-line
68
+ warn("payload is empty", RuntimeWarning)
69
+
70
+ return prefix(length + PREFIX) + payload
71
+
72
+
73
+ def payload(pktline: bytes) -> None | bytes:
74
+ """
75
+ Get the payload of a pkt-line.
76
+
77
+ Arguments:
78
+ pktline: the pkt-line data.
79
+
80
+ Raises:
81
+ ValueError: when the prefix is invalid.
82
+
83
+ Returns:
84
+ `None` if the prefix holds an integer lower than the prefix length of 4,
85
+ else the payload.
86
+ """
87
+ # get prefix
88
+ prefix = pktline[:PREFIX]
89
+
90
+ if len(prefix) < PREFIX:
91
+ raise ValueError("invalid pkt-line prefix")
92
+
93
+ # convert to integer
94
+ length = int(prefix, base=16)
95
+
96
+ if length < PREFIX:
97
+ # special packets don't have a payload
98
+ return
99
+ else:
100
+ # no special packet and valid prefix,
101
+ # get payload
102
+ payload = pktline[PREFIX:length]
103
+
104
+ if len(payload) < length - PREFIX:
105
+ raise ValueError("incomplete pkt-line payload")
106
+
107
+ return payload
108
+
109
+
110
+ class Service(StrEnum):
111
+ """
112
+ Commands for exchanging repository state information.
113
+
114
+ Can be `git-receive-pack`, `git-upload-pack` or `git-upload-archive`.
115
+
116
+ - https://git-scm.dev/book/en/v2/Git-Internals-Transfer-Protocols
117
+ - https://git-scm.com/docs/git-shell#_commands
118
+ """
119
+
120
+ UPLOAD = "git-upload-pack"
121
+ """
122
+ Learns what objects the other side is missing, and sends them after packing.
123
+ """
124
+
125
+ RECEIVE = "git-receive-pack"
126
+ """
127
+ Updates the repository with information fed from the remote end.
128
+ """
129
+
130
+ ARCHIVE = "git-upload-archive"
131
+ """
132
+ Sends a generated archive to the remote end.
133
+ """
134
+
135
+ @property
136
+ def pktline(self) -> bytes:
137
+ """
138
+ Get the pkt-line representation.
139
+
140
+ Clients MUST verify the first pkt-line is `# service=$service` and
141
+ servers MUST set `$service` to be the request parameter value.
142
+ Servers SHOULD include an LF at the end of this line.
143
+
144
+ - https://git-scm.com/docs/http-protocol#_smart_server_response
145
+
146
+ It is only required for a smart Git HTTP `GET` request and
147
+ for the Git protocol versions v0 and v1 and for the
148
+ `git-upload-pack` and `git-receive-pack` services, so explicitely
149
+ not for the `git-archive-pack` service only request in a
150
+ smart Git HTTP `POST` response.
151
+
152
+ - https://git-scm.com/docs/git-http-backend#Documentation/git-http-backend.txt-httpuploadarchive
153
+
154
+ Raises:
155
+ NotImplementedError: when called on the `ARCHIVE` service.
156
+
157
+ Returns:
158
+ the pkt-line with payload `# service={name}\\n`.
159
+ """
160
+ if self == self.ARCHIVE:
161
+ raise NotImplementedError(
162
+ "service pktline is only defined for "
163
+ "smart Git HTTP protocol v0/v1, "
164
+ f"and {self.ARCHIVE} only for v2"
165
+ )
166
+
167
+ return pktline(f"# service={self}\n".encode())
168
+
169
+
170
+ class Version(Enum):
171
+ """
172
+ Git smart HTTP protocol versions.
173
+ """
174
+
175
+ V1 = 1
176
+ """
177
+ Git smart HTTP protocol version 1.
178
+ """
179
+
180
+ V2 = 2
181
+ """
182
+ Git smart HTTP protocol version 2.
183
+ """
184
+
185
+ @property
186
+ def pktline(self) -> bytes:
187
+ """
188
+ Get the pkt-line representation.
189
+
190
+ It reads `version 1` if `version=1` was sent as an Extra Parameter.
191
+
192
+ - https://git-scm.com/docs/http-protocol#_smart_server_response
193
+
194
+ Similarly, it reads `version 2` for `version=2`.
195
+
196
+ - https://git-scm.com/docs/protocol-v2#_http_transport
197
+
198
+ Returns:
199
+ the pkt-line with payload `version {index}\\n`.
200
+ """
201
+ return pktline(f"version {self.value}\n".encode())
202
+
203
+
204
+ class Pkt(Enum):
205
+ """
206
+ Special packets for pkt-line framing.
207
+ """
208
+
209
+ # TODO: check for other versions than 2
210
+
211
+ FLUSH = 0
212
+ """
213
+ Flush Packet (flush-pkt).
214
+
215
+ Indicates the end of a message.
216
+ """
217
+
218
+ DELIMITER = 1
219
+ """
220
+ Delimiter Packet (delim-pkt).
221
+
222
+ Separates sections of a message.
223
+ """
224
+
225
+ RESPONSE_END = 2
226
+ """
227
+ Response End Packet (response-end-pkt).
228
+
229
+ Indicates the end of a response for stateless connections.
230
+ """
231
+
232
+ @property
233
+ def pktline(self) -> bytes:
234
+ """
235
+ Get the pkt-line representation.
236
+
237
+ - https://git-scm.com/docs/protocol-v2#_packet_line_framing
238
+
239
+ Returns:
240
+ the prefix holding the index without any payload.
241
+ """
242
+ return prefix(self.value)
git_asgi/py.typed ADDED
File without changes
git_asgi/utils.py ADDED
@@ -0,0 +1,94 @@
1
+ from os import R_OK, X_OK, access
2
+ from pathlib import Path
3
+ from re import ASCII, Pattern
4
+ from re import compile as re_compile
5
+ from shutil import which
6
+
7
+
8
+ def regex(pattern: str | bytes) -> Pattern:
9
+ """
10
+ Compile a regular expression pattern for git request paths, queries and
11
+ Extra Parameters.
12
+
13
+ Arguments:
14
+ pattern: the pattern to compile.
15
+
16
+ Returns:
17
+ the compiled pattern.
18
+ """
19
+ return re_compile(pattern, flags=ASCII)
20
+
21
+
22
+ def check_git_executable() -> None:
23
+ """
24
+ Check the presence of the `git` executable with `shutils.which`.
25
+
26
+ Raises:
27
+ RuntimeError: when no `git` executable was found.
28
+ """
29
+ if which("git") is None:
30
+ raise RuntimeError("no 'git' executable found")
31
+
32
+
33
+ def is_readable(path: Path) -> bool:
34
+ """
35
+ Check if the real user has read access to the given path.
36
+
37
+ UNIX only.
38
+
39
+ Arguments:
40
+ path: the path to check for read access.
41
+
42
+ Returns:
43
+ `True` if the path is readable, else `False`.
44
+ """
45
+ return access(path, R_OK)
46
+
47
+
48
+ def is_writable(path: Path) -> bool:
49
+ """
50
+ Check if the real user has write access within the given path.
51
+
52
+ UNIX only.
53
+
54
+ Arguments:
55
+ path: the path to check for write access.
56
+
57
+ Returns:
58
+ `True` if path contents is writeable, else `False`.
59
+ """
60
+ return access(path, X_OK)
61
+
62
+
63
+ def check_base(path: str | Path) -> Path:
64
+ """
65
+ Check if a given base path is ready for Git operations.
66
+
67
+ Checks existence, being a directory, read and write permissions.
68
+
69
+ Ensure the given path to be of type `pathlib.Path`, absolute and resolved.
70
+
71
+ Arguments:
72
+ path: the base path to check.
73
+
74
+ Raises:
75
+ RuntimeError: when any of the checks failes.
76
+
77
+ Returns:
78
+ the absolute and resolved path.
79
+ """
80
+ path = Path(path).absolute().resolve()
81
+
82
+ if not path.exists():
83
+ raise RuntimeError(f"{path}: no such directory")
84
+
85
+ if not path.is_dir():
86
+ raise RuntimeError(f"{path}: not a directory")
87
+
88
+ if not is_readable(path):
89
+ raise RuntimeError(f"{path}: not readable")
90
+
91
+ if not is_writable(path):
92
+ raise RuntimeError(f"{path}: not writable")
93
+
94
+ return path
@@ -0,0 +1,167 @@
1
+ Metadata-Version: 2.4
2
+ Name: git-asgi
3
+ Version: 0.1
4
+ Summary: Git HTTP server as ASGI middleware according to spec.
5
+ Author-email: Jakob Zahn <jakob.zahn@mailbox.org>
6
+ Maintainer-email: Jakob Zahn <jakob.zahn@mailbox.org>
7
+ License-Expression: AGPL-3.0-only
8
+ Project-URL: documentation, https://codeberg.org/jbdyn/git-asgi/src/branch/main/README.md
9
+ Project-URL: source, https://codeberg.org/jbdyn/git-asgi
10
+ Project-URL: issues, https://codeberg.org/jbdyn/git-asgi/issues
11
+ Project-URL: changelog, https://codeberg.org/jbdyn/git-asgi/src/branch/main/CHANGELOG.md
12
+ Keywords: asgi,middleware,application,git,http,server
13
+ Classifier: Development Status :: 3 - Alpha
14
+ Classifier: Programming Language :: Python :: 3
15
+ Classifier: Programming Language :: Python :: 3.11
16
+ Classifier: Programming Language :: Python :: 3.12
17
+ Classifier: Programming Language :: Python :: 3.13
18
+ Classifier: Programming Language :: Python :: 3.14
19
+ Classifier: Operating System :: Unix
20
+ Classifier: Typing :: Typed
21
+ Classifier: Topic :: Software Development :: Version Control :: Git
22
+ Classifier: Topic :: Internet :: WWW/HTTP :: WSGI :: Middleware
23
+ Classifier: Topic :: Internet :: WWW/HTTP :: WSGI :: Application
24
+ Requires-Python: >=3.11
25
+ Description-Content-Type: text/markdown
26
+ License-File: LICENSE
27
+ Requires-Dist: asgiref
28
+ Requires-Dist: typing-extensions
29
+ Dynamic: license-file
30
+
31
+ # git-asgi
32
+
33
+ > Git HTTP server as ASGI middleware according to spec.
34
+
35
+
36
+ ## Features
37
+
38
+ - [x] ASGI 3 middleware with ASGI 2 application compatibility
39
+ - [x] ready-to-use ASGI 3 application included
40
+ - [x] ready-to-use within ASGI frameworks
41
+ - [x] dumb Git HTTP protocol
42
+ - [x] smart Git HTTP protocol, optionally supporting dumb Git HTTP protocol requests
43
+ - [x] Git archive creation
44
+ - [x] enabling and disabling of reading, writing or archiving
45
+ - [x] compatible with both SHA1 and SHA256 repositories
46
+ - [x] flexible and attachable logging formatting
47
+ - [ ] custom server-side Git hooks
48
+ - [ ] fully tested
49
+ - [x] fully documented
50
+ - [x] fully typed
51
+ - [x] minimal dependencies: just the Python standard library, `asgiref` and `typing-extensions`
52
+ - [x] handcrafted with love ❤️, no AI has ever touched this repo
53
+
54
+
55
+ ## Package
56
+
57
+ The package is named `git_asgi` and [available on PyPI](https://pypi.org/project/git_asgi) for your favorite Python package manager to download.
58
+
59
+
60
+ ## Usage
61
+
62
+ ### ASGI Server
63
+
64
+ The ASGI application is named `app`, located in the [`git_asgi.app`](./src/git_asgi/app.py) Python module and can be customized via optional environment variables with carefully chosen defaults.
65
+
66
+ ```sh
67
+ GIT_ASGI_BASE=/path/to/repos \
68
+ GIT_ASGI_LOGGER=base.logger.name \
69
+ GIT_ASGI_LEVEL=git-logger-logging-level \
70
+ GIT_ASGI_FORMAT=git-request-logger-str-format \
71
+ GIT_ASGI_SMART=0-or-1 \
72
+ GIT_ASGI_DUMB=0-or-1 \
73
+ GIT_ASGI_UPLOAD=0-or-1 \
74
+ GIT_ASGI_RECEIVE=0-or-1 \
75
+ GIT_ASGI_ARCHIVE=0-or-1 \
76
+ GIT_ASGI_REQUEST=request-timeout-in-seconds \
77
+ GIT_ASGI_OVERLOAD=overload-timeout-in-seconds \
78
+ GIT_ASGI_CHUNK=chunk-size-in-bytes \
79
+ SERVER [OPTIONS] git_asgi.app:app
80
+ ```
81
+
82
+ The term `SERVER` refers to your ASGI server of choice.
83
+
84
+ As the used `GitMiddleware` ASGI middleware needs an ASGI application, a small one is defined to support the `lifespan` protocol and to answer every HTTP request not handled by the `GitMiddleware` ASGI middleware with a `403 FORBIDDEN` HTTP response.
85
+
86
+
87
+ ### ASGI Framework
88
+
89
+ The ASGI middleware is named `GitMiddleware`, located in the [`git_asgi.middleware`](./src/git_asgi/middleware.py) Python module and can be used analogously to this pseudocode:
90
+
91
+ ```python
92
+ from asgi_framework import FrameworkApp
93
+ from git_asgi.middleware import GitMiddleware
94
+
95
+ # initialize ASGI framework app
96
+ app = FrameworkApp()
97
+
98
+ # extend app ...
99
+
100
+ # define mandatory base path
101
+ base = "/path/to/repos"
102
+
103
+ # add ASGI Git middleware alongside configuration arguments
104
+ # to ASGI framework app
105
+ app.add_middleware(GitMiddleware, base=base, **kwargs)
106
+
107
+ # run app ...
108
+ ```
109
+
110
+ Please refer to the documentation of your ASGI framework of choice on how to include an ASGI middleware.
111
+
112
+ If you need to align the app routes with the ones `GitMiddleware` uses, you will find them defined as regular expressions in the same [`git_asgi.middleware`](./src/git_asgi/middleware.py) Python module as well.
113
+
114
+
115
+ ## Development
116
+
117
+ This repository follows the [Python packaging standard](https://packaging.python.org/en/latest/) with a [`pyproject.toml`](./pyproject.toml) Python project configuration file.
118
+
119
+ Please refer to the documentation of your Python package manager of choice on how to install a possibly editable Python package from your obtained copy of the source code.
120
+
121
+ There is a `dev` dependency group defined, which you want to also install if you plan on developing on the code base.
122
+
123
+ After successful installation of all dependencies, you are able to run
124
+
125
+ ```
126
+ prek install
127
+ ```
128
+
129
+ to install pre-commit Git hooks helping with adhering to the code quality and style.
130
+
131
+
132
+ ## AI
133
+
134
+ This repository is featuring only handcrafted lines of code and text.
135
+
136
+ No AI will ever be used to change its content.
137
+
138
+ No change requests with AI-written code will be accepted.
139
+
140
+ Why?
141
+ Despite being an arguably useful tool, AI comes with arguably unacceptable aspects:
142
+
143
+ - licensing: inferenced code is partially stolen code
144
+ - footprint: hugely negative environmental impact
145
+ - foresight: no concept of understanding fundamental ideas of a code base
146
+ - quality: hallucinations and tendency to extremely wordy output
147
+
148
+
149
+ ## Windows
150
+
151
+ No special effort was put into making this software work on Windows.
152
+
153
+ There are a few lines of code which work on UNIX only.
154
+ However, this is considered to be a rare issue, since the ASGI middleware could be run in UNIX containers or in the Windows Subsystem for Linux (WSL) natively.
155
+
156
+ If you really need to run this code on bare Windows, test it, change it and make it available to the public as per the AGPL-3.0-only license.
157
+ If you think that your changes will be a beneficial contribution to the project, feel free to open a change request.
158
+
159
+
160
+ ## Changelog
161
+
162
+ Project changes are documented in [CHANGELOG.md](./CHANGELOG.md)
163
+
164
+
165
+ ## License
166
+
167
+ [AGPL-3.0-only](./LICENSE)
@@ -0,0 +1,11 @@
1
+ git_asgi/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
2
+ git_asgi/app.py,sha256=15BgUHobFH4DqM7iPXSfQqntqQ9BRLQyUbCHe7Fk8Dg,5065
3
+ git_asgi/middleware.py,sha256=cRYYSfec4GdCqsawLVzJEYaNmFNT120CsPX5UoV3lZo,51720
4
+ git_asgi/pktline.py,sha256=yKhgzQ-xhCI-Mrz2FI3yAjy-RCsl0GGGanEmZacLw5U,6332
5
+ git_asgi/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
6
+ git_asgi/utils.py,sha256=poW9E_mGCT_FRK9a_KrzZFkE9dMo0qY4PjcRY_FWTsY,2175
7
+ git_asgi-0.1.dist-info/licenses/LICENSE,sha256=DZak_2itbUtvHzD3E7GNUYSRK6jdOJ-GqncQ2weavLA,34523
8
+ git_asgi-0.1.dist-info/METADATA,sha256=lT7RTBs1Kr0BIITDQVBu9nDcaXutgqiveXXE7d-uRLI,6044
9
+ git_asgi-0.1.dist-info/WHEEL,sha256=mOdXR9C3wMVov7cSY8PY-XCzo3SmmWCHvGQr5csJoao,91
10
+ git_asgi-0.1.dist-info/top_level.txt,sha256=ONyEklRtShRRCsxVY3xqwKks5vnmtOilKE018p7ujVM,9
11
+ git_asgi-0.1.dist-info/RECORD,,
@@ -0,0 +1,5 @@
1
+ Wheel-Version: 1.0
2
+ Generator: setuptools (84.2.1)
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
5
+