python-ship 0.2.0__py3-none-any.whl → 0.3.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 +1 -1
- python_ship/adapters.py +28 -3
- python_ship/capabilities.py +26 -1
- python_ship/cli.py +305 -90
- python_ship/compose.py +40 -14
- python_ship/config.py +26 -11
- python_ship/contracts.py +13 -1
- python_ship/environment.py +252 -38
- python_ship/image_build.py +143 -0
- python_ship/init.py +298 -76
- python_ship/layout.py +50 -0
- python_ship/mutagen.py +1 -1
- python_ship/package_managers.py +1 -1
- python_ship/plugins.py +22 -2
- python_ship/portable.py +7 -0
- python_ship/ports.py +120 -0
- python_ship/production.py +1 -0
- python_ship/release.py +4 -2
- python_ship/runtime.py +9 -7
- python_ship/schema/ship.schema.json +22 -0
- python_ship/security.py +2 -1
- python_ship/service_setup.py +80 -0
- python_ship/services.py +63 -4
- python_ship/storage.py +9 -3
- python_ship/stubs.py +23 -21
- python_ship/templates/Dockerfile +12 -2
- python_ship/templates/check-python-security-floor.py +1 -1
- python_ship/templates/launcher +49 -0
- python_ship/terminal.py +77 -0
- python_ship/wizard.py +52 -6
- {python_ship-0.2.0.dist-info → python_ship-0.3.0.dist-info}/METADATA +363 -178
- python_ship-0.3.0.dist-info/RECORD +47 -0
- python_ship-0.2.0.dist-info/RECORD +0 -41
- {python_ship-0.2.0.dist-info → python_ship-0.3.0.dist-info}/WHEEL +0 -0
- {python_ship-0.2.0.dist-info → python_ship-0.3.0.dist-info}/entry_points.txt +0 -0
- {python_ship-0.2.0.dist-info → python_ship-0.3.0.dist-info}/licenses/LICENSE.md +0 -0
- {python_ship-0.2.0.dist-info → python_ship-0.3.0.dist-info}/top_level.txt +0 -0
|
@@ -0,0 +1,143 @@
|
|
|
1
|
+
"""Run a Compose build with progress, keeping its log for failures."""
|
|
2
|
+
|
|
3
|
+
from collections.abc import Iterator, Mapping
|
|
4
|
+
from contextlib import ExitStack, contextmanager
|
|
5
|
+
from itertools import cycle
|
|
6
|
+
import json
|
|
7
|
+
import os
|
|
8
|
+
from pathlib import Path
|
|
9
|
+
import re
|
|
10
|
+
import shutil
|
|
11
|
+
import subprocess
|
|
12
|
+
import sys
|
|
13
|
+
from tempfile import TemporaryDirectory
|
|
14
|
+
from threading import Event, Thread
|
|
15
|
+
from typing import BinaryIO, TextIO
|
|
16
|
+
|
|
17
|
+
from rich.console import Console, Group
|
|
18
|
+
from rich.live import Live
|
|
19
|
+
from rich.text import Text
|
|
20
|
+
import typer
|
|
21
|
+
|
|
22
|
+
from .config import ConfigError
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
def build_images(
|
|
26
|
+
command: list[str], project: Path, message: str, *, verbose: bool = False, env: Mapping[str, str] | None = None,
|
|
27
|
+
) -> int:
|
|
28
|
+
if verbose:
|
|
29
|
+
print(message, flush=True)
|
|
30
|
+
code = subprocess.run(command, cwd=project, env=env, stdin=subprocess.DEVNULL, check=False).returncode
|
|
31
|
+
return 128 - code if code < 0 else code
|
|
32
|
+
|
|
33
|
+
with TemporaryDirectory(prefix="ship-build-") as directory:
|
|
34
|
+
path = Path(directory) / "build.log"
|
|
35
|
+
with path.open("w+t", encoding="utf-8", errors="replace") as log:
|
|
36
|
+
code = _with_progress(command, project, message, env, log, path)
|
|
37
|
+
if code:
|
|
38
|
+
log.seek(0)
|
|
39
|
+
shutil.copyfileobj(log, sys.stderr)
|
|
40
|
+
sys.stderr.flush()
|
|
41
|
+
return 128 - code if code < 0 else code
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
def _with_progress(
|
|
45
|
+
command: list[str], project: Path, message: str, env: Mapping[str, str] | None, log: TextIO, path: Path,
|
|
46
|
+
) -> int:
|
|
47
|
+
animate = sys.stdin.isatty() and sys.stdout.isatty() and "CI" not in os.environ and os.environ.get("TERM") != "dumb"
|
|
48
|
+
with _build_display(message, path, animate=animate):
|
|
49
|
+
return subprocess.run(command, cwd=project, env=env, stdin=subprocess.DEVNULL,
|
|
50
|
+
stdout=log, stderr=subprocess.STDOUT, check=False).returncode
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
@contextmanager
|
|
54
|
+
def _build_display(message: str, path: Path, *, animate: bool) -> Iterator[None]:
|
|
55
|
+
if not animate:
|
|
56
|
+
print(message, flush=True)
|
|
57
|
+
yield
|
|
58
|
+
return
|
|
59
|
+
|
|
60
|
+
done = Event()
|
|
61
|
+
frames = cycle("⠋⠙⠹⠸⠼⠴⠦⠧⠇⠏")
|
|
62
|
+
console = Console(file=sys.stdout, highlight=False, force_terminal=True)
|
|
63
|
+
with ExitStack() as display:
|
|
64
|
+
display.callback(print, message, flush=True)
|
|
65
|
+
reader = display.enter_context(path.open("rb"))
|
|
66
|
+
live = display.enter_context(Live(console=console, auto_refresh=False, transient=True,
|
|
67
|
+
redirect_stdout=False, redirect_stderr=False))
|
|
68
|
+
|
|
69
|
+
def render_frame(activity: str) -> None:
|
|
70
|
+
live.update(Group(
|
|
71
|
+
Text(f"{next(frames)} {message}", no_wrap=True, overflow="ellipsis"),
|
|
72
|
+
Text(f" {activity}" if activity else "", style="dim", no_wrap=True, overflow="ellipsis"),
|
|
73
|
+
), refresh=True)
|
|
74
|
+
|
|
75
|
+
def spin() -> None:
|
|
76
|
+
activity = ""
|
|
77
|
+
while not done.wait(0.08):
|
|
78
|
+
activity = _recent_activity(reader) or activity
|
|
79
|
+
render_frame(activity)
|
|
80
|
+
|
|
81
|
+
render_frame("")
|
|
82
|
+
spinner = Thread(target=spin, daemon=True)
|
|
83
|
+
spinner.start()
|
|
84
|
+
display.callback(spinner.join)
|
|
85
|
+
display.callback(done.set)
|
|
86
|
+
yield
|
|
87
|
+
|
|
88
|
+
|
|
89
|
+
def _recent_activity(reader: BinaryIO) -> str:
|
|
90
|
+
"""Read a bounded tail without disturbing the file descriptor Docker writes to."""
|
|
91
|
+
end = os.fstat(reader.fileno()).st_size
|
|
92
|
+
if end == reader.tell():
|
|
93
|
+
return ""
|
|
94
|
+
start = max(0, end - 8192)
|
|
95
|
+
reader.seek(start)
|
|
96
|
+
tail = reader.read(end - start).decode("utf-8", errors="replace")
|
|
97
|
+
for line in reversed(tail.splitlines()):
|
|
98
|
+
plain = Text.from_ansi(line).plain
|
|
99
|
+
activity = re.sub(r"[\x00-\x1f\x7f-\x9f]", " ", plain).strip()
|
|
100
|
+
if activity:
|
|
101
|
+
return activity
|
|
102
|
+
return ""
|
|
103
|
+
|
|
104
|
+
|
|
105
|
+
def run_pull_args(prefix: list[str], project: Path, service: str) -> list[str]:
|
|
106
|
+
"""Use the built image unless an override replaced its build with a registry image."""
|
|
107
|
+
services = _overridden_services(prefix, project, service)
|
|
108
|
+
return ["--pull", "never"] if services is None or services.get(service, {}).get("build") is not None else []
|
|
109
|
+
|
|
110
|
+
|
|
111
|
+
@contextmanager
|
|
112
|
+
def built_stack_prefix(prefix: list[str], project: Path) -> Iterator[list[str]]:
|
|
113
|
+
"""Keep Compose's --build policy for locally built tags, including overridden ones."""
|
|
114
|
+
services = _overridden_services(prefix, project) or {}
|
|
115
|
+
policies = {
|
|
116
|
+
name: {"pull_policy": "build"}
|
|
117
|
+
for name, service in services.items()
|
|
118
|
+
if service.get("build") and service.get("image") and service.get("pull_policy") not in ("never", "build")
|
|
119
|
+
}
|
|
120
|
+
if not policies:
|
|
121
|
+
yield prefix
|
|
122
|
+
return
|
|
123
|
+
with TemporaryDirectory(prefix="ship-compose-") as directory:
|
|
124
|
+
overlay = Path(directory) / "built-images.json"
|
|
125
|
+
overlay.write_text(json.dumps({"services": policies}), encoding="utf-8")
|
|
126
|
+
yield [*prefix, "-f", str(overlay)]
|
|
127
|
+
|
|
128
|
+
|
|
129
|
+
def _overridden_services(
|
|
130
|
+
prefix: list[str], project: Path, service: str | None = None,
|
|
131
|
+
) -> dict[str, dict[str, object]] | None:
|
|
132
|
+
if prefix.count("-f") < 2:
|
|
133
|
+
return None
|
|
134
|
+
command = [*prefix, "config", "--no-env-resolution", "--format", "json"]
|
|
135
|
+
if service is not None:
|
|
136
|
+
command.append(service)
|
|
137
|
+
result = subprocess.run(command, cwd=project, stdin=subprocess.DEVNULL, stdout=subprocess.PIPE, check=False)
|
|
138
|
+
if result.returncode:
|
|
139
|
+
raise typer.Exit(128 - result.returncode if result.returncode < 0 else result.returncode)
|
|
140
|
+
try:
|
|
141
|
+
return json.loads(result.stdout)["services"]
|
|
142
|
+
except (ValueError, KeyError, TypeError) as exc:
|
|
143
|
+
raise ConfigError("Docker Compose did not return the resolved service model.") from exc
|
python_ship/init.py
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
"""`ship init`: pick services, write ship.json and publish
|
|
1
|
+
"""`ship init`: pick services, write ship.json and publish project Docker files."""
|
|
2
2
|
|
|
3
3
|
from __future__ import annotations
|
|
4
4
|
|
|
@@ -11,21 +11,25 @@ from typing import Any
|
|
|
11
11
|
|
|
12
12
|
import typer
|
|
13
13
|
|
|
14
|
-
from . import __version__, wizard
|
|
15
|
-
from .capabilities import process_suggestions
|
|
14
|
+
from . import __version__, terminal, wizard
|
|
15
|
+
from .capabilities import process_suggestions, setup_advice
|
|
16
16
|
from .compose import app_interface, build_compose, project_name
|
|
17
17
|
from .config import (
|
|
18
|
-
GROUPS_SUPPORTING_ADDITIONAL_INSTANCES,
|
|
19
18
|
INSTANCE_NAME,
|
|
19
|
+
SERVICE_NAME,
|
|
20
20
|
SILO_IMAGES,
|
|
21
21
|
AdditionalService,
|
|
22
22
|
ConfigError,
|
|
23
23
|
ShipConfig,
|
|
24
24
|
)
|
|
25
25
|
from .contracts import FrameworkAdapter
|
|
26
|
-
from .environment import ensure_environment, environment_warnings
|
|
27
|
-
from .
|
|
28
|
-
from .
|
|
26
|
+
from .environment import ENV_FILES, ensure_environment, environment_rows, environment_warnings
|
|
27
|
+
from .layout import DOCKER_DIRECTORY, archive_legacy_directory, publish_launcher
|
|
28
|
+
from .plugins import Registry, load_extensions, supports_named_instances
|
|
29
|
+
from .ports import Port, available_ports, port_number, suggest_ports
|
|
30
|
+
from .production import read_env
|
|
31
|
+
from .security import NEW_PROJECT_PYTHON, problem_with
|
|
32
|
+
from .service_setup import dependency_advice
|
|
29
33
|
from .stubs import asset_stub_problem, publish_stubs, server_stub_problem, stub_version_warning
|
|
30
34
|
from .uv import require_uv
|
|
31
35
|
|
|
@@ -51,6 +55,7 @@ DOCKERIGNORE = (
|
|
|
51
55
|
"node_modules/\n**/node_modules/\nstaticfiles/\n"
|
|
52
56
|
".npmrc\n**/.npmrc\nauth.json\n**/auth.json\n"
|
|
53
57
|
".git\ndist/\nship/docker-compose.generated.yml\nship/docker-compose.production.yml\n"
|
|
58
|
+
"docker/ship/docker-compose.generated.yml\ndocker/ship/docker-compose.production.yml\ndocker/ship-legacy/\n"
|
|
54
59
|
)
|
|
55
60
|
# Re-applied as the file's last lines before every production build, so a hand-edited
|
|
56
61
|
# .dockerignore can't re-include a secret or an earlier release into the next image.
|
|
@@ -65,6 +70,9 @@ GITIGNORE = (
|
|
|
65
70
|
"/dist/ship/",
|
|
66
71
|
"/ship/docker-compose.generated.yml",
|
|
67
72
|
"/ship/docker-compose.production.yml",
|
|
73
|
+
"/docker/ship/docker-compose.generated.yml",
|
|
74
|
+
"/docker/ship/docker-compose.production.yml",
|
|
75
|
+
"/docker/ship-legacy/",
|
|
68
76
|
)
|
|
69
77
|
|
|
70
78
|
VITE_SNIPPET = """\
|
|
@@ -159,20 +167,44 @@ def _groups(registry: Registry) -> dict[str, str]:
|
|
|
159
167
|
return groups
|
|
160
168
|
|
|
161
169
|
|
|
162
|
-
def
|
|
163
|
-
|
|
164
|
-
if
|
|
165
|
-
|
|
170
|
+
def _select_many(label: str, choices: dict[str, str], defaults: list[str]) -> list[str]:
|
|
171
|
+
session = wizard.active.get()
|
|
172
|
+
if session and session.rich:
|
|
173
|
+
return list(session.ask("checkbox", label, defaults, choices))
|
|
174
|
+
|
|
175
|
+
typer.echo(f"\n{label}:")
|
|
176
|
+
aliases = {}
|
|
177
|
+
for index, (key, text) in enumerate(choices.items(), 1):
|
|
178
|
+
typer.echo(f" [{index}] {text}")
|
|
179
|
+
aliases.update({str(index): key, key.casefold(): key, text.casefold(): key})
|
|
180
|
+
none = str(len(choices) + 1)
|
|
181
|
+
typer.echo(f" [{none}] None")
|
|
182
|
+
while True:
|
|
183
|
+
answer = str(wizard.prompt(f"{label} (comma-separated, or none)", default=",".join(defaults) or NONE))
|
|
184
|
+
items = [item.strip().casefold() for item in answer.split(",")]
|
|
185
|
+
if items in ([NONE], [none]):
|
|
186
|
+
return []
|
|
187
|
+
if all(item in aliases for item in items):
|
|
188
|
+
return list(dict.fromkeys(aliases[item] for item in items))
|
|
189
|
+
typer.echo("Choose by number or name, or enter none.", err=True)
|
|
190
|
+
|
|
191
|
+
|
|
192
|
+
def _prompt_additional(
|
|
193
|
+
groups: dict[str, str], choices: dict[str, dict[str, str]], existing: list[AdditionalService], *, has_primary: bool,
|
|
194
|
+
) -> list[AdditionalService]:
|
|
195
|
+
additional = [entry for entry in existing if wizard.confirm(f"Keep instance {entry.name} ({entry.service})?", default=True)]
|
|
166
196
|
used = {entry.name for entry in additional}
|
|
167
|
-
while
|
|
168
|
-
|
|
169
|
-
|
|
170
|
-
|
|
171
|
-
|
|
172
|
-
|
|
197
|
+
while choices:
|
|
198
|
+
if additional:
|
|
199
|
+
question = "Add another named service instance?"
|
|
200
|
+
elif has_primary:
|
|
201
|
+
question = "Add another service as a named instance?"
|
|
202
|
+
else:
|
|
203
|
+
question = "Add a named service instance?"
|
|
204
|
+
if not wizard.confirm(question, default=False):
|
|
173
205
|
break
|
|
174
206
|
group = select("Which kind of service?", groups)
|
|
175
|
-
service = select("Which one?",
|
|
207
|
+
service = select("Which one?", choices[group])
|
|
176
208
|
while True:
|
|
177
209
|
name = str(wizard.prompt(
|
|
178
210
|
"Name this instance (its env var prefix and Compose service suffix, e.g. \"analytics\")"
|
|
@@ -188,6 +220,58 @@ def _prompt_additional(registry: Registry, existing: list[AdditionalService]) ->
|
|
|
188
220
|
return additional
|
|
189
221
|
|
|
190
222
|
|
|
223
|
+
def _resolve_services(base: ShipConfig, options: InitOptions, registry: Registry) -> tuple[dict[str, str], list[AdditionalService]]:
|
|
224
|
+
groups = _groups(registry)
|
|
225
|
+
primary = {group: {item.key: item.label for item in registry.in_group(group)} for group in groups}
|
|
226
|
+
named: dict[str, dict[str, str]] = {}
|
|
227
|
+
for group, choices in primary.items():
|
|
228
|
+
eligible = {key: label for key, label in choices.items() if supports_named_instances(registry.services[key])}
|
|
229
|
+
if eligible:
|
|
230
|
+
named[group] = eligible
|
|
231
|
+
named_groups = {group: groups[group] for group in named}
|
|
232
|
+
flags = options.selections or {}
|
|
233
|
+
kinds = {group: groups[group] for group, choices in primary.items() if choices and flags.get(group) is None}
|
|
234
|
+
defaults = [group for group in kinds if base.services.get(group) in primary[group]]
|
|
235
|
+
|
|
236
|
+
existing = [entry for entry in base.additional_services if entry.name not in (options.remove_instances or [])]
|
|
237
|
+
for raw in options.additional or []:
|
|
238
|
+
try:
|
|
239
|
+
group, rest = raw.split("=", 1)
|
|
240
|
+
service, instance = rest.split(":", 1)
|
|
241
|
+
except ValueError as exc:
|
|
242
|
+
raise ConfigError("--additional-service requires GROUP=PROVIDER:NAME.") from exc
|
|
243
|
+
existing.append(AdditionalService(group, service, instance))
|
|
244
|
+
|
|
245
|
+
session = wizard.active.get()
|
|
246
|
+
checkpoint = session.cursor if session else 0
|
|
247
|
+
while True:
|
|
248
|
+
services = {} if options.interactive else dict(base.services)
|
|
249
|
+
selected = _select_many("Select kinds of service", kinds, defaults) if options.interactive and kinds else []
|
|
250
|
+
for group, providers in primary.items():
|
|
251
|
+
answer = flags.get(group)
|
|
252
|
+
if answer is not None and answer != NONE and answer not in providers:
|
|
253
|
+
raise ConfigError(f"Unknown {group} service {answer!r}; use one of {', '.join([*providers, NONE])}.")
|
|
254
|
+
if answer is None and group in selected:
|
|
255
|
+
label = groups[group]
|
|
256
|
+
answer = select(f"Select {_article(label)} {label}", {**providers, NONE: "None"}, base.services.get(group, NONE))
|
|
257
|
+
if answer == NONE:
|
|
258
|
+
services.pop(group, None)
|
|
259
|
+
elif answer is not None:
|
|
260
|
+
services[group] = answer
|
|
261
|
+
|
|
262
|
+
if not options.interactive:
|
|
263
|
+
return services, existing
|
|
264
|
+
additional = existing
|
|
265
|
+
if existing or named:
|
|
266
|
+
additional = _prompt_additional(named_groups, named, existing, has_primary=bool(services))
|
|
267
|
+
if services or additional or not kinds:
|
|
268
|
+
return services, additional
|
|
269
|
+
if select("Set up this project with just the app?", {"app-only": "Use only the app", "choose-services": "Choose services"}) == "app-only":
|
|
270
|
+
return services, additional
|
|
271
|
+
if session:
|
|
272
|
+
session.restart_from(checkpoint)
|
|
273
|
+
|
|
274
|
+
|
|
191
275
|
def _prompt_silo_image(current: str) -> str:
|
|
192
276
|
typer.echo(
|
|
193
277
|
"\nSilo publishes two images of the same release. The standard one is built on RHEL 9, which\n"
|
|
@@ -218,11 +302,111 @@ def _silo_selected(services: dict[str, str], additional: list[AdditionalService]
|
|
|
218
302
|
return services.get("storage") == "silo" or any(entry.service == "silo" for entry in additional)
|
|
219
303
|
|
|
220
304
|
|
|
305
|
+
def _prompt_service_names(config: ShipConfig, name: str) -> dict[str, str]:
|
|
306
|
+
defaults = list(dict.fromkeys([
|
|
307
|
+
"app", *config.services.values(), *(f"{entry.service}-{entry.name}" for entry in config.additional_services),
|
|
308
|
+
]))
|
|
309
|
+
names = {key: config.service_names[key] for key in defaults if key in config.service_names}
|
|
310
|
+
typer.echo('Docker Compose uses the app service name as a hostname. Keep the default "app" if you are unsure. '
|
|
311
|
+
f'Use a unique name such as "{name}-app" when sharing a Docker network with other projects.')
|
|
312
|
+
for key in defaults:
|
|
313
|
+
current = names.get(key, key)
|
|
314
|
+
taken = {names.get(other, other) for other in defaults if other != key} | config.processes.keys()
|
|
315
|
+
label = "App service name" if key == "app" else f"Compose service name for {key}"
|
|
316
|
+
while True:
|
|
317
|
+
answer = str(wizard.prompt(label, default=current)).strip() or current
|
|
318
|
+
if answer != key and not SERVICE_NAME.fullmatch(answer):
|
|
319
|
+
typer.echo("Use lowercase letters and digits, with words separated by a hyphen or underscore.", err=True)
|
|
320
|
+
elif answer in taken:
|
|
321
|
+
typer.echo(f'The name "{answer}" is already used by a service or process in this project.', err=True)
|
|
322
|
+
else:
|
|
323
|
+
break
|
|
324
|
+
names[key] = answer
|
|
325
|
+
return {key: value for key, value in names.items() if key != value}
|
|
326
|
+
|
|
327
|
+
|
|
328
|
+
def _port_label(port: Port, config: ShipConfig) -> str:
|
|
329
|
+
if port.variable == "APP_PORT":
|
|
330
|
+
return f"App HTTP ({port.service})"
|
|
331
|
+
if port.variable == "VITE_PORT":
|
|
332
|
+
return f"Vite ({port.service})"
|
|
333
|
+
original = next((key for key, name in config.service_names.items() if name == port.service), port.service)
|
|
334
|
+
provider = next((entry.service for entry in config.additional_services if f"{entry.service}-{entry.name}" == original), original)
|
|
335
|
+
label = {
|
|
336
|
+
("garage", 3900): "Garage S3 API", ("garage", 3903): "Garage admin UI and API",
|
|
337
|
+
("seaweedfs", 8333): "SeaweedFS S3 API", ("seaweedfs", 8888): "SeaweedFS filer UI",
|
|
338
|
+
("meilisearch", 7700): "Meilisearch API and search preview",
|
|
339
|
+
}.get((provider, port.target))
|
|
340
|
+
return f"{label} ({port.service})" if label else port.service
|
|
341
|
+
|
|
342
|
+
|
|
343
|
+
def _host_ports(ports: list[Port], config: ShipConfig, settings: dict[str, str], environment: str) -> dict[str, str]:
|
|
344
|
+
addresses = {}
|
|
345
|
+
preferences = {}
|
|
346
|
+
claimed: set[tuple[str, int]] = set()
|
|
347
|
+
result: dict[str, str] = {}
|
|
348
|
+
for port in ports:
|
|
349
|
+
default = settings.get(port.variable, "")
|
|
350
|
+
host = re.fullmatch(r"((?:\[[0-9a-fA-F:.]+\]|[0-9.]+):)([0-9]+)", default)
|
|
351
|
+
configured = port_number(host[2] if host else default)
|
|
352
|
+
addresses[port.id] = host[1] if host and environment == "production" and isinstance(port.mapping, str) and port.mapping.startswith("${") else ""
|
|
353
|
+
preferences[port.id] = (configured or port.default_host, port.protocol, configured is not None)
|
|
354
|
+
for port in ports:
|
|
355
|
+
fallback = suggest_ports(preferences, claimed)[port.id]
|
|
356
|
+
label = f"{environment.capitalize()} host port for {_port_label(port, config)} · {port.target}/{port.protocol.upper()}"
|
|
357
|
+
while True:
|
|
358
|
+
answer = port_number(str(wizard.prompt(label, default=str(fallback))).strip())
|
|
359
|
+
if answer is None:
|
|
360
|
+
typer.echo("Enter a port number from 1 to 65535.", err=True)
|
|
361
|
+
elif (port.protocol, answer) in claimed:
|
|
362
|
+
typer.echo(f"Port {answer}/{port.protocol} is already assigned.", err=True)
|
|
363
|
+
else:
|
|
364
|
+
break
|
|
365
|
+
claimed.add((port.protocol, answer))
|
|
366
|
+
result[port.variable] = addresses[port.id] + str(answer)
|
|
367
|
+
del preferences[port.id]
|
|
368
|
+
return result
|
|
369
|
+
|
|
370
|
+
|
|
371
|
+
def _prompt_ports(config: ShipConfig, root: Path) -> tuple[ShipConfig, dict[str, dict[str, str]]]:
|
|
372
|
+
previous = ShipConfig.lenient(root)
|
|
373
|
+
base = replace(config, publish_ports=True, port_publishing=None)
|
|
374
|
+
publishing: dict[str, list[str]] = {}
|
|
375
|
+
settings: dict[str, dict[str, str]] = {}
|
|
376
|
+
for environment in ("development", "production"):
|
|
377
|
+
production = environment == "production"
|
|
378
|
+
model = build_compose(base, root, production=production)
|
|
379
|
+
available = available_ports(model["services"], production=production)
|
|
380
|
+
if config.port_publishing is not None:
|
|
381
|
+
defaults = []
|
|
382
|
+
old_names = {name: key for key, name in previous.service_names.items()} if previous else {}
|
|
383
|
+
for value in config.port_publishing[environment]:
|
|
384
|
+
service, target = value.split(":", 1)
|
|
385
|
+
key = old_names.get(service, service)
|
|
386
|
+
defaults.append(f"{config.service_names.get(key, key)}:{target}")
|
|
387
|
+
else:
|
|
388
|
+
defaults = [port.id for port in available.values() if port.legacy and (not production or config.publish_ports)]
|
|
389
|
+
if production:
|
|
390
|
+
terminal.note("Published production ports may be public. Clear App HTTP to use a proxy on the Docker network.")
|
|
391
|
+
labels = {key: f"{_port_label(port, config)} · {port.target}/{port.protocol.upper()}" for key, port in available.items()}
|
|
392
|
+
selected = _select_many(f"Publish ports in {environment}", labels, [key for key in defaults if key in labels]) if labels else []
|
|
393
|
+
ports = [available[key] for key in selected]
|
|
394
|
+
if len({port.variable for port in ports}) != len(ports):
|
|
395
|
+
raise ConfigError(f"Selected {environment} ports share a host port setting. Select only one endpoint per setting.")
|
|
396
|
+
path = root / (".env.production" if production else ".env")
|
|
397
|
+
if not production and not path.is_file():
|
|
398
|
+
path = root / ".env.example"
|
|
399
|
+
publishing[environment] = selected
|
|
400
|
+
settings[environment] = _host_ports(ports, config, read_env(path), environment)
|
|
401
|
+
return replace(config, port_publishing=publishing, publish_ports=False), settings
|
|
402
|
+
|
|
403
|
+
|
|
221
404
|
def resolve_config(root: Path, options: InitOptions) -> ShipConfig:
|
|
222
405
|
"""Combine flags, answers, the existing ship.json and detection into the new config."""
|
|
223
406
|
existing = ShipConfig.lenient(root) if (root / "ship.json").exists() else None
|
|
224
|
-
base = existing or ShipConfig()
|
|
407
|
+
base = existing or ShipConfig(python=NEW_PROJECT_PYTHON)
|
|
225
408
|
name = options.name or base.name or project_name(base, root)
|
|
409
|
+
wizard.stage("Application")
|
|
226
410
|
if interactive := options.interactive:
|
|
227
411
|
if not options.name:
|
|
228
412
|
name = str(wizard.prompt("Project name (keep stable after deployment)", default=name)).strip()
|
|
@@ -260,42 +444,10 @@ def resolve_config(root: Path, options: InitOptions) -> ShipConfig:
|
|
|
260
444
|
server = select(f"Select a web server for this {interface.upper()} app", choices, server)
|
|
261
445
|
registry.server(replace(base, server=server), interface) # Rejects a server that can't run this app.
|
|
262
446
|
|
|
263
|
-
|
|
264
|
-
|
|
265
|
-
|
|
266
|
-
|
|
267
|
-
session = wizard.active.get()
|
|
268
|
-
if interactive and session and session.rich:
|
|
269
|
-
selected_groups = set(session.ask("checkbox", "Select kinds of service", list(services), groups))
|
|
270
|
-
services = {key: value for key, value in services.items() if key in selected_groups}
|
|
271
|
-
for group, label in groups.items():
|
|
272
|
-
if interactive and group not in selected_groups and flags.get(group) is None:
|
|
273
|
-
continue
|
|
274
|
-
choices = {NONE: "None", **{item.key: item.label for item in registry.in_group(group)}}
|
|
275
|
-
flagged = flags.get(group)
|
|
276
|
-
if flagged is not None:
|
|
277
|
-
if flagged != NONE and flagged not in choices:
|
|
278
|
-
raise ConfigError(f"Unknown {group} service {flagged!r}; use one of {', '.join(choices)}.")
|
|
279
|
-
answer = flagged
|
|
280
|
-
elif interactive and len(choices) > 1:
|
|
281
|
-
answer = select(f"Select {_article(label)} {label}", choices, services.get(group, NONE))
|
|
282
|
-
else:
|
|
283
|
-
continue
|
|
284
|
-
if answer == NONE:
|
|
285
|
-
services.pop(group, None)
|
|
286
|
-
else:
|
|
287
|
-
services[group] = answer
|
|
288
|
-
|
|
289
|
-
additional = [entry for entry in base.additional_services if entry.name not in (options.remove_instances or [])]
|
|
290
|
-
for raw in options.additional or []:
|
|
291
|
-
try:
|
|
292
|
-
group, rest = raw.split("=", 1)
|
|
293
|
-
service, instance = rest.split(":", 1)
|
|
294
|
-
except ValueError as exc:
|
|
295
|
-
raise ConfigError("--additional-service requires GROUP=PROVIDER:NAME.") from exc
|
|
296
|
-
additional.append(AdditionalService(group, service, instance))
|
|
297
|
-
if interactive:
|
|
298
|
-
additional = _prompt_additional(registry, additional)
|
|
447
|
+
if framework != base.framework:
|
|
448
|
+
registry = load_extensions(replace(base, framework=framework))
|
|
449
|
+
wizard.stage("Services")
|
|
450
|
+
services, additional = _resolve_services(base, options, registry)
|
|
299
451
|
|
|
300
452
|
silo_image = options.silo_image or base.silo_image
|
|
301
453
|
if options.silo_image and options.silo_image not in SILO_IMAGES:
|
|
@@ -309,7 +461,7 @@ def resolve_config(root: Path, options: InitOptions) -> ShipConfig:
|
|
|
309
461
|
if problem:
|
|
310
462
|
raise ConfigError(problem)
|
|
311
463
|
elif interactive:
|
|
312
|
-
python = _prompt_python(base.python
|
|
464
|
+
python = _prompt_python(base.python)
|
|
313
465
|
|
|
314
466
|
processes = {key: value for key, value in base.processes.items() if key not in (options.remove_processes or [])}
|
|
315
467
|
for raw in options.process_options or []:
|
|
@@ -322,8 +474,9 @@ def resolve_config(root: Path, options: InitOptions) -> ShipConfig:
|
|
|
322
474
|
raise ConfigError(f"Invalid JSON process {key!r}.") from exc
|
|
323
475
|
networks = None if options.clear_networks else options.networks if options.networks is not None else base.external_network
|
|
324
476
|
if interactive:
|
|
477
|
+
wizard.stage("Processes and networking")
|
|
325
478
|
processes = {key: value for key, value in processes.items() if wizard.confirm(f"Keep process {key}?", default=True)}
|
|
326
|
-
for key, value in process_suggestions(adapter, replace(base, framework=framework, app=app), root).items():
|
|
479
|
+
for key, value in process_suggestions(adapter, replace(base, framework=framework, app=app, services=services), root).items():
|
|
327
480
|
if key not in processes and wizard.confirm(f"Run suggested process {key} in production?", default=False):
|
|
328
481
|
processes[key] = value
|
|
329
482
|
while wizard.confirm("Add a custom production process?", default=False):
|
|
@@ -331,7 +484,9 @@ def resolve_config(root: Path, options: InitOptions) -> ShipConfig:
|
|
|
331
484
|
command = str(wizard.prompt("Process command")).strip()
|
|
332
485
|
definition: dict[str, Any] = {"command": command}
|
|
333
486
|
if wizard.confirm("Does this process receive HTTP or WebSocket traffic?", default=False):
|
|
334
|
-
|
|
487
|
+
while (port := port_number(str(wizard.prompt("Container port")).strip())) is None:
|
|
488
|
+
terminal.warning("Enter a port number from 1 to 65535.")
|
|
489
|
+
definition["http"] = {"port": port,
|
|
335
490
|
"role": str(wizard.prompt("HTTP role", default="websocket")),
|
|
336
491
|
"health": str(wizard.prompt("Healthy path (empty when unknown)", default="")) or None,
|
|
337
492
|
"urlSetting": str(wizard.prompt("Public URL setting name (empty when unknown)", default="")) or None}
|
|
@@ -339,10 +494,6 @@ def resolve_config(root: Path, options: InitOptions) -> ShipConfig:
|
|
|
339
494
|
if health:
|
|
340
495
|
definition["healthcheck"] = health
|
|
341
496
|
processes[key] = definition
|
|
342
|
-
if options.networks is None and not options.clear_networks:
|
|
343
|
-
current = ",".join(base.external_networks)
|
|
344
|
-
answer = str(wizard.prompt("External networks (comma-separated, optional)", default=current)).strip()
|
|
345
|
-
networks = [item.strip() for item in answer.split(",") if item.strip()] or None
|
|
346
497
|
result = replace(
|
|
347
498
|
base,
|
|
348
499
|
name=name,
|
|
@@ -360,6 +511,12 @@ def resolve_config(root: Path, options: InitOptions) -> ShipConfig:
|
|
|
360
511
|
node_assets=base.node_assets if options.node_assets is None else options.node_assets,
|
|
361
512
|
django_collectstatic=base.django_collectstatic and framework == "django",
|
|
362
513
|
)
|
|
514
|
+
if interactive:
|
|
515
|
+
result = replace(result, service_names=_prompt_service_names(result, name))
|
|
516
|
+
if options.networks is None and not options.clear_networks:
|
|
517
|
+
current = ",".join(base.external_networks)
|
|
518
|
+
answer = str(wizard.prompt("External networks (comma-separated, optional)", default=current)).strip()
|
|
519
|
+
result = replace(result, external_network=[item.strip() for item in answer.split(",") if item.strip()] or None)
|
|
363
520
|
checked, problems = ShipConfig.from_data(result.to_json())
|
|
364
521
|
if problems:
|
|
365
522
|
raise ConfigError(" ".join(problems))
|
|
@@ -410,6 +567,9 @@ def _vite_reminder(root: Path, config: ShipConfig) -> str | None:
|
|
|
410
567
|
dependencies = {**data.get("dependencies", {}), **data.get("devDependencies", {})} if isinstance(data, dict) else {}
|
|
411
568
|
if "vite" not in dependencies:
|
|
412
569
|
return None
|
|
570
|
+
node = config.service_names.get("node", "node")
|
|
571
|
+
if config.port_publishing is not None and f"{node}:5173" not in config.port_publishing["development"]:
|
|
572
|
+
return "Publish the Vite endpoint in development to reach the dev server and HMR from the host browser."
|
|
413
573
|
for name in ("vite.config.js", "vite.config.ts", "vite.config.mjs", "vite.config.mts", "vite.config.cjs", "vite.config.cts"):
|
|
414
574
|
config_file = root / name
|
|
415
575
|
if config_file.is_file() and re.search(r"0\.0\.0\.0|host:\s*true", config_file.read_text(encoding="utf-8")):
|
|
@@ -425,6 +585,7 @@ def run_init(root: Path, options: InitOptions) -> int:
|
|
|
425
585
|
session = wizard.terminal_wizard()
|
|
426
586
|
token = wizard.active.set(session)
|
|
427
587
|
try:
|
|
588
|
+
terminal.heading("Ship · Initialize project")
|
|
428
589
|
while True:
|
|
429
590
|
try:
|
|
430
591
|
return _run_init(root, options)
|
|
@@ -435,40 +596,101 @@ def run_init(root: Path, options: InitOptions) -> int:
|
|
|
435
596
|
|
|
436
597
|
|
|
437
598
|
def _run_init(root: Path, options: InitOptions) -> int:
|
|
438
|
-
dockerfile = root /
|
|
599
|
+
dockerfile = root / DOCKER_DIRECTORY / "Dockerfile"
|
|
439
600
|
had_config = (root / "ship.json").exists()
|
|
440
601
|
if dockerfile.exists() and not had_config and not options.force:
|
|
441
|
-
raise ConfigError("ship/Dockerfile already exists; use --force to replace it.")
|
|
602
|
+
raise ConfigError("docker/ship/Dockerfile already exists; use --force to replace it.")
|
|
442
603
|
config = resolve_config(root, options)
|
|
604
|
+
if not had_config and config.port_publishing is None:
|
|
605
|
+
development = available_ports(build_compose(config, root)["services"], production=False)
|
|
606
|
+
config = replace(config, port_publishing={
|
|
607
|
+
"development": [port.id for port in development.values() if port.legacy],
|
|
608
|
+
"production": [f"{config.app_service}:8000"],
|
|
609
|
+
})
|
|
610
|
+
host_ports = None
|
|
611
|
+
if options.interactive:
|
|
612
|
+
wizard.stage("Published ports")
|
|
613
|
+
config, host_ports = _prompt_ports(config, root)
|
|
443
614
|
# Validate the complete model before writing any project file.
|
|
444
|
-
build_compose(config, root)
|
|
445
|
-
|
|
615
|
+
models = {"development": build_compose(config, root), "production": build_compose(config, root, production=True)}
|
|
616
|
+
advice = setup_advice(config, root)
|
|
446
617
|
for problem in (server_stub_problem(root, config), asset_stub_problem(root, config)):
|
|
447
618
|
if problem and dockerfile.exists() and not options.force:
|
|
448
619
|
raise ConfigError(problem)
|
|
449
|
-
|
|
450
|
-
typer.echo("Planned ship.json:\n" + json.dumps(config.to_json(), indent=2))
|
|
620
|
+
_show_plan(config, root, models, host_ports)
|
|
451
621
|
if options.interactive and not wizard.confirm("Write configuration, templates and missing environment settings?", default=True):
|
|
452
|
-
|
|
622
|
+
typer.echo("Initialization cancelled. No project files were written.")
|
|
623
|
+
return 0
|
|
624
|
+
terminal.note("Preparing Ship project files…")
|
|
453
625
|
require_uv(interactive=options.interactive)
|
|
454
626
|
published = publish_stubs(root, config, force=options.force)
|
|
455
627
|
config.write(root)
|
|
628
|
+
if archive_legacy_directory(root):
|
|
629
|
+
typer.echo("Moved previous Docker files to docker/ship-legacy/. Review any customizations and update paths in your Compose override.")
|
|
630
|
+
if not publish_launcher(root):
|
|
631
|
+
typer.echo("Kept the existing project path `ship`. Use the installed `ship` command.")
|
|
456
632
|
ensure_dockerignore(root)
|
|
457
633
|
ensure_gitignore(root)
|
|
458
|
-
|
|
634
|
+
previous_settings = {filename: read_env(root / filename) for filename in ENV_FILES}
|
|
635
|
+
managed = ensure_environment(config, root, host_ports)
|
|
636
|
+
for filename in ENV_FILES:
|
|
637
|
+
rows = environment_rows(config, root, filename, previous_settings[filename], managed[filename])
|
|
638
|
+
terminal.table(filename, ("Key", "Value", "Used for", "Status"), rows)
|
|
459
639
|
for message in environment_warnings(config, root):
|
|
460
|
-
|
|
640
|
+
terminal.warning(message)
|
|
461
641
|
if not published:
|
|
462
642
|
warning = stub_version_warning(root)
|
|
463
643
|
if warning:
|
|
464
|
-
|
|
644
|
+
terminal.warning(warning)
|
|
465
645
|
reminder = _vite_reminder(root, config)
|
|
646
|
+
dependencies = dependency_advice(config, root)
|
|
647
|
+
if dependencies:
|
|
648
|
+
terminal.table("Suggested application dependencies", ("Service", "Package"), dependencies)
|
|
649
|
+
if (root / "pyproject.toml").is_file():
|
|
650
|
+
terminal.note("Add the clients your app uses with `ship uv add PACKAGE`. Use `--dev` for test-only packages.")
|
|
651
|
+
else:
|
|
652
|
+
terminal.note("Add the clients your app uses to requirements.txt. Rebuild with `ship up` after changing dependencies.")
|
|
653
|
+
if reminder or advice:
|
|
654
|
+
terminal.heading("Application setup")
|
|
466
655
|
if reminder:
|
|
467
|
-
|
|
656
|
+
terminal.note(reminder, err=True)
|
|
657
|
+
for item in advice:
|
|
658
|
+
terminal.note(item.message, err=True)
|
|
468
659
|
if published:
|
|
469
|
-
|
|
470
|
-
|
|
660
|
+
terminal.success(f"Wrote ship.json and published docker/ship/ (python-ship {__version__}). "
|
|
661
|
+
"Run `ship up` to build and start the environment.")
|
|
471
662
|
else:
|
|
472
|
-
|
|
663
|
+
terminal.success("Updated ship.json and kept your docker/ship/Dockerfile. Run `ship up` to apply the changes.")
|
|
473
664
|
return 0
|
|
474
665
|
|
|
666
|
+
|
|
667
|
+
def _show_plan(config: ShipConfig, root: Path, models: dict[str, dict[str, Any]],
|
|
668
|
+
host_ports: dict[str, dict[str, str]] | None) -> None:
|
|
669
|
+
rows = [("Project", config.name or root.name), ("Application", f"{config.framework} · {config.app} ({config.app_service})"),
|
|
670
|
+
("Runtime", f"Python {config.python} · {config.server or 'automatic server'}")]
|
|
671
|
+
services = [f"{key} ({config.service_names[key]})" if key in config.service_names else key
|
|
672
|
+
for key in config.services.values()]
|
|
673
|
+
services.extend(f"{entry.service} ({config.service_names.get(f'{entry.service}-{entry.name}', entry.name)})"
|
|
674
|
+
for entry in config.additional_services)
|
|
675
|
+
rows.append(("Services", ", ".join(services) or "App only"))
|
|
676
|
+
for environment, model in models.items():
|
|
677
|
+
development = environment == "development"
|
|
678
|
+
values = read_env(root / (".env" if development else ".env.production"))
|
|
679
|
+
values.update((host_ports or {}).get(environment, {}))
|
|
680
|
+
ports = available_ports(model["services"], production=not development)
|
|
681
|
+
published = []
|
|
682
|
+
for port in ports.values():
|
|
683
|
+
if port.legacy:
|
|
684
|
+
value = values.get(port.variable, "")
|
|
685
|
+
host = value if re.fullmatch(r"(?:(?:\[[0-9a-fA-F:.]+\]|[0-9.]+):)?[0-9]{1,5}", value) else str(port.default_host)
|
|
686
|
+
published.append(f"{port.id} → {host}")
|
|
687
|
+
rows.append((f"{environment.capitalize()} ports", ", ".join(published) or "None"))
|
|
688
|
+
if config.processes:
|
|
689
|
+
rows.append(("Production processes", ", ".join(config.processes)))
|
|
690
|
+
if config.external_networks:
|
|
691
|
+
rows.append(("External networks", ", ".join(config.external_networks)))
|
|
692
|
+
if config.deploy_commands:
|
|
693
|
+
rows.append(("Deploy commands", str(len(config.deploy_commands))))
|
|
694
|
+
terminal.table("Review setup", ("Setting", "Selection"), rows)
|
|
695
|
+
terminal.note("Writes ship.json, docker/ship/, the launcher, ignore files, and environment settings.")
|
|
696
|
+
|