python-ship 0.1.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.
- python_ship/__init__.py +3 -0
- python_ship/__main__.py +3 -0
- python_ship/adapters.py +270 -0
- python_ship/cli.py +588 -0
- python_ship/compose.py +439 -0
- python_ship/config.py +368 -0
- python_ship/contracts.py +234 -0
- python_ship/init.py +369 -0
- python_ship/mutagen.py +89 -0
- python_ship/plugins.py +149 -0
- python_ship/production.py +69 -0
- python_ship/py.typed +0 -0
- python_ship/release.py +175 -0
- python_ship/runtime.py +83 -0
- python_ship/security.py +69 -0
- python_ship/servers.py +72 -0
- python_ship/services.py +353 -0
- python_ship/storage.py +151 -0
- python_ship/stubs.py +149 -0
- python_ship/templates/Dockerfile +52 -0
- python_ship/templates/check-python-security-floor.py +49 -0
- python_ship/templates/garage/Dockerfile +7 -0
- python_ship/templates/garage/garage.toml +15 -0
- python_ship/uv.py +76 -0
- python_ship-0.1.0.dist-info/METADATA +936 -0
- python_ship-0.1.0.dist-info/RECORD +30 -0
- python_ship-0.1.0.dist-info/WHEEL +5 -0
- python_ship-0.1.0.dist-info/entry_points.txt +2 -0
- python_ship-0.1.0.dist-info/licenses/LICENSE.md +21 -0
- python_ship-0.1.0.dist-info/top_level.txt +1 -0
python_ship/__init__.py
ADDED
python_ship/__main__.py
ADDED
python_ship/adapters.py
ADDED
|
@@ -0,0 +1,270 @@
|
|
|
1
|
+
"""Built-in framework adapters: plain ASGI or WSGI apps, Django, FastAPI and Flask."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import ast
|
|
6
|
+
from pathlib import Path
|
|
7
|
+
import re
|
|
8
|
+
|
|
9
|
+
from .config import ShipConfig
|
|
10
|
+
from .contracts import Interface
|
|
11
|
+
|
|
12
|
+
TARGET = re.compile(r"[A-Za-z_]\w*(?:\.[A-Za-z_]\w*)*:[A-Za-z_]\w*")
|
|
13
|
+
# Directories never searched when detecting a project's app module.
|
|
14
|
+
_SKIP = {".git", ".venv", "venv", "node_modules", "__pycache__", "dist", "build", "ship", "tests", ".tox"}
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
def module_file(project_root: Path, target: str) -> Path:
|
|
18
|
+
"""The file an import target refers to, at the project root or under ``src/``."""
|
|
19
|
+
relative = Path(*target.split(":", 1)[0].split(".")).with_suffix(".py")
|
|
20
|
+
direct = project_root / relative
|
|
21
|
+
return direct if direct.is_file() else project_root / "src" / relative
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
def _module_name(project_root: Path, path: Path) -> str:
|
|
25
|
+
relative = path.relative_to(project_root).with_suffix("")
|
|
26
|
+
parts = relative.parts[1:] if relative.parts[0] == "src" else relative.parts
|
|
27
|
+
return ".".join(parts)
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
def _bindings(path: Path) -> tuple[set[str], bool]:
|
|
31
|
+
try:
|
|
32
|
+
tree = ast.parse(path.read_text(encoding="utf-8"), filename=str(path))
|
|
33
|
+
except (OSError, SyntaxError, UnicodeDecodeError, ValueError):
|
|
34
|
+
return set(), False
|
|
35
|
+
names: set[str] = set()
|
|
36
|
+
wildcard = False
|
|
37
|
+
for node in tree.body:
|
|
38
|
+
if isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef, ast.ClassDef)):
|
|
39
|
+
names.add(node.name)
|
|
40
|
+
elif isinstance(node, (ast.Assign, ast.AnnAssign)):
|
|
41
|
+
targets = node.targets if isinstance(node, ast.Assign) else [node.target]
|
|
42
|
+
names.update(name.id for target in targets for name in ast.walk(target) if isinstance(name, ast.Name))
|
|
43
|
+
elif isinstance(node, (ast.Import, ast.ImportFrom)):
|
|
44
|
+
wildcard |= any(alias.name == "*" for alias in node.names)
|
|
45
|
+
names.update(alias.asname or alias.name.split(".")[0] for alias in node.names if alias.name != "*")
|
|
46
|
+
return names, wildcard
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
def target_problems(project_root: Path, target: str, label: str, example: str) -> list[str]:
|
|
50
|
+
"""Check an import target statically, without importing project code on the host."""
|
|
51
|
+
if not TARGET.fullmatch(target):
|
|
52
|
+
return [f"{label} must be a module:callable target, e.g. {example}."]
|
|
53
|
+
module = module_file(project_root, target)
|
|
54
|
+
if not module.is_file():
|
|
55
|
+
return [f"{label} module for {target!r} does not exist; expected {module.relative_to(project_root)}."]
|
|
56
|
+
try:
|
|
57
|
+
ast.parse(module.read_text(encoding="utf-8"), filename=str(module))
|
|
58
|
+
except SyntaxError as exc:
|
|
59
|
+
return [f"{label} module {module.relative_to(project_root)} has a syntax error at line {exc.lineno}: {exc.msg}."]
|
|
60
|
+
names, wildcard = _bindings(module)
|
|
61
|
+
callable_name = target.partition(":")[2]
|
|
62
|
+
if callable_name not in names and not wildcard:
|
|
63
|
+
return [f"{label} callable {callable_name!r} is not defined in {module.relative_to(project_root)}."]
|
|
64
|
+
return []
|
|
65
|
+
|
|
66
|
+
|
|
67
|
+
def python_files(project_root: Path, depth: int = 3) -> list[Path]:
|
|
68
|
+
"""Project Python files, shallowest first, skipping environments and build output."""
|
|
69
|
+
found: list[Path] = []
|
|
70
|
+
|
|
71
|
+
def walk(directory: Path, level: int) -> None:
|
|
72
|
+
try:
|
|
73
|
+
entries = sorted(directory.iterdir())
|
|
74
|
+
except OSError:
|
|
75
|
+
return
|
|
76
|
+
found.extend(entry for entry in entries if entry.suffix == ".py" and entry.is_file())
|
|
77
|
+
if level < depth:
|
|
78
|
+
for entry in entries:
|
|
79
|
+
if entry.is_dir() and entry.name not in _SKIP and not entry.name.startswith("."):
|
|
80
|
+
walk(entry, level + 1)
|
|
81
|
+
|
|
82
|
+
walk(project_root, 1)
|
|
83
|
+
return sorted(found, key=lambda path: (len(path.relative_to(project_root).parts), str(path)))
|
|
84
|
+
|
|
85
|
+
|
|
86
|
+
def callable_interface(project_root: Path, target: str) -> Interface | None:
|
|
87
|
+
"""Guess a plain callable's interface from its signature, without importing it.
|
|
88
|
+
|
|
89
|
+
``async def app(scope, receive, send)`` is ASGI; ``def app(environ, start_response)`` is WSGI.
|
|
90
|
+
"""
|
|
91
|
+
module = module_file(project_root, target)
|
|
92
|
+
name = target.partition(":")[2]
|
|
93
|
+
try:
|
|
94
|
+
tree = ast.parse(module.read_text(encoding="utf-8"), filename=str(module))
|
|
95
|
+
except (OSError, SyntaxError, UnicodeDecodeError, ValueError):
|
|
96
|
+
return None
|
|
97
|
+
for node in tree.body:
|
|
98
|
+
if isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef)) and node.name == name:
|
|
99
|
+
positional = len(node.args.posonlyargs) + len(node.args.args)
|
|
100
|
+
if isinstance(node, ast.AsyncFunctionDef) or positional == 3:
|
|
101
|
+
return "asgi"
|
|
102
|
+
if positional == 2:
|
|
103
|
+
return "wsgi"
|
|
104
|
+
return None
|
|
105
|
+
|
|
106
|
+
|
|
107
|
+
class GenericAdapter:
|
|
108
|
+
"""Serve any ASGI or WSGI callable; no web framework required."""
|
|
109
|
+
|
|
110
|
+
key = "generic"
|
|
111
|
+
label = "Plain ASGI or WSGI app (no framework)"
|
|
112
|
+
|
|
113
|
+
def detect(self, project_root: Path) -> bool:
|
|
114
|
+
return True
|
|
115
|
+
|
|
116
|
+
def default_app(self, project_root: Path) -> str | None:
|
|
117
|
+
for module in ("main", "app", "asgi", "wsgi", "server"):
|
|
118
|
+
path = project_root / f"{module}.py"
|
|
119
|
+
if path.is_file():
|
|
120
|
+
names, _ = _bindings(path)
|
|
121
|
+
for name in ("app", "application"):
|
|
122
|
+
if name in names:
|
|
123
|
+
return f"{module}:{name}"
|
|
124
|
+
return None
|
|
125
|
+
|
|
126
|
+
def interface(self, config: ShipConfig, project_root: Path) -> Interface:
|
|
127
|
+
# Anything that isn't recognizably a WSGI function is treated as ASGI, the default.
|
|
128
|
+
return callable_interface(project_root, config.app) or "asgi"
|
|
129
|
+
|
|
130
|
+
def validate(self, config: ShipConfig, project_root: Path) -> list[str]:
|
|
131
|
+
return target_problems(project_root, config.app, "App", "main:app")
|
|
132
|
+
|
|
133
|
+
def server_target(self, config: ShipConfig) -> str:
|
|
134
|
+
return config.app
|
|
135
|
+
|
|
136
|
+
def console_commands(self) -> dict[str, list[str]]:
|
|
137
|
+
return {}
|
|
138
|
+
|
|
139
|
+
def release_commands(self, config: ShipConfig) -> list[list[str]]:
|
|
140
|
+
return []
|
|
141
|
+
|
|
142
|
+
|
|
143
|
+
class DjangoAdapter:
|
|
144
|
+
key = "django"
|
|
145
|
+
label = "Django"
|
|
146
|
+
|
|
147
|
+
def detect(self, project_root: Path) -> bool:
|
|
148
|
+
return (project_root / "manage.py").is_file()
|
|
149
|
+
|
|
150
|
+
def default_app(self, project_root: Path) -> str | None:
|
|
151
|
+
manage = project_root / "manage.py"
|
|
152
|
+
package = None
|
|
153
|
+
if manage.is_file():
|
|
154
|
+
match = re.search(r"""DJANGO_SETTINGS_MODULE['"]\s*,\s*['"]([\w.]+)\.settings['"]""",
|
|
155
|
+
manage.read_text(encoding="utf-8", errors="replace"))
|
|
156
|
+
package = match.group(1) if match else None
|
|
157
|
+
# ASGI first: Django serves both, and ASGI also covers async views and websockets.
|
|
158
|
+
for kind in ("asgi", "wsgi"):
|
|
159
|
+
if package and module_file(project_root, f"{package}.{kind}:application").is_file():
|
|
160
|
+
return f"{package}.{kind}:application"
|
|
161
|
+
for kind in ("asgi", "wsgi"):
|
|
162
|
+
for path in python_files(project_root):
|
|
163
|
+
if path.name == f"{kind}.py" and "application" in _bindings(path)[0]:
|
|
164
|
+
return f"{_module_name(project_root, path)}:application"
|
|
165
|
+
return None
|
|
166
|
+
|
|
167
|
+
def interface(self, config: ShipConfig, project_root: Path) -> Interface:
|
|
168
|
+
return "wsgi" if config.app.partition(":")[0].rsplit(".", 1)[-1] == "wsgi" else "asgi"
|
|
169
|
+
|
|
170
|
+
def validate(self, config: ShipConfig, project_root: Path) -> list[str]:
|
|
171
|
+
problems = []
|
|
172
|
+
if not self.detect(project_root):
|
|
173
|
+
problems.append("The Django adapter requires manage.py in the project root.")
|
|
174
|
+
problems.extend(target_problems(project_root, config.app, "Django app", "project.asgi:application"))
|
|
175
|
+
return problems
|
|
176
|
+
|
|
177
|
+
def server_target(self, config: ShipConfig) -> str:
|
|
178
|
+
return config.app
|
|
179
|
+
|
|
180
|
+
def console_commands(self) -> dict[str, list[str]]:
|
|
181
|
+
return {"manage": ["python", "manage.py"]}
|
|
182
|
+
|
|
183
|
+
def release_commands(self, config: ShipConfig) -> list[list[str]]:
|
|
184
|
+
commands = [["python", "manage.py", "check", "--deploy"]]
|
|
185
|
+
if config.django_collectstatic:
|
|
186
|
+
commands.append(["python", "manage.py", "collectstatic", "--noinput"])
|
|
187
|
+
return commands
|
|
188
|
+
|
|
189
|
+
|
|
190
|
+
def _framework_apps(project_root: Path, module: str, constructor: str) -> list[tuple[Path, str]]:
|
|
191
|
+
"""Modules that bind ``name = Constructor(...)`` for a framework, shallowest first."""
|
|
192
|
+
pattern = re.compile(rf"^([A-Za-z_]\w*)\s*(?::[^=\n]+)?=\s*(?:{module}\.)?{constructor}\(", re.MULTILINE)
|
|
193
|
+
found = []
|
|
194
|
+
for path in python_files(project_root):
|
|
195
|
+
try:
|
|
196
|
+
source = path.read_text(encoding="utf-8", errors="replace")
|
|
197
|
+
except OSError:
|
|
198
|
+
continue
|
|
199
|
+
if module not in source:
|
|
200
|
+
continue
|
|
201
|
+
match = pattern.search(source)
|
|
202
|
+
if match:
|
|
203
|
+
found.append((path, match.group(1)))
|
|
204
|
+
return found
|
|
205
|
+
|
|
206
|
+
|
|
207
|
+
class FastAPIAdapter:
|
|
208
|
+
key = "fastapi"
|
|
209
|
+
label = "FastAPI"
|
|
210
|
+
|
|
211
|
+
def detect(self, project_root: Path) -> bool:
|
|
212
|
+
return bool(_framework_apps(project_root, "fastapi", "FastAPI"))
|
|
213
|
+
|
|
214
|
+
def default_app(self, project_root: Path) -> str | None:
|
|
215
|
+
found = _framework_apps(project_root, "fastapi", "FastAPI")
|
|
216
|
+
return f"{_module_name(project_root, found[0][0])}:{found[0][1]}" if found else None
|
|
217
|
+
|
|
218
|
+
def interface(self, config: ShipConfig, project_root: Path) -> Interface:
|
|
219
|
+
return "asgi"
|
|
220
|
+
|
|
221
|
+
def validate(self, config: ShipConfig, project_root: Path) -> list[str]:
|
|
222
|
+
return target_problems(project_root, config.app, "FastAPI app", "app.main:app")
|
|
223
|
+
|
|
224
|
+
def server_target(self, config: ShipConfig) -> str:
|
|
225
|
+
return config.app
|
|
226
|
+
|
|
227
|
+
def console_commands(self) -> dict[str, list[str]]:
|
|
228
|
+
return {}
|
|
229
|
+
|
|
230
|
+
def release_commands(self, config: ShipConfig) -> list[list[str]]:
|
|
231
|
+
return []
|
|
232
|
+
|
|
233
|
+
|
|
234
|
+
class FlaskAdapter:
|
|
235
|
+
"""Flask is WSGI, so it runs on Gunicorn (the suggestion) or Granian."""
|
|
236
|
+
|
|
237
|
+
key = "flask"
|
|
238
|
+
label = "Flask"
|
|
239
|
+
|
|
240
|
+
def detect(self, project_root: Path) -> bool:
|
|
241
|
+
return bool(_framework_apps(project_root, "flask", "Flask"))
|
|
242
|
+
|
|
243
|
+
def default_app(self, project_root: Path) -> str | None:
|
|
244
|
+
found = _framework_apps(project_root, "flask", "Flask")
|
|
245
|
+
return f"{_module_name(project_root, found[0][0])}:{found[0][1]}" if found else None
|
|
246
|
+
|
|
247
|
+
def interface(self, config: ShipConfig, project_root: Path) -> Interface:
|
|
248
|
+
return "wsgi"
|
|
249
|
+
|
|
250
|
+
def validate(self, config: ShipConfig, project_root: Path) -> list[str]:
|
|
251
|
+
return target_problems(project_root, config.app, "Flask app", "app:app")
|
|
252
|
+
|
|
253
|
+
def server_target(self, config: ShipConfig) -> str:
|
|
254
|
+
return config.app
|
|
255
|
+
|
|
256
|
+
def app_environment(self, config: ShipConfig) -> dict[str, str]:
|
|
257
|
+
# Lets `ship flask ...` (and `flask` inside the container) find the app.
|
|
258
|
+
return {"FLASK_APP": config.app}
|
|
259
|
+
|
|
260
|
+
def console_commands(self) -> dict[str, list[str]]:
|
|
261
|
+
return {"flask": ["flask"]}
|
|
262
|
+
|
|
263
|
+
def release_commands(self, config: ShipConfig) -> list[list[str]]:
|
|
264
|
+
return []
|
|
265
|
+
|
|
266
|
+
|
|
267
|
+
# Detection order for `ship init`: the most specific framework first, the generic adapter last.
|
|
268
|
+
BUILTIN_ADAPTERS = {
|
|
269
|
+
adapter.key: adapter for adapter in (DjangoAdapter(), FastAPIAdapter(), FlaskAdapter(), GenericAdapter())
|
|
270
|
+
}
|