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
|
@@ -0,0 +1,369 @@
|
|
|
1
|
+
"""`ship init`: pick services, write ship.json and publish the ship/ directory."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from dataclasses import dataclass, replace
|
|
6
|
+
import json
|
|
7
|
+
from pathlib import Path
|
|
8
|
+
import re
|
|
9
|
+
import sys
|
|
10
|
+
|
|
11
|
+
import typer
|
|
12
|
+
|
|
13
|
+
from . import __version__
|
|
14
|
+
from .compose import app_interface, build_compose
|
|
15
|
+
from .config import (
|
|
16
|
+
GROUPS_SUPPORTING_ADDITIONAL_INSTANCES,
|
|
17
|
+
INSTANCE_NAME,
|
|
18
|
+
SILO_IMAGES,
|
|
19
|
+
AdditionalService,
|
|
20
|
+
ConfigError,
|
|
21
|
+
ShipConfig,
|
|
22
|
+
)
|
|
23
|
+
from .contracts import FrameworkAdapter
|
|
24
|
+
from .plugins import Registry, load_extensions
|
|
25
|
+
from .security import DEFAULT_PYTHON, problem_with
|
|
26
|
+
from .stubs import asset_stub_problem, publish_stubs, server_stub_problem, stub_version_warning
|
|
27
|
+
from .uv import require_uv
|
|
28
|
+
|
|
29
|
+
NONE = "none"
|
|
30
|
+
# Groups `ship init` asks about, in order, with the label used in its prompt.
|
|
31
|
+
GROUPS = {
|
|
32
|
+
"database": "database",
|
|
33
|
+
"cache": "cache",
|
|
34
|
+
"broker": "message broker",
|
|
35
|
+
"tasks": "background task queue",
|
|
36
|
+
"storage": "object storage",
|
|
37
|
+
"search": "search engine",
|
|
38
|
+
"mail": "mail capture service",
|
|
39
|
+
"testing": "browser testing driver",
|
|
40
|
+
"frontend": "frontend toolchain",
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
DOCKERIGNORE = (
|
|
44
|
+
".env\n.env.*\n!.env.example\n"
|
|
45
|
+
"**/.env\n**/.env.*\n**/.venv\n**/__pycache__\n"
|
|
46
|
+
"**/*.pem\n**/*.key\n**/id_rsa\n**/id_ed25519\nsecrets/\n"
|
|
47
|
+
"node_modules/\n**/node_modules/\nstaticfiles/\n"
|
|
48
|
+
".npmrc\n**/.npmrc\nauth.json\n**/auth.json\n"
|
|
49
|
+
".git\ndist/\nship/docker-compose.generated.yml\nship/docker-compose.production.yml\n"
|
|
50
|
+
)
|
|
51
|
+
# Re-applied as the file's last lines before every production build, so a hand-edited
|
|
52
|
+
# .dockerignore can't re-include a secret or an earlier release into the next image.
|
|
53
|
+
RELEASE_IGNORE_GUARD = (
|
|
54
|
+
"# python-ship release guard\n"
|
|
55
|
+
".env\n.env.*\n**/.env\n**/.env.*\n"
|
|
56
|
+
"dist/ship/\n.npmrc\n**/.npmrc\nauth.json\n**/auth.json\n"
|
|
57
|
+
)
|
|
58
|
+
GITIGNORE = (
|
|
59
|
+
"/.env.production",
|
|
60
|
+
"/dist/ship/",
|
|
61
|
+
"/ship/docker-compose.generated.yml",
|
|
62
|
+
"/ship/docker-compose.production.yml",
|
|
63
|
+
)
|
|
64
|
+
|
|
65
|
+
VITE_SNIPPET = """\
|
|
66
|
+
const port = Number(process.env.VITE_PORT ?? 5173);
|
|
67
|
+
|
|
68
|
+
export default defineConfig({
|
|
69
|
+
// ...
|
|
70
|
+
server: {
|
|
71
|
+
host: '0.0.0.0', // bind inside the container, not just its loopback
|
|
72
|
+
port, // the port Ship publishes on the host
|
|
73
|
+
strictPort: true, // fail fast instead of silently picking an unpublished port
|
|
74
|
+
origin: `http://localhost:${port}`, // asset URLs for pages your Python app renders
|
|
75
|
+
},
|
|
76
|
+
});"""
|
|
77
|
+
|
|
78
|
+
|
|
79
|
+
@dataclass
|
|
80
|
+
class InitOptions:
|
|
81
|
+
app: str | None = None
|
|
82
|
+
framework: str | None = None
|
|
83
|
+
server: str | None = None
|
|
84
|
+
python: str | None = None
|
|
85
|
+
selections: dict[str, str | None] | None = None
|
|
86
|
+
silo_image: str | None = None
|
|
87
|
+
node_assets: bool | None = None
|
|
88
|
+
force: bool = False
|
|
89
|
+
interactive: bool = False
|
|
90
|
+
|
|
91
|
+
|
|
92
|
+
def _article(noun: str) -> str:
|
|
93
|
+
return "an" if noun[:1].lower() in "aeiou" else "a"
|
|
94
|
+
|
|
95
|
+
|
|
96
|
+
def interactive_terminal() -> bool:
|
|
97
|
+
return sys.stdin.isatty() and sys.stdout.isatty()
|
|
98
|
+
|
|
99
|
+
|
|
100
|
+
def select(label: str, choices: dict[str, str], default: str | None = None) -> str:
|
|
101
|
+
"""A numbered picker; accepts the number, the key or the label."""
|
|
102
|
+
keys = list(choices)
|
|
103
|
+
default = default if default in choices else keys[0]
|
|
104
|
+
typer.echo(f"\n{label}:")
|
|
105
|
+
for index, key in enumerate(keys, 1):
|
|
106
|
+
marker = "*" if key == default else " "
|
|
107
|
+
typer.echo(f" {marker} [{index}] {choices[key]}")
|
|
108
|
+
while True:
|
|
109
|
+
answer = str(typer.prompt(label, default=str(keys.index(default) + 1))).strip()
|
|
110
|
+
if answer.isdigit() and 1 <= int(answer) <= len(keys):
|
|
111
|
+
return keys[int(answer) - 1]
|
|
112
|
+
for key, text in choices.items():
|
|
113
|
+
if answer.lower() in (key.lower(), text.lower()):
|
|
114
|
+
return key
|
|
115
|
+
typer.echo(f"{answer!r} is not a valid choice.", err=True)
|
|
116
|
+
|
|
117
|
+
|
|
118
|
+
def _detect_framework(registry: Registry, root: Path) -> FrameworkAdapter:
|
|
119
|
+
# Specific frameworks first; the generic adapter detects everything.
|
|
120
|
+
adapters = sorted(registry.adapters.values(), key=lambda adapter: adapter.key == "generic")
|
|
121
|
+
for adapter in adapters:
|
|
122
|
+
try:
|
|
123
|
+
if adapter.detect(root):
|
|
124
|
+
return adapter
|
|
125
|
+
except Exception:
|
|
126
|
+
continue
|
|
127
|
+
return registry.adapters["generic"]
|
|
128
|
+
|
|
129
|
+
|
|
130
|
+
def _default_app(adapter: FrameworkAdapter, root: Path) -> str | None:
|
|
131
|
+
try:
|
|
132
|
+
target = adapter.default_app(root)
|
|
133
|
+
except Exception:
|
|
134
|
+
return None
|
|
135
|
+
return target if isinstance(target, str) and target else None
|
|
136
|
+
|
|
137
|
+
|
|
138
|
+
def _groups(registry: Registry) -> dict[str, str]:
|
|
139
|
+
groups = dict(GROUPS)
|
|
140
|
+
for service in registry.services.values():
|
|
141
|
+
groups.setdefault(service.group, service.group)
|
|
142
|
+
return groups
|
|
143
|
+
|
|
144
|
+
|
|
145
|
+
def _prompt_additional(registry: Registry, existing: list[AdditionalService]) -> list[AdditionalService]:
|
|
146
|
+
additional = list(existing)
|
|
147
|
+
used = {entry.name for entry in additional}
|
|
148
|
+
while typer.confirm(
|
|
149
|
+
"Add a named additional service instance (e.g. a second database)?" if not additional else "Add another one?",
|
|
150
|
+
default=False,
|
|
151
|
+
):
|
|
152
|
+
groups = {group: group for group in GROUPS_SUPPORTING_ADDITIONAL_INSTANCES if registry.in_group(group)}
|
|
153
|
+
if not groups:
|
|
154
|
+
break
|
|
155
|
+
group = select("Which kind of service?", groups)
|
|
156
|
+
service = select("Which one?", {item.key: item.label for item in registry.in_group(group)})
|
|
157
|
+
while True:
|
|
158
|
+
name = str(typer.prompt(
|
|
159
|
+
"Name this instance (its env var prefix and Compose service suffix, e.g. \"analytics\")"
|
|
160
|
+
)).strip().lower()
|
|
161
|
+
if not INSTANCE_NAME.fullmatch(name):
|
|
162
|
+
typer.echo(f"\"{name}\" must use lowercase letters, digits and underscores, starting with a letter.", err=True)
|
|
163
|
+
elif name in used:
|
|
164
|
+
typer.echo(f"\"{name}\" is already used; pick a different name.", err=True)
|
|
165
|
+
else:
|
|
166
|
+
break
|
|
167
|
+
used.add(name)
|
|
168
|
+
additional.append(AdditionalService(group, service, name))
|
|
169
|
+
return additional
|
|
170
|
+
|
|
171
|
+
|
|
172
|
+
def _prompt_silo_image(current: str) -> str:
|
|
173
|
+
typer.echo(
|
|
174
|
+
"\nSilo publishes two images of the same release. The standard one is built on RHEL 9, which\n"
|
|
175
|
+
"requires a CPU with the x86-64-v2 instruction set: on an older CPU, or a virtual machine that\n"
|
|
176
|
+
"exposes a generic CPU model, its container fails to start. The distroless one has no such\n"
|
|
177
|
+
"requirement, but no shell either, so `ship shell` can't open one in it.\n"
|
|
178
|
+
"Pick distroless if any machine that will run this stack (yours, a teammate's, the production\n"
|
|
179
|
+
"server) might be affected. On Linux, check a machine with:\n"
|
|
180
|
+
" /lib64/ld-linux-x86-64.so.2 --help | grep x86-64-v2\n"
|
|
181
|
+
"You can switch later with ship.json's \"siloImage\"; both images use the same data volume."
|
|
182
|
+
)
|
|
183
|
+
return select("Which Silo image?", {
|
|
184
|
+
"standard": "Standard (needs an x86-64-v2 CPU)",
|
|
185
|
+
"distroless": "Distroless (any CPU, no shell)",
|
|
186
|
+
}, current)
|
|
187
|
+
|
|
188
|
+
|
|
189
|
+
def _prompt_python(current: str) -> str:
|
|
190
|
+
while True:
|
|
191
|
+
answer = str(typer.prompt("Python version", default=current)).strip()
|
|
192
|
+
problem = problem_with(answer)
|
|
193
|
+
if problem is None:
|
|
194
|
+
return answer
|
|
195
|
+
typer.echo(problem, err=True)
|
|
196
|
+
|
|
197
|
+
|
|
198
|
+
def _silo_selected(services: dict[str, str], additional: list[AdditionalService]) -> bool:
|
|
199
|
+
return services.get("storage") == "silo" or any(entry.service == "silo" for entry in additional)
|
|
200
|
+
|
|
201
|
+
|
|
202
|
+
def resolve_config(root: Path, options: InitOptions) -> ShipConfig:
|
|
203
|
+
"""Combine flags, answers, the existing ship.json and detection into the new config."""
|
|
204
|
+
existing = ShipConfig.lenient(root) if (root / "ship.json").exists() else None
|
|
205
|
+
base = existing or ShipConfig()
|
|
206
|
+
registry = load_extensions(base)
|
|
207
|
+
interactive = options.interactive
|
|
208
|
+
|
|
209
|
+
if options.framework and options.framework not in registry.adapters:
|
|
210
|
+
raise ConfigError(f"Unknown framework {options.framework!r}; use one of {', '.join(sorted(registry.adapters))}.")
|
|
211
|
+
detected = _detect_framework(registry, root)
|
|
212
|
+
framework = options.framework or (existing.framework if existing else detected.key)
|
|
213
|
+
if interactive and not options.framework:
|
|
214
|
+
framework = select("Select a framework", {key: adapter.label for key, adapter in registry.adapters.items()}, framework)
|
|
215
|
+
adapter = registry.adapters[framework]
|
|
216
|
+
|
|
217
|
+
suggested = existing.app if existing and existing.framework == framework else _default_app(adapter, root)
|
|
218
|
+
app = options.app
|
|
219
|
+
if app is None and interactive:
|
|
220
|
+
app = str(typer.prompt("App target (module:callable)", default=suggested or "main:app")).strip()
|
|
221
|
+
app = app or suggested
|
|
222
|
+
if not app:
|
|
223
|
+
raise ConfigError(
|
|
224
|
+
f"Could not find the {adapter.label} app to serve; pass it with --app, such as `--app main:app`."
|
|
225
|
+
)
|
|
226
|
+
|
|
227
|
+
# Suggest servers that can run this app: ASGI (FastAPI, Django's asgi.py) or WSGI (Flask, wsgi.py).
|
|
228
|
+
interface = app_interface(replace(base, framework=framework, app=app), root, registry)
|
|
229
|
+
compatible = registry.servers_for(interface)
|
|
230
|
+
if options.server and options.server not in registry.servers:
|
|
231
|
+
raise ConfigError(f"Unknown web server {options.server!r}; use one of {', '.join(sorted(registry.servers))}.")
|
|
232
|
+
current = base.server if base.server and base.server in [item.key for item in compatible] else None
|
|
233
|
+
server = options.server or current or compatible[0].key
|
|
234
|
+
if interactive and not options.server:
|
|
235
|
+
choices = {item.key: item.label + (" (recommended)" if index == 0 else "") for index, item in enumerate(compatible)}
|
|
236
|
+
server = select(f"Select a web server for this {interface.upper()} app", choices, server)
|
|
237
|
+
registry.server(replace(base, server=server), interface) # Rejects a server that can't run this app.
|
|
238
|
+
|
|
239
|
+
services = dict(base.services)
|
|
240
|
+
flags = options.selections or {}
|
|
241
|
+
for group, label in _groups(registry).items():
|
|
242
|
+
choices = {NONE: "None", **{item.key: item.label for item in registry.in_group(group)}}
|
|
243
|
+
flagged = flags.get(group)
|
|
244
|
+
if flagged is not None:
|
|
245
|
+
if flagged != NONE and flagged not in choices:
|
|
246
|
+
raise ConfigError(f"Unknown {group} service {flagged!r}; use one of {', '.join(choices)}.")
|
|
247
|
+
answer = flagged
|
|
248
|
+
elif interactive and len(choices) > 1:
|
|
249
|
+
answer = select(f"Select {_article(label)} {label}", choices, services.get(group, NONE))
|
|
250
|
+
else:
|
|
251
|
+
continue
|
|
252
|
+
if answer == NONE:
|
|
253
|
+
services.pop(group, None)
|
|
254
|
+
else:
|
|
255
|
+
services[group] = answer
|
|
256
|
+
|
|
257
|
+
additional = list(base.additional_services)
|
|
258
|
+
if interactive:
|
|
259
|
+
additional = _prompt_additional(registry, additional)
|
|
260
|
+
|
|
261
|
+
silo_image = options.silo_image or base.silo_image
|
|
262
|
+
if options.silo_image and options.silo_image not in SILO_IMAGES:
|
|
263
|
+
raise ConfigError("--silo-image must be standard or distroless.")
|
|
264
|
+
if interactive and not options.silo_image and _silo_selected(services, additional):
|
|
265
|
+
silo_image = _prompt_silo_image(silo_image)
|
|
266
|
+
|
|
267
|
+
python = options.python or base.python
|
|
268
|
+
if options.python:
|
|
269
|
+
problem = problem_with(options.python)
|
|
270
|
+
if problem:
|
|
271
|
+
raise ConfigError(problem)
|
|
272
|
+
elif interactive:
|
|
273
|
+
python = _prompt_python(base.python or DEFAULT_PYTHON)
|
|
274
|
+
|
|
275
|
+
return replace(
|
|
276
|
+
base,
|
|
277
|
+
framework=framework,
|
|
278
|
+
app=app,
|
|
279
|
+
server=server,
|
|
280
|
+
python=python,
|
|
281
|
+
services=services,
|
|
282
|
+
additional_services=additional,
|
|
283
|
+
silo_image=silo_image,
|
|
284
|
+
node_assets=base.node_assets if options.node_assets is None else options.node_assets,
|
|
285
|
+
django_collectstatic=base.django_collectstatic and framework == "django",
|
|
286
|
+
)
|
|
287
|
+
|
|
288
|
+
|
|
289
|
+
def ensure_dockerignore(root: Path) -> None:
|
|
290
|
+
path = root / ".dockerignore"
|
|
291
|
+
existing = path.read_text(encoding="utf-8") if path.exists() else ""
|
|
292
|
+
missing = [line for line in DOCKERIGNORE.splitlines() if line not in existing.splitlines()]
|
|
293
|
+
if missing:
|
|
294
|
+
with path.open("a", encoding="utf-8") as stream:
|
|
295
|
+
if existing and not existing.endswith("\n"):
|
|
296
|
+
stream.write("\n")
|
|
297
|
+
stream.write("\n".join(missing) + "\n")
|
|
298
|
+
current = path.read_text(encoding="utf-8")
|
|
299
|
+
if not current.endswith(RELEASE_IGNORE_GUARD):
|
|
300
|
+
current = current.replace(RELEASE_IGNORE_GUARD, "")
|
|
301
|
+
path.write_text(current.rstrip("\n") + "\n" + RELEASE_IGNORE_GUARD, encoding="utf-8")
|
|
302
|
+
|
|
303
|
+
|
|
304
|
+
def ensure_gitignore(root: Path) -> None:
|
|
305
|
+
"""Merge the secret and generated-file rules into .gitignore without touching other entries."""
|
|
306
|
+
path = root / ".gitignore"
|
|
307
|
+
current = path.read_text(encoding="utf-8") if path.is_file() else ""
|
|
308
|
+
lines = {line.strip() for line in current.splitlines()}
|
|
309
|
+
missing = [rule for rule in GITIGNORE if rule not in lines and rule.lstrip("/") not in lines]
|
|
310
|
+
if not missing:
|
|
311
|
+
return
|
|
312
|
+
header = "# Added by `ship init`: production secrets, release output and generated files.\n"
|
|
313
|
+
with path.open("a", encoding="utf-8") as stream:
|
|
314
|
+
if current and not current.endswith("\n"):
|
|
315
|
+
stream.write("\n")
|
|
316
|
+
if current:
|
|
317
|
+
stream.write("\n")
|
|
318
|
+
stream.write(header + "\n".join(missing) + "\n")
|
|
319
|
+
|
|
320
|
+
|
|
321
|
+
def _vite_reminder(root: Path, config: ShipConfig) -> str | None:
|
|
322
|
+
package = root / "package.json"
|
|
323
|
+
if config.services.get("frontend") != "node" or not package.is_file():
|
|
324
|
+
return None
|
|
325
|
+
try:
|
|
326
|
+
data = json.loads(package.read_text(encoding="utf-8"))
|
|
327
|
+
except (OSError, ValueError):
|
|
328
|
+
return None
|
|
329
|
+
dependencies = {**data.get("dependencies", {}), **data.get("devDependencies", {})} if isinstance(data, dict) else {}
|
|
330
|
+
if "vite" not in dependencies:
|
|
331
|
+
return None
|
|
332
|
+
for name in ("vite.config.js", "vite.config.ts", "vite.config.mjs", "vite.config.mts", "vite.config.cjs", "vite.config.cts"):
|
|
333
|
+
config_file = root / name
|
|
334
|
+
if config_file.is_file() and re.search(r"0\.0\.0\.0|host:\s*true", config_file.read_text(encoding="utf-8")):
|
|
335
|
+
return None
|
|
336
|
+
return ("Vite runs in the node container, so its dev server must bind 0.0.0.0 on the port Ship publishes "
|
|
337
|
+
"for the page and its HMR WebSocket to reach the browser. Add this to your vite.config.js:\n\n" + VITE_SNIPPET)
|
|
338
|
+
|
|
339
|
+
|
|
340
|
+
def run_init(root: Path, options: InitOptions) -> int:
|
|
341
|
+
dockerfile = root / "ship" / "Dockerfile"
|
|
342
|
+
had_config = (root / "ship.json").exists()
|
|
343
|
+
if dockerfile.exists() and not had_config and not options.force:
|
|
344
|
+
raise ConfigError("ship/Dockerfile already exists; use --force to replace it.")
|
|
345
|
+
config = resolve_config(root, options)
|
|
346
|
+
# Validate the complete model before writing any project file.
|
|
347
|
+
build_compose(config, root)
|
|
348
|
+
for problem in (server_stub_problem(root, config), asset_stub_problem(root, config)):
|
|
349
|
+
if problem and dockerfile.exists() and not options.force:
|
|
350
|
+
raise ConfigError(problem)
|
|
351
|
+
require_uv()
|
|
352
|
+
published = publish_stubs(root, config, force=options.force)
|
|
353
|
+
config.write(root)
|
|
354
|
+
ensure_dockerignore(root)
|
|
355
|
+
ensure_gitignore(root)
|
|
356
|
+
if not published:
|
|
357
|
+
warning = stub_version_warning(root)
|
|
358
|
+
if warning:
|
|
359
|
+
typer.echo(f"ship: warning: {warning}", err=True)
|
|
360
|
+
reminder = _vite_reminder(root, config)
|
|
361
|
+
if reminder:
|
|
362
|
+
typer.echo(f"ship: note: {reminder}", err=True)
|
|
363
|
+
if published:
|
|
364
|
+
typer.echo(f"Wrote ship.json and published the ship/ directory (python-ship {__version__}). "
|
|
365
|
+
"Run `ship up` to build and start the environment.")
|
|
366
|
+
else:
|
|
367
|
+
typer.echo("Updated ship.json and kept your ship/Dockerfile. Run `ship up` to apply the changes.")
|
|
368
|
+
return 0
|
|
369
|
+
|
python_ship/mutagen.py
ADDED
|
@@ -0,0 +1,89 @@
|
|
|
1
|
+
"""Optional direct Mutagen synchronization for Docker Desktop development."""
|
|
2
|
+
|
|
3
|
+
import hashlib
|
|
4
|
+
import os
|
|
5
|
+
from pathlib import Path
|
|
6
|
+
import shutil
|
|
7
|
+
import subprocess
|
|
8
|
+
import time
|
|
9
|
+
|
|
10
|
+
from .config import ConfigError
|
|
11
|
+
|
|
12
|
+
IGNORES = (
|
|
13
|
+
".venv", "venv", "node_modules", "__pycache__", ".pytest_cache",
|
|
14
|
+
".mypy_cache", ".ruff_cache", ".tox", "dist", "build",
|
|
15
|
+
"*.egg-info", ".env", ".env.*", "ship/docker-compose.*.yml", "dist/ship",
|
|
16
|
+
)
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
def enabled() -> bool:
|
|
20
|
+
return os.environ.get("SHIP_MUTAGEN", "").lower() in {"1", "true"}
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
def _label(root: Path) -> str:
|
|
24
|
+
digest = hashlib.sha256(str(root.resolve()).encode()).hexdigest()[:16]
|
|
25
|
+
return f"ship-project={digest}"
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
def _binary(*, required: bool = False) -> str | None:
|
|
29
|
+
binary = shutil.which("mutagen")
|
|
30
|
+
if required and binary is None:
|
|
31
|
+
raise ConfigError("SHIP_MUTAGEN requires the Mutagen CLI on PATH. Install Mutagen, then run `ship up` again.")
|
|
32
|
+
return binary
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
def _run(command: list[str], root: Path) -> subprocess.CompletedProcess[str]:
|
|
36
|
+
try:
|
|
37
|
+
return subprocess.run(command, cwd=root, capture_output=True, text=True, check=False, timeout=45)
|
|
38
|
+
except (OSError, subprocess.TimeoutExpired) as exc:
|
|
39
|
+
raise ConfigError(f"Mutagen command failed: {exc}") from exc
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
def stop(root: Path, *, required: bool = False) -> None:
|
|
43
|
+
binary = _binary(required=required)
|
|
44
|
+
if binary is None:
|
|
45
|
+
return
|
|
46
|
+
result = _run([binary, "sync", "terminate", "--label-selector", _label(root)], root)
|
|
47
|
+
if result.returncode != 0:
|
|
48
|
+
raise ConfigError(f"Could not stop Mutagen sync: {result.stderr.strip() or result.stdout.strip()}")
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
def start(prefix: list[str], root: Path, services: tuple[str, ...] = ("app",)) -> None:
|
|
52
|
+
binary = _binary(required=True)
|
|
53
|
+
assert binary is not None
|
|
54
|
+
label = _label(root)
|
|
55
|
+
try:
|
|
56
|
+
for service in services:
|
|
57
|
+
container = subprocess.run(prefix + ["ps", "-q", service], cwd=root, capture_output=True, text=True, check=False)
|
|
58
|
+
container_id = container.stdout.strip()
|
|
59
|
+
if container.returncode != 0 or not container_id:
|
|
60
|
+
raise ConfigError(f"Could not find the running {service} container for Mutagen sync.")
|
|
61
|
+
name = "ship-" + label.partition("=")[2] + "-" + service
|
|
62
|
+
command = [binary, "sync", "create", "--no-global-configuration", "--name", name, "--label", label,
|
|
63
|
+
"--mode", "two-way-resolved", "--ignore-vcs"]
|
|
64
|
+
for pattern in IGNORES:
|
|
65
|
+
command += ["--ignore", pattern]
|
|
66
|
+
command += [str(root.resolve()), f"docker://{container_id}/app"]
|
|
67
|
+
created = _run(command, root)
|
|
68
|
+
if created.returncode != 0:
|
|
69
|
+
raise ConfigError(f"Could not create Mutagen sync for {service}: {created.stderr.strip() or created.stdout.strip()}")
|
|
70
|
+
deadline = time.monotonic() + 120
|
|
71
|
+
while time.monotonic() < deadline:
|
|
72
|
+
status = _run([binary, "sync", "list", "--label-selector", label,
|
|
73
|
+
"--template", '{{range .}}{{.Status}}|{{.Alpha.Connected}}|{{.Beta.Connected}}{{"\\n"}}{{end}}'], root)
|
|
74
|
+
if status.returncode != 0:
|
|
75
|
+
raise ConfigError(f"Could not inspect Mutagen sync: {status.stderr.strip()}")
|
|
76
|
+
ready = [line for line in status.stdout.splitlines() if line.strip().lower() == "watching|true|true"]
|
|
77
|
+
if len(ready) == len(services):
|
|
78
|
+
flushed = _run([binary, "sync", "flush", "--label-selector", label], root)
|
|
79
|
+
if flushed.returncode != 0:
|
|
80
|
+
raise ConfigError(f"Could not flush Mutagen sync: {flushed.stderr.strip()}")
|
|
81
|
+
return
|
|
82
|
+
time.sleep(1)
|
|
83
|
+
raise ConfigError("Mutagen did not finish its initial sync within 120 seconds. Run `ship up` again.")
|
|
84
|
+
except (ConfigError, OSError):
|
|
85
|
+
try:
|
|
86
|
+
stop(root, required=True)
|
|
87
|
+
except ConfigError:
|
|
88
|
+
pass
|
|
89
|
+
raise
|
python_ship/plugins.py
ADDED
|
@@ -0,0 +1,149 @@
|
|
|
1
|
+
"""Resolve ship.json's ``extensions`` into a registry of adapters, services and servers."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from dataclasses import dataclass, field
|
|
6
|
+
from importlib.metadata import entry_points
|
|
7
|
+
import re
|
|
8
|
+
from typing import Any
|
|
9
|
+
|
|
10
|
+
from .adapters import BUILTIN_ADAPTERS
|
|
11
|
+
from .config import RESERVED_COMMANDS, ConfigError, ShipConfig
|
|
12
|
+
from .contracts import FrameworkAdapter, Interface, ServiceDefinition, WebServer
|
|
13
|
+
from .servers import BUILTIN_SERVERS, RECOMMENDED
|
|
14
|
+
from .services import BUILTIN_SERVICES
|
|
15
|
+
|
|
16
|
+
GROUPS = {"adapter": "python_ship.adapters", "service": "python_ship.services", "server": "python_ship.servers"}
|
|
17
|
+
KEY = re.compile(r"[a-z][a-z0-9]*(?:[-_][a-z0-9]+)*")
|
|
18
|
+
GROUP = re.compile(r"[a-z][a-z0-9_-]*")
|
|
19
|
+
COMMAND = re.compile(r"[a-z][a-z0-9:_-]*")
|
|
20
|
+
|
|
21
|
+
_REQUIRED = {
|
|
22
|
+
"adapter": ("detect", "default_app", "interface", "validate", "server_target", "console_commands", "release_commands"),
|
|
23
|
+
"service": ("compose_fragment", "app_environment"),
|
|
24
|
+
"server": ("development_command", "production_command"),
|
|
25
|
+
}
|
|
26
|
+
_OPTIONAL = {"adapter": ("app_environment",), "service": ("database_shell", "validate"), "server": ()}
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
@dataclass
|
|
30
|
+
class Registry:
|
|
31
|
+
adapters: dict[str, FrameworkAdapter] = field(default_factory=dict)
|
|
32
|
+
services: dict[str, ServiceDefinition] = field(default_factory=dict)
|
|
33
|
+
servers: dict[str, WebServer] = field(default_factory=dict)
|
|
34
|
+
|
|
35
|
+
def in_group(self, group: str) -> list[ServiceDefinition]:
|
|
36
|
+
return [service for service in self.services.values() if service.group == group]
|
|
37
|
+
|
|
38
|
+
def adapter(self, config: ShipConfig) -> FrameworkAdapter:
|
|
39
|
+
adapter = self.adapters.get(config.framework)
|
|
40
|
+
if adapter is None:
|
|
41
|
+
raise ConfigError(
|
|
42
|
+
f"Unknown framework adapter {config.framework!r}; use one of "
|
|
43
|
+
f"{', '.join(sorted(self.adapters))}, or install and select its extension."
|
|
44
|
+
)
|
|
45
|
+
return adapter
|
|
46
|
+
|
|
47
|
+
def servers_for(self, interface: Interface) -> list[WebServer]:
|
|
48
|
+
"""Servers able to run an app with this interface, recommended ones first."""
|
|
49
|
+
ranked = [self.servers[key] for key in RECOMMENDED[interface] if key in self.servers]
|
|
50
|
+
others = [server for server in self.servers.values() if interface in server.interfaces and server not in ranked]
|
|
51
|
+
return ranked + others
|
|
52
|
+
|
|
53
|
+
def server(self, config: ShipConfig, interface: Interface) -> WebServer:
|
|
54
|
+
"""The configured server, or the recommended one for the app's interface."""
|
|
55
|
+
if config.server is None:
|
|
56
|
+
return self.servers_for(interface)[0]
|
|
57
|
+
server = self.servers.get(config.server)
|
|
58
|
+
if server is None:
|
|
59
|
+
raise ConfigError(
|
|
60
|
+
f"Unknown web server {config.server!r}; use one of {', '.join(sorted(self.servers))}, "
|
|
61
|
+
"or install and select its extension."
|
|
62
|
+
)
|
|
63
|
+
if interface not in server.interfaces:
|
|
64
|
+
choices = ", ".join(item.key for item in self.servers_for(interface))
|
|
65
|
+
raise ConfigError(
|
|
66
|
+
f"{server.label} can't serve a {interface.upper()} app; use one of {choices}."
|
|
67
|
+
)
|
|
68
|
+
return server
|
|
69
|
+
|
|
70
|
+
|
|
71
|
+
def _check(kind: str, selected: str, extension: Any, existing: dict[str, Any]) -> None:
|
|
72
|
+
key = getattr(extension, "key", None)
|
|
73
|
+
if not isinstance(key, str) or not KEY.fullmatch(key):
|
|
74
|
+
raise ConfigError(f"Extension {selected!r} has an invalid key {key!r}.")
|
|
75
|
+
if key in existing:
|
|
76
|
+
raise ConfigError(f"Extension {selected!r} reuses the {kind} key {key!r}, which is already registered.")
|
|
77
|
+
label = getattr(extension, "label", None)
|
|
78
|
+
if not isinstance(label, str) or not label:
|
|
79
|
+
raise ConfigError(f"Extension {selected!r} needs a nonempty label.")
|
|
80
|
+
missing = [name for name in _REQUIRED[kind] if not callable(getattr(extension, name, None))]
|
|
81
|
+
if missing:
|
|
82
|
+
raise ConfigError(
|
|
83
|
+
f"Extension {selected!r} does not implement the {kind} contract; missing: {', '.join(missing)}."
|
|
84
|
+
)
|
|
85
|
+
invalid = [name for name in _OPTIONAL[kind] if hasattr(extension, name) and not callable(getattr(extension, name))]
|
|
86
|
+
if invalid:
|
|
87
|
+
raise ConfigError(f"Extension {selected!r} has non-callable optional hooks: {', '.join(invalid)}.")
|
|
88
|
+
if kind == "service":
|
|
89
|
+
group = getattr(extension, "group", None)
|
|
90
|
+
if not isinstance(group, str) or not GROUP.fullmatch(group):
|
|
91
|
+
raise ConfigError(f"Extension {selected!r} has an invalid service group {group!r}.")
|
|
92
|
+
if kind == "server":
|
|
93
|
+
requirement = getattr(extension, "requirement", None)
|
|
94
|
+
if not isinstance(requirement, str) or not requirement.strip():
|
|
95
|
+
raise ConfigError(f"Extension {selected!r} needs a nonempty PEP 508 requirement.")
|
|
96
|
+
interfaces = getattr(extension, "interfaces", None)
|
|
97
|
+
if not isinstance(interfaces, (tuple, list)) or not interfaces or any(item not in ("asgi", "wsgi") for item in interfaces):
|
|
98
|
+
raise ConfigError(f"Extension {selected!r} must declare interfaces: \"asgi\", \"wsgi\" or both.")
|
|
99
|
+
|
|
100
|
+
|
|
101
|
+
def load_extensions(config: ShipConfig) -> Registry:
|
|
102
|
+
"""Built-ins plus every explicitly selected entry point; nothing is loaded implicitly."""
|
|
103
|
+
registry = Registry(dict(BUILTIN_ADAPTERS), dict(BUILTIN_SERVICES), dict(BUILTIN_SERVERS))
|
|
104
|
+
targets: dict[str, dict[str, Any]] = {
|
|
105
|
+
"adapter": registry.adapters, "service": registry.services, "server": registry.servers,
|
|
106
|
+
}
|
|
107
|
+
for selected in config.extensions:
|
|
108
|
+
matches = [
|
|
109
|
+
(kind, point)
|
|
110
|
+
for kind, group in GROUPS.items()
|
|
111
|
+
for point in entry_points(group=group)
|
|
112
|
+
if point.name == selected
|
|
113
|
+
]
|
|
114
|
+
if not matches:
|
|
115
|
+
raise ConfigError(
|
|
116
|
+
f"Extension {selected!r} is not installed; install its distribution in the same environment "
|
|
117
|
+
"as the ship command (for example `uv tool install python-ship --with DISTRIBUTION`)."
|
|
118
|
+
)
|
|
119
|
+
if len(matches) > 1:
|
|
120
|
+
raise ConfigError(
|
|
121
|
+
f"Extension {selected!r} matches {len(matches)} python_ship entry points; "
|
|
122
|
+
"each extension needs a unique entry point name."
|
|
123
|
+
)
|
|
124
|
+
kind, point = matches[0]
|
|
125
|
+
try:
|
|
126
|
+
loaded = point.load()
|
|
127
|
+
extension = loaded() if isinstance(loaded, type) else loaded
|
|
128
|
+
except Exception as exc:
|
|
129
|
+
raise ConfigError(f"Could not load extension {selected!r}: {exc}") from exc
|
|
130
|
+
target = targets[kind]
|
|
131
|
+
_check(kind, selected, extension, target)
|
|
132
|
+
target[extension.key] = extension
|
|
133
|
+
return registry
|
|
134
|
+
|
|
135
|
+
|
|
136
|
+
def console_commands(adapter: FrameworkAdapter) -> dict[str, list[str]]:
|
|
137
|
+
"""An adapter's proxy commands, validated so they can't shadow Ship's own commands."""
|
|
138
|
+
try:
|
|
139
|
+
commands = adapter.console_commands()
|
|
140
|
+
except Exception as exc:
|
|
141
|
+
raise ConfigError(f"Adapter {adapter.key!r} console commands failed: {exc}") from exc
|
|
142
|
+
if not isinstance(commands, dict):
|
|
143
|
+
raise ConfigError(f"Adapter {adapter.key!r} console_commands() must return a dict.")
|
|
144
|
+
for name, prefix in commands.items():
|
|
145
|
+
if not isinstance(name, str) or not COMMAND.fullmatch(name) or name in RESERVED_COMMANDS:
|
|
146
|
+
raise ConfigError(f"Adapter {adapter.key!r} console command {name!r} is invalid or reserved.")
|
|
147
|
+
if not isinstance(prefix, list) or not prefix or any(not isinstance(part, str) or not part for part in prefix):
|
|
148
|
+
raise ConfigError(f"Adapter {adapter.key!r} console command {name!r} must be a nonempty argument list.")
|
|
149
|
+
return commands
|
|
@@ -0,0 +1,69 @@
|
|
|
1
|
+
"""Production environment checks shared by config:test, build and release."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import json
|
|
6
|
+
from pathlib import Path
|
|
7
|
+
import re
|
|
8
|
+
|
|
9
|
+
REQUIRED = re.compile(r"\$\{([A-Za-z_][A-Za-z0-9_]*):\?")
|
|
10
|
+
# Every development default a built-in service uses for a secret. Shipping one to production
|
|
11
|
+
# would give every project that forgot the same, publicly known credential.
|
|
12
|
+
DEVELOPMENT_DEFAULTS = frozenset({
|
|
13
|
+
"ship", "rootship", "shipsecret", "shipsecretplaceholder", "shipsearchkey", "changeme", "0" * 64,
|
|
14
|
+
})
|
|
15
|
+
_KEY = re.compile(r"[A-Za-z_][A-Za-z0-9_]*")
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
def read_env(path: Path) -> dict[str, str]:
|
|
19
|
+
"""Parse the KEY=VALUE subset that Compose env files accept.
|
|
20
|
+
|
|
21
|
+
Handles a BOM, ``export`` prefixes, single and double quotes (with escapes in
|
|
22
|
+
double quotes) and trailing ``#`` comments on unquoted values.
|
|
23
|
+
"""
|
|
24
|
+
if not path.is_file():
|
|
25
|
+
return {}
|
|
26
|
+
values: dict[str, str] = {}
|
|
27
|
+
for raw in path.read_text(encoding="utf-8-sig").splitlines():
|
|
28
|
+
line = raw.strip()
|
|
29
|
+
if not line or line.startswith("#") or "=" not in line:
|
|
30
|
+
continue
|
|
31
|
+
key, value = line.split("=", 1)
|
|
32
|
+
key = key.strip()
|
|
33
|
+
if key.startswith("export "):
|
|
34
|
+
key = key[len("export "):].strip()
|
|
35
|
+
if not _KEY.fullmatch(key):
|
|
36
|
+
continue
|
|
37
|
+
value = value.strip()
|
|
38
|
+
if value.startswith('"'):
|
|
39
|
+
match = re.match(r'^"((?:\\.|[^"\\])*)"', value)
|
|
40
|
+
if match:
|
|
41
|
+
value = re.sub(r'\\(["\\$])', r"\1", match.group(1)).replace("\\n", "\n")
|
|
42
|
+
elif value.startswith("'"):
|
|
43
|
+
end = value.find("'", 1)
|
|
44
|
+
if end >= 0:
|
|
45
|
+
value = value[1:end]
|
|
46
|
+
else:
|
|
47
|
+
value = re.split(r"\s+#", value, maxsplit=1)[0].rstrip()
|
|
48
|
+
values[key] = value
|
|
49
|
+
return values
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
def required_variables(model: dict) -> list[str]:
|
|
53
|
+
return sorted(set(REQUIRED.findall(json.dumps(model))))
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
def credential_problems(model: dict, root: Path) -> list[str]:
|
|
57
|
+
"""Required production variables missing from .env.production, or set to a development default."""
|
|
58
|
+
required = required_variables(model)
|
|
59
|
+
if not required:
|
|
60
|
+
return []
|
|
61
|
+
values = read_env(root / ".env.production")
|
|
62
|
+
missing = [key for key in required if not values.get(key)]
|
|
63
|
+
unsafe = [key for key in required if values.get(key, "").lower() in DEVELOPMENT_DEFAULTS]
|
|
64
|
+
problems = []
|
|
65
|
+
if missing:
|
|
66
|
+
problems.append(f"Production credentials missing from .env.production: {', '.join(missing)}.")
|
|
67
|
+
if unsafe:
|
|
68
|
+
problems.append(f"Production credentials still use a development default: {', '.join(unsafe)}.")
|
|
69
|
+
return problems
|
python_ship/py.typed
ADDED
|
File without changes
|