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
python_ship/cli.py
CHANGED
|
@@ -7,24 +7,33 @@ adapter's console commands such as Django's `manage`).
|
|
|
7
7
|
|
|
8
8
|
from __future__ import annotations
|
|
9
9
|
|
|
10
|
-
from collections.abc import Callable
|
|
10
|
+
from collections.abc import Callable, Iterator
|
|
11
|
+
from contextlib import contextmanager
|
|
11
12
|
from contextvars import ContextVar
|
|
13
|
+
from dataclasses import replace
|
|
12
14
|
import os
|
|
13
15
|
from pathlib import Path
|
|
14
16
|
import re
|
|
15
17
|
import shutil
|
|
16
18
|
import subprocess
|
|
17
19
|
import sys
|
|
18
|
-
from
|
|
20
|
+
from tempfile import TemporaryDirectory
|
|
21
|
+
from typing import Annotated, Any, NoReturn, cast
|
|
22
|
+
from uuid import uuid4
|
|
19
23
|
|
|
20
24
|
import typer
|
|
25
|
+
from typer.core import TyperGroup
|
|
21
26
|
|
|
22
|
-
from . import __version__
|
|
27
|
+
from . import __version__, terminal
|
|
23
28
|
from .build_environment import build_problems
|
|
24
|
-
from .capabilities import release_description, required_setting_problems
|
|
29
|
+
from .capabilities import release_description, required_setting_problems, setup_advice
|
|
25
30
|
from .compose import (
|
|
26
31
|
adapter_problems,
|
|
27
32
|
build_compose,
|
|
33
|
+
compose_path,
|
|
34
|
+
current_development_compose_path,
|
|
35
|
+
host_user,
|
|
36
|
+
render,
|
|
28
37
|
resolve_selections,
|
|
29
38
|
selection_problems,
|
|
30
39
|
server_for,
|
|
@@ -33,7 +42,9 @@ from .compose import (
|
|
|
33
42
|
from .config import ConfigError, ShipConfig
|
|
34
43
|
from .contracts import ShipEnvironment
|
|
35
44
|
from .environment import environment_warnings
|
|
45
|
+
from .image_build import build_images, built_stack_prefix, run_pull_args
|
|
36
46
|
from .init import InitOptions, ensure_dockerignore, ensure_gitignore, interactive_terminal, run_init
|
|
47
|
+
from .layout import docker_directory
|
|
37
48
|
from .mutagen import enabled as mutagen_enabled
|
|
38
49
|
from .mutagen import start as start_mutagen
|
|
39
50
|
from .mutagen import stop as stop_mutagen
|
|
@@ -50,9 +61,29 @@ OVERRIDE_FILES = (
|
|
|
50
61
|
)
|
|
51
62
|
PROXY_CONTEXT = {"allow_extra_args": True, "ignore_unknown_options": True, "help_option_names": []}
|
|
52
63
|
UV_STATEFUL = {"sync", "run", "pip", "python", "tool", "venv"}
|
|
64
|
+
FRONTEND_SETUP = {"add", "ci", "dedupe", "init", "install", "remove", "rm", "uninstall", "up", "update", "upgrade"}
|
|
53
65
|
|
|
54
66
|
_raw_argv: ContextVar[list[str] | None] = ContextVar("ship_raw_argv", default=None)
|
|
55
67
|
_project_root: ContextVar[Path | None] = ContextVar("ship_project_root", default=None)
|
|
68
|
+
_verbose_builds: ContextVar[bool] = ContextVar("ship_verbose_builds", default=False)
|
|
69
|
+
|
|
70
|
+
|
|
71
|
+
class ShipHelpGroup(TyperGroup):
|
|
72
|
+
def format_commands(self, ctx: Any, formatter: Any) -> None:
|
|
73
|
+
groups: dict[str, list[tuple[str, str]]] = {
|
|
74
|
+
group: [] for group in ("Project setup", "Development", "Troubleshooting", "Production", "Command-line tools")
|
|
75
|
+
}
|
|
76
|
+
for name in self.list_commands(ctx):
|
|
77
|
+
command = self.get_command(ctx, name)
|
|
78
|
+
if command is None or command.hidden:
|
|
79
|
+
continue
|
|
80
|
+
group = getattr(command, "rich_help_panel", None) or "Other commands"
|
|
81
|
+
summary = command.get_short_help_str(max(20, formatter.width - 24))
|
|
82
|
+
groups.setdefault(group, []).append((terminal.command_name(name), summary))
|
|
83
|
+
for group, rows in groups.items():
|
|
84
|
+
if rows:
|
|
85
|
+
with formatter.section(group):
|
|
86
|
+
formatter.write_dl(rows)
|
|
56
87
|
|
|
57
88
|
|
|
58
89
|
# Helpers ----------------------------------------------------------------------------------------
|
|
@@ -70,6 +101,8 @@ def proxy_tail(command: str, count: int) -> list[str]:
|
|
|
70
101
|
index += 2
|
|
71
102
|
elif argv[index].startswith("--project-directory="):
|
|
72
103
|
index += 1
|
|
104
|
+
elif argv[index] in {"-v", "--verbose"}:
|
|
105
|
+
index += 1
|
|
73
106
|
else:
|
|
74
107
|
break
|
|
75
108
|
if index >= len(argv) or argv[index] != command:
|
|
@@ -81,10 +114,6 @@ def fail(message: str) -> NoReturn:
|
|
|
81
114
|
raise ConfigError(message)
|
|
82
115
|
|
|
83
116
|
|
|
84
|
-
def warn(message: str) -> None:
|
|
85
|
-
typer.echo(f"ship: warning: {message}", err=True)
|
|
86
|
-
|
|
87
|
-
|
|
88
117
|
def require_docker() -> None:
|
|
89
118
|
if shutil.which("docker") is None:
|
|
90
119
|
fail("Docker is required for this command; install Docker Desktop or Docker Engine with Compose v2.")
|
|
@@ -94,9 +123,15 @@ def override_file(project: Path) -> Path | None:
|
|
|
94
123
|
return next((project / name for name in OVERRIDE_FILES if (project / name).is_file()), None)
|
|
95
124
|
|
|
96
125
|
|
|
97
|
-
def compose_prefix(project: Path, config: ShipConfig) -> list[str]:
|
|
126
|
+
def compose_prefix(project: Path, config: ShipConfig, *, regenerate: bool = False) -> list[str]:
|
|
98
127
|
"""The `docker compose` prefix every development command shares, with the override file applied."""
|
|
99
|
-
|
|
128
|
+
active = current_development_compose_path(project)
|
|
129
|
+
if not regenerate and active != compose_path(project):
|
|
130
|
+
return _compose_args(project, active)
|
|
131
|
+
return _compose_args(project, write_compose(config, project))
|
|
132
|
+
|
|
133
|
+
|
|
134
|
+
def _compose_args(project: Path, path: Path) -> list[str]:
|
|
100
135
|
require_docker()
|
|
101
136
|
prefix = ["docker", "compose", "--project-directory", str(project), "-f", str(path)]
|
|
102
137
|
override = override_file(project)
|
|
@@ -105,6 +140,109 @@ def compose_prefix(project: Path, config: ShipConfig) -> list[str]:
|
|
|
105
140
|
return prefix
|
|
106
141
|
|
|
107
142
|
|
|
143
|
+
def existing_compose_prefix(project: Path) -> list[str]:
|
|
144
|
+
path = current_development_compose_path(project)
|
|
145
|
+
if not path.is_file():
|
|
146
|
+
fail("The development Compose file is missing; run `ship up` first.")
|
|
147
|
+
return _compose_args(project, path)
|
|
148
|
+
|
|
149
|
+
|
|
150
|
+
def service_running(project: Path, service: str) -> bool:
|
|
151
|
+
if not current_development_compose_path(project).is_file():
|
|
152
|
+
return False
|
|
153
|
+
command = existing_compose_prefix(project) + ["ps", "--services", "--status", "running"]
|
|
154
|
+
result = subprocess.run(command, cwd=project, capture_output=True, text=True, check=False)
|
|
155
|
+
if result.returncode:
|
|
156
|
+
fail(f"Could not inspect the development stack: {result.stderr.strip()}")
|
|
157
|
+
return service in result.stdout.splitlines()
|
|
158
|
+
|
|
159
|
+
|
|
160
|
+
@contextmanager
|
|
161
|
+
def temporary_compose(project: Path, config: ShipConfig) -> Iterator[list[str]]:
|
|
162
|
+
problems = stub_problems(project, config)
|
|
163
|
+
if problems:
|
|
164
|
+
fail(" ".join(problems))
|
|
165
|
+
model = build_compose(config, project, direct_bind=True)
|
|
166
|
+
with TemporaryDirectory(prefix="ship-setup-") as directory:
|
|
167
|
+
path = Path(directory) / "compose.json"
|
|
168
|
+
path.write_text(render(model), encoding="utf-8")
|
|
169
|
+
yield _compose_args(project, path)
|
|
170
|
+
|
|
171
|
+
|
|
172
|
+
def _split_run_args(arguments: list[str]) -> tuple[list[str], list[str]]:
|
|
173
|
+
environment = []
|
|
174
|
+
while arguments and (arguments[0] in ("-e", "--env") or arguments[0].startswith("--env=")):
|
|
175
|
+
option, *arguments = arguments
|
|
176
|
+
if option.startswith("--env="):
|
|
177
|
+
value = option.split("=", 1)[1]
|
|
178
|
+
elif arguments:
|
|
179
|
+
value, *arguments = arguments
|
|
180
|
+
else:
|
|
181
|
+
fail("ship run --env expects NAME=value before the command.")
|
|
182
|
+
if not re.match(r"^[A-Za-z_][A-Za-z0-9_]*=", value):
|
|
183
|
+
fail("ship run --env expects NAME=value before the command.")
|
|
184
|
+
environment += ["--env", value]
|
|
185
|
+
if arguments[:1] == ["--"]:
|
|
186
|
+
arguments = arguments[1:]
|
|
187
|
+
if not arguments or not arguments[0] or arguments[0].startswith("-"):
|
|
188
|
+
fail("Usage: ship run [--env NAME=value] [--] COMMAND [ARGS...].")
|
|
189
|
+
return environment, arguments
|
|
190
|
+
|
|
191
|
+
|
|
192
|
+
def development_run(project: Path, config: ShipConfig, service: str, command: list[str], environment: list[str]) -> int:
|
|
193
|
+
with temporary_compose(project, config) as prefix:
|
|
194
|
+
code = _build_development_service(prefix, project, service)
|
|
195
|
+
if code:
|
|
196
|
+
return code
|
|
197
|
+
name = f"ship-run-{uuid4().hex}"
|
|
198
|
+
user = host_user(replace(config, host_user=True), direct_bind=True) if service == config.app_service else None
|
|
199
|
+
identity = ["--user", user, "--env", "HOME=/tmp"] if user else []
|
|
200
|
+
terminal = [] if interactive_terminal() else ["-T"]
|
|
201
|
+
arguments = ["run", "--rm", "--no-deps", *run_pull_args(prefix, project, service), "--name", name,
|
|
202
|
+
"--entrypoint", "/bin/sh", *terminal, *identity, *environment]
|
|
203
|
+
result = None
|
|
204
|
+
try:
|
|
205
|
+
result = run(prefix + arguments + [service, "-c", 'exec "$@"', "ship-run", *command], project)
|
|
206
|
+
return result
|
|
207
|
+
finally:
|
|
208
|
+
if result != 0:
|
|
209
|
+
_remove_setup_container(project, name)
|
|
210
|
+
|
|
211
|
+
|
|
212
|
+
def _build_development_service(prefix: list[str], project: Path, service: str) -> int:
|
|
213
|
+
return build_images(prefix + ["--progress", "plain", "build", service], project,
|
|
214
|
+
f"Building the development image for {service}…", verbose=_verbose_builds.get())
|
|
215
|
+
|
|
216
|
+
|
|
217
|
+
def _remove_setup_container(project: Path, name: str) -> None:
|
|
218
|
+
try:
|
|
219
|
+
subprocess.run(["docker", "rm", "--force", "--volumes", name], cwd=project,
|
|
220
|
+
stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, check=False)
|
|
221
|
+
except OSError:
|
|
222
|
+
pass
|
|
223
|
+
|
|
224
|
+
|
|
225
|
+
@contextmanager
|
|
226
|
+
def frontend_setup_session(project: Path, config: ShipConfig, service: str) -> Iterator[Callable[[list[str]], int]]:
|
|
227
|
+
if service_running(project, service):
|
|
228
|
+
prefix = existing_compose_prefix(project)
|
|
229
|
+
yield lambda arguments: run(prefix + ["exec", "-T", service, *arguments], project)
|
|
230
|
+
return
|
|
231
|
+
with temporary_compose(project, config) as prefix:
|
|
232
|
+
code = _build_development_service(prefix, project, service)
|
|
233
|
+
if code:
|
|
234
|
+
raise typer.Exit(code)
|
|
235
|
+
name = f"ship-run-{uuid4().hex}"
|
|
236
|
+
try:
|
|
237
|
+
code = run(prefix + ["run", "--detach", "--rm", "--no-deps", *run_pull_args(prefix, project, service),
|
|
238
|
+
"--name", name, "--entrypoint", "sleep", service, "infinity"], project)
|
|
239
|
+
if code:
|
|
240
|
+
raise typer.Exit(code)
|
|
241
|
+
yield lambda arguments: run(["docker", "exec", name, *arguments], project)
|
|
242
|
+
finally:
|
|
243
|
+
_remove_setup_container(project, name)
|
|
244
|
+
|
|
245
|
+
|
|
108
246
|
def application_argv(config: ShipConfig, service: str, arguments: list[str]) -> list[str]:
|
|
109
247
|
# Exec does not invoke Docker ENTRYPOINT; prepare the same service credentials as startup.
|
|
110
248
|
managed = set(config.services.values()) | {entry.service for entry in config.additional_services}
|
|
@@ -126,7 +264,7 @@ def execute(action: Callable[[], int]) -> int:
|
|
|
126
264
|
try:
|
|
127
265
|
return action()
|
|
128
266
|
except (ConfigError, OSError) as exc:
|
|
129
|
-
|
|
267
|
+
terminal.error(str(exc))
|
|
130
268
|
return 1
|
|
131
269
|
|
|
132
270
|
|
|
@@ -137,7 +275,7 @@ def read_config(project: Path) -> ShipConfig:
|
|
|
137
275
|
# Checks shared by config:test, doctor, up, build and release -------------------------------------
|
|
138
276
|
|
|
139
277
|
def config_problems(project: Path, *, production: bool = True) -> list[str]:
|
|
140
|
-
"""Every independent problem with ship.json,
|
|
278
|
+
"""Every independent problem with ship.json, Docker files and both Compose models, in one pass.
|
|
141
279
|
|
|
142
280
|
``production=False`` skips the production model, for development-only diagnostics.
|
|
143
281
|
"""
|
|
@@ -199,10 +337,13 @@ def build_production(project: Path, config: ShipConfig, tag: str) -> tuple[dict[
|
|
|
199
337
|
prefix = ["docker", "compose", "--project-directory", str(project)]
|
|
200
338
|
if env_file.is_file():
|
|
201
339
|
prefix += ["--env-file", str(env_file)]
|
|
202
|
-
command = prefix + ["-f", str(path), "build", *(image["owner"] for image in images)]
|
|
340
|
+
command = prefix + ["-f", str(path), "--progress", "plain", "build", *(image["owner"] for image in images)]
|
|
203
341
|
environment = {**os.environ, **read_env(env_file)}
|
|
204
|
-
|
|
205
|
-
|
|
342
|
+
code = build_images(command, project, f"Building production images for {config.name or project.name}…",
|
|
343
|
+
verbose=_verbose_builds.get(), env=environment)
|
|
344
|
+
if code != 0:
|
|
345
|
+
terminal.error("Building the production images failed. See the Docker output above.")
|
|
346
|
+
raise typer.Exit(code)
|
|
206
347
|
return planned, images
|
|
207
348
|
|
|
208
349
|
|
|
@@ -216,6 +357,7 @@ def version_callback(value: bool) -> None:
|
|
|
216
357
|
|
|
217
358
|
def create_app(adapter_commands: dict[str, list[str]] | None = None) -> typer.Typer:
|
|
218
359
|
app = typer.Typer(
|
|
360
|
+
cls=ShipHelpGroup,
|
|
219
361
|
help="Docker development environments and portable releases for Python web apps.",
|
|
220
362
|
no_args_is_help=True,
|
|
221
363
|
add_completion=True,
|
|
@@ -231,11 +373,13 @@ def create_app(adapter_commands: dict[str, list[str]] | None = None) -> typer.Ty
|
|
|
231
373
|
version: Annotated[bool, typer.Option(
|
|
232
374
|
"--version", "-V", callback=version_callback, is_eager=True, help="Show the python-ship version and exit.",
|
|
233
375
|
)] = False,
|
|
376
|
+
verbose: Annotated[bool, typer.Option("--verbose", "-v", help="Stream image build output.")] = False,
|
|
234
377
|
) -> None:
|
|
235
378
|
if project_directory is not None:
|
|
236
379
|
_project_root.set(project_directory.resolve())
|
|
380
|
+
_verbose_builds.set(verbose)
|
|
237
381
|
|
|
238
|
-
@app.command("init")
|
|
382
|
+
@app.command("init", rich_help_panel="Project setup")
|
|
239
383
|
def init_command(
|
|
240
384
|
name: Annotated[str | None, typer.Option("--name", help="Stable application and release identity.")] = None,
|
|
241
385
|
additional_service: Annotated[list[str] | None, typer.Option("--additional-service", help="GROUP=PROVIDER:NAME; repeatable.")] = None,
|
|
@@ -245,7 +389,7 @@ def create_app(adapter_commands: dict[str, list[str]] | None = None) -> typer.Ty
|
|
|
245
389
|
network: Annotated[list[str] | None, typer.Option("--network", help="External network; repeatable.")] = None,
|
|
246
390
|
no_network: Annotated[bool, typer.Option("--no-network")] = False,
|
|
247
391
|
deploy_command: Annotated[list[str] | None, typer.Option("--deploy-command")] = None,
|
|
248
|
-
broadcasting: Annotated[str | None, typer.Option(help="Real-time server (centrifugo), or none.")] = None,
|
|
392
|
+
broadcasting: Annotated[str | None, typer.Option(help="Real-time server (centrifugo or mercure), or none.")] = None,
|
|
249
393
|
app_target: Annotated[str | None, typer.Option("--app", help="App import target, such as main:app.")] = None,
|
|
250
394
|
framework: Annotated[str | None, typer.Option(help="Framework adapter: generic, django, fastapi, flask, or an extension.")] = None,
|
|
251
395
|
server: Annotated[str | None, typer.Option(help="Web server: uvicorn, hypercorn, granian (ASGI); gunicorn, granian (WSGI); or an extension. Defaults to the one recommended for the app.")] = None,
|
|
@@ -262,10 +406,10 @@ def create_app(adapter_commands: dict[str, list[str]] | None = None) -> typer.Ty
|
|
|
262
406
|
tasks: Annotated[str | None, typer.Option(help="Background task queue (celery), or none.")] = None,
|
|
263
407
|
silo_image: Annotated[str | None, typer.Option("--silo-image", help="Silo image: standard or distroless.")] = None,
|
|
264
408
|
node_assets: Annotated[bool | None, typer.Option("--node-assets/--no-node-assets", help="Build npm assets into the production image.")] = None,
|
|
265
|
-
force: Annotated[bool, typer.Option("--force", help="Republish
|
|
409
|
+
force: Annotated[bool, typer.Option("--force", help="Republish the project Dockerfile, replacing local edits.")] = False,
|
|
266
410
|
no_interaction: Annotated[bool, typer.Option("--no-interaction", "-n", help="Don't prompt; use options, the existing ship.json and detection.")] = False,
|
|
267
411
|
) -> int:
|
|
268
|
-
"""Pick services, write ship.json and publish the
|
|
412
|
+
"""Pick services, write ship.json and publish the project Docker files."""
|
|
269
413
|
options = InitOptions(
|
|
270
414
|
name=name, node=node_version, additional=additional_service, remove_instances=remove_instance, process_options=process,
|
|
271
415
|
remove_processes=remove_process, networks=network, clear_networks=no_network, deploy=deploy_command,
|
|
@@ -278,12 +422,12 @@ def create_app(adapter_commands: dict[str, list[str]] | None = None) -> typer.Ty
|
|
|
278
422
|
)
|
|
279
423
|
return execute(lambda: run_init(root(), options))
|
|
280
424
|
|
|
281
|
-
@app.command("up")
|
|
425
|
+
@app.command("up", rich_help_panel="Development")
|
|
282
426
|
def up_command() -> int:
|
|
283
|
-
"""Generate
|
|
427
|
+
"""Generate the development Compose file and start the stack."""
|
|
284
428
|
return execute(up)
|
|
285
429
|
|
|
286
|
-
@app.command("down")
|
|
430
|
+
@app.command("down", rich_help_panel="Development")
|
|
287
431
|
def down_command(
|
|
288
432
|
volumes: Annotated[bool, typer.Option("--volumes", "-v", help="Also delete named volumes (database and storage data).")] = False,
|
|
289
433
|
) -> int:
|
|
@@ -296,7 +440,26 @@ def create_app(adapter_commands: dict[str, list[str]] | None = None) -> typer.Ty
|
|
|
296
440
|
return run(prefix + ["down", *(["--volumes"] if volumes else [])], project)
|
|
297
441
|
return execute(action)
|
|
298
442
|
|
|
299
|
-
@app.command("
|
|
443
|
+
@app.command("ps", context_settings=PROXY_CONTEXT, rich_help_panel="Development")
|
|
444
|
+
def ps_command(ctx: typer.Context) -> int:
|
|
445
|
+
"""Show development containers and published ports. Compose filters pass through."""
|
|
446
|
+
return execute(lambda: run(existing_compose_prefix(root()) + ["ps", "--all", *proxy_tail("ps", 1)], root()))
|
|
447
|
+
|
|
448
|
+
@app.command("run", context_settings=PROXY_CONTEXT, rich_help_panel="Development",
|
|
449
|
+
options_metavar="[--env NAME=value] [--] COMMAND [ARGS]...")
|
|
450
|
+
def run_command(ctx: typer.Context) -> int:
|
|
451
|
+
"""Run COMMAND in a disposable development app container, with optional --env NAME=value before COMMAND."""
|
|
452
|
+
def action() -> int:
|
|
453
|
+
environment, command = _split_run_args(proxy_tail("run", 1))
|
|
454
|
+
project = root()
|
|
455
|
+
config = read_config(project)
|
|
456
|
+
service = config.app_service
|
|
457
|
+
if command[0] in ("npm", "pnpm", "yarn"):
|
|
458
|
+
service = frontend_service(config, project, command[0])
|
|
459
|
+
return development_run(project, config, service, command, environment)
|
|
460
|
+
return execute(action)
|
|
461
|
+
|
|
462
|
+
@app.command("exec", context_settings=PROXY_CONTEXT, rich_help_panel="Development")
|
|
300
463
|
def exec_command(ctx: typer.Context, service: Annotated[str, typer.Argument(help="Compose service name.")]) -> int:
|
|
301
464
|
"""Run a command in a running service; every following argument is passed through."""
|
|
302
465
|
def action() -> int:
|
|
@@ -309,7 +472,7 @@ def create_app(adapter_commands: dict[str, list[str]] | None = None) -> typer.Ty
|
|
|
309
472
|
return run(prefix + ["exec", *tty_flags(), service, *application_argv(config, service, arguments)], project)
|
|
310
473
|
return execute(action)
|
|
311
474
|
|
|
312
|
-
@app.command("shell")
|
|
475
|
+
@app.command("shell", rich_help_panel="Development")
|
|
313
476
|
def shell_command(service: Annotated[str | None, typer.Argument(help="Compose service name; defaults to the app.")] = None) -> int:
|
|
314
477
|
"""Open an interactive shell (sh) in a running service."""
|
|
315
478
|
def action() -> int:
|
|
@@ -319,7 +482,7 @@ def create_app(adapter_commands: dict[str, list[str]] | None = None) -> typer.Ty
|
|
|
319
482
|
return run(prefix + ["exec", *tty_flags(), service or config.app_service, *application_argv(config, service or config.app_service, ["sh"])], project)
|
|
320
483
|
return execute(action)
|
|
321
484
|
|
|
322
|
-
@app.command("logs")
|
|
485
|
+
@app.command("logs", rich_help_panel="Development")
|
|
323
486
|
def logs_command(
|
|
324
487
|
service: Annotated[str | None, typer.Argument(help="Compose service name; all services when omitted.")] = None,
|
|
325
488
|
follow: Annotated[bool, typer.Option("--follow", "-f", help="Stream new log output.")] = False,
|
|
@@ -331,43 +494,44 @@ def create_app(adapter_commands: dict[str, list[str]] | None = None) -> typer.Ty
|
|
|
331
494
|
return run(prefix + ["logs", *(["--follow"] if follow else []), *([service] if service else [])], project)
|
|
332
495
|
return execute(action)
|
|
333
496
|
|
|
334
|
-
@app.command("db")
|
|
497
|
+
@app.command("db", rich_help_panel="Development")
|
|
335
498
|
def db_command(instance: Annotated[str | None, typer.Argument(help="Name of an additionalServices database; the default database when omitted.")] = None) -> int:
|
|
336
499
|
"""Open a database's interactive client, using credentials from its own container."""
|
|
337
500
|
return execute(lambda: database_shell(instance))
|
|
338
501
|
|
|
339
|
-
@app.command("config:test")
|
|
502
|
+
@app.command("config:test", hidden=True)
|
|
503
|
+
@app.command("check", rich_help_panel="Troubleshooting", short_help="[config:test] Validate settings without Docker.")
|
|
340
504
|
def config_test_command() -> int:
|
|
341
|
-
"""Validate
|
|
505
|
+
"""Validate settings and Compose models without Docker (alias: config:test)."""
|
|
342
506
|
def action() -> int:
|
|
507
|
+
terminal.heading("Ship configuration check")
|
|
343
508
|
project = root()
|
|
344
509
|
problems = config_problems(project)
|
|
345
|
-
for problem in problems:
|
|
346
|
-
typer.echo(f"ship: {problem}", err=True)
|
|
347
510
|
if problems:
|
|
348
|
-
|
|
511
|
+
terminal.diagnostics("Problems", problems)
|
|
512
|
+
terminal.error(f"{len(problems)} problem{'s' if len(problems) != 1 else ''} found.")
|
|
349
513
|
return 1
|
|
350
|
-
|
|
351
|
-
warn(message)
|
|
514
|
+
warnings = environment_warnings(read_config(project), project)
|
|
352
515
|
warning = stub_version_warning(project)
|
|
353
516
|
if warning:
|
|
354
|
-
|
|
355
|
-
|
|
517
|
+
warnings.append(warning)
|
|
518
|
+
terminal.diagnostics("Warnings", warnings, color=typer.colors.YELLOW)
|
|
519
|
+
terminal.success("ship.json, Docker files and both Compose models are valid.")
|
|
356
520
|
return 0
|
|
357
521
|
return execute(action)
|
|
358
522
|
|
|
359
|
-
@app.command("build")
|
|
523
|
+
@app.command("build", rich_help_panel="Production")
|
|
360
524
|
def build_command() -> int:
|
|
361
525
|
"""Build every project-owned production image, tagged locally."""
|
|
362
526
|
def action() -> int:
|
|
363
527
|
project = root()
|
|
364
528
|
_, images = build_production(project, read_config(project), "local")
|
|
365
|
-
|
|
366
|
-
|
|
529
|
+
terminal.table("Production images built", ("Image", "Services"),
|
|
530
|
+
[(image["image"], ", ".join(image["services"])) for image in images])
|
|
367
531
|
return 0
|
|
368
532
|
return execute(action)
|
|
369
533
|
|
|
370
|
-
@app.command("release")
|
|
534
|
+
@app.command("release", rich_help_panel="Production")
|
|
371
535
|
def release_command(
|
|
372
536
|
tag: Annotated[str | None, typer.Option("--tag", help="Release tag, such as 1.2.0.")] = None,
|
|
373
537
|
force: Annotated[bool, typer.Option("--force", help="Explicitly replace an existing release.")] = False,
|
|
@@ -390,11 +554,11 @@ def create_app(adapter_commands: dict[str, list[str]] | None = None) -> typer.Ty
|
|
|
390
554
|
source = source_metadata(project)
|
|
391
555
|
model, _ = build_production(project, config, chosen)
|
|
392
556
|
destination = assemble_release(project, config, model, chosen, force=force, no_env=no_env, source=source)
|
|
393
|
-
|
|
557
|
+
terminal.success(f"Release ready at {destination}")
|
|
394
558
|
return 0
|
|
395
559
|
return execute(action)
|
|
396
560
|
|
|
397
|
-
@app.command("doctor")
|
|
561
|
+
@app.command("doctor", rich_help_panel="Troubleshooting")
|
|
398
562
|
def doctor_command() -> int:
|
|
399
563
|
"""Report versions, stub freshness and the state and health of every container."""
|
|
400
564
|
return execute(doctor)
|
|
@@ -402,28 +566,25 @@ def create_app(adapter_commands: dict[str, list[str]] | None = None) -> typer.Ty
|
|
|
402
566
|
def frontend_proxy(tool: str) -> int:
|
|
403
567
|
project = root()
|
|
404
568
|
config = read_config(project)
|
|
405
|
-
|
|
406
|
-
|
|
407
|
-
if
|
|
408
|
-
|
|
409
|
-
|
|
410
|
-
|
|
411
|
-
|
|
412
|
-
return run(compose_prefix(project, config) + ["exec", *tty_flags(), nodes[0].service_name, tool, *proxy_tail(tool, 1)], project)
|
|
413
|
-
|
|
414
|
-
@app.command("npm", context_settings=PROXY_CONTEXT)
|
|
569
|
+
service = frontend_service(config, project, tool)
|
|
570
|
+
arguments = proxy_tail(tool, 1)
|
|
571
|
+
if arguments and arguments[0] in FRONTEND_SETUP and not service_running(project, service):
|
|
572
|
+
return development_run(project, config, service, [tool, *arguments], [])
|
|
573
|
+
return run(compose_prefix(project, config) + ["exec", *tty_flags(), service, tool, *arguments], project)
|
|
574
|
+
|
|
575
|
+
@app.command("npm", context_settings=PROXY_CONTEXT, rich_help_panel="Development", help="Run npm with the project’s Node service.")
|
|
415
576
|
def npm_command(ctx: typer.Context) -> int:
|
|
416
577
|
return execute(lambda: frontend_proxy("npm"))
|
|
417
578
|
|
|
418
|
-
@app.command("pnpm", context_settings=PROXY_CONTEXT)
|
|
579
|
+
@app.command("pnpm", context_settings=PROXY_CONTEXT, rich_help_panel="Development", help="Run pnpm with the project’s Node service.")
|
|
419
580
|
def pnpm_command(ctx: typer.Context) -> int:
|
|
420
581
|
return execute(lambda: frontend_proxy("pnpm"))
|
|
421
582
|
|
|
422
|
-
@app.command("yarn", context_settings=PROXY_CONTEXT)
|
|
583
|
+
@app.command("yarn", context_settings=PROXY_CONTEXT, rich_help_panel="Development", help="Run Yarn with the project’s Node service.")
|
|
423
584
|
def yarn_command(ctx: typer.Context) -> int:
|
|
424
585
|
return execute(lambda: frontend_proxy("yarn"))
|
|
425
586
|
|
|
426
|
-
@app.command("package-manager")
|
|
587
|
+
@app.command("package-manager", rich_help_panel="Project setup", help="Switch the frontend package manager and reinstall dependencies.")
|
|
427
588
|
def package_manager_command(
|
|
428
589
|
tool: Annotated[str, typer.Argument(help="npm, pnpm or yarn, optionally @EXACT_VERSION.")],
|
|
429
590
|
yes: Annotated[bool, typer.Option("--yes", "-y", help="Confirm lockfile and dependency replacement.")] = False,
|
|
@@ -433,19 +594,21 @@ def create_app(adapter_commands: dict[str, list[str]] | None = None) -> typer.Ty
|
|
|
433
594
|
config = read_config(project)
|
|
434
595
|
if config.services.get("frontend") != "node":
|
|
435
596
|
fail("Select the Node frontend service before switching package managers.")
|
|
597
|
+
if not (project / "package.json").is_file():
|
|
598
|
+
fail("Create package.json before switching package managers.")
|
|
436
599
|
if not yes and (not interactive_terminal() or not typer.confirm("Replace frontend lockfiles and reinstall dependencies?", default=False)):
|
|
437
600
|
fail("Switch cancelled; pass --yes to confirm in automation.")
|
|
438
|
-
prefix = compose_prefix(project, config)
|
|
439
601
|
node = config.service_names.get("node", "node")
|
|
440
|
-
|
|
602
|
+
with frontend_setup_session(project, config, node) as run_on_node:
|
|
603
|
+
switch_manager(project, tool, run_on_node)
|
|
441
604
|
# Only the generated frontend image changes; preserve the application Dockerfile.
|
|
442
605
|
from .package_managers import node_dockerfile
|
|
443
|
-
(project / "
|
|
444
|
-
|
|
606
|
+
(docker_directory(project) / "node/Dockerfile").write_text(node_dockerfile(project, config.node))
|
|
607
|
+
terminal.success("Package manager updated. Review the lockfile, then run `ship up` to rebuild the frontend container.")
|
|
445
608
|
return 0
|
|
446
609
|
return execute(action)
|
|
447
610
|
|
|
448
|
-
@app.command("test", context_settings=PROXY_CONTEXT)
|
|
611
|
+
@app.command("test", context_settings=PROXY_CONTEXT, rich_help_panel="Development", help="Run the selected browser testing workflow.")
|
|
449
612
|
def test_command(ctx: typer.Context) -> int:
|
|
450
613
|
def action() -> int:
|
|
451
614
|
project = root()
|
|
@@ -459,23 +622,53 @@ def create_app(adapter_commands: dict[str, list[str]] | None = None) -> typer.Ty
|
|
|
459
622
|
arguments = arguments[1:]
|
|
460
623
|
prefix = compose_prefix(project, config)
|
|
461
624
|
if selected.service.key == "cypress":
|
|
462
|
-
|
|
625
|
+
code = build_images(prefix + ["--progress", "plain", "build", selected.service_name], project,
|
|
626
|
+
f"Building the Cypress image for {config.name or project.name}…", verbose=_verbose_builds.get())
|
|
627
|
+
if code != 0:
|
|
628
|
+
return code
|
|
629
|
+
return run(prefix + ["run", *run_pull_args(prefix, project, selected.service_name), "--rm", "--no-deps", *tty_flags(), "--entrypoint", "sh", selected.service_name,
|
|
463
630
|
"-c", 'set -eu; mkdir -p /e2e/node_modules; if [ ! -e /e2e/node_modules/cypress ]; then ln -s /usr/local/lib/node_modules/cypress /e2e/node_modules/cypress; fi; exec cypress run "$@"', "ship-cypress", *arguments], project)
|
|
464
631
|
return run(prefix + ["exec", *tty_flags(), config.app_service, *application_argv(config, config.app_service, ["python", "-m", "pytest", *arguments])], project)
|
|
465
632
|
return execute(action)
|
|
466
633
|
|
|
467
|
-
@app.command("uv", context_settings=PROXY_CONTEXT)
|
|
634
|
+
@app.command("uv", context_settings=PROXY_CONTEXT, rich_help_panel="Development")
|
|
468
635
|
def uv_command(ctx: typer.Context) -> int:
|
|
469
636
|
"""Run uv dependency commands (add, remove, lock, tree, ...) in a temporary container."""
|
|
470
637
|
return execute(lambda: uv(proxy_tail("uv", 1)))
|
|
471
638
|
|
|
639
|
+
@app.command("help", rich_help_panel="Command-line tools")
|
|
640
|
+
def help_command(ctx: typer.Context, command: Annotated[str | None, typer.Argument(help="Command name.")] = None) -> int:
|
|
641
|
+
"""List all commands or show help for one command."""
|
|
642
|
+
parent = ctx.find_root()
|
|
643
|
+
if command is None:
|
|
644
|
+
typer.echo(parent.get_help())
|
|
645
|
+
return 0
|
|
646
|
+
selected = cast(TyperGroup, parent.command).get_command(parent, command)
|
|
647
|
+
if selected is None:
|
|
648
|
+
terminal.error(f"No such command {command!r}.")
|
|
649
|
+
return 2
|
|
650
|
+
with selected.make_context(command, [], parent=parent, resilient_parsing=True) as child:
|
|
651
|
+
typer.echo(selected.get_help(child))
|
|
652
|
+
return 0
|
|
653
|
+
|
|
472
654
|
for name, command_prefix in (adapter_commands or {}).items():
|
|
473
|
-
app.command(name, context_settings=PROXY_CONTEXT,
|
|
655
|
+
app.command(name, context_settings=PROXY_CONTEXT, rich_help_panel="Development",
|
|
656
|
+
help=f"Run `{' '.join(command_prefix)}` in the app container; arguments pass through.")(
|
|
474
657
|
_adapter_command(name, command_prefix)
|
|
475
658
|
)
|
|
476
659
|
return app
|
|
477
660
|
|
|
478
661
|
|
|
662
|
+
def frontend_service(config: ShipConfig, project: Path, tool: str) -> str:
|
|
663
|
+
nodes = [item for item in resolve_selections(config, load_extensions(config)) if item.service.key == "node"]
|
|
664
|
+
if len(nodes) != 1:
|
|
665
|
+
fail(f"ship {tool} requires the Node frontend service; select it with ship init --frontend node.")
|
|
666
|
+
manager = inspect_manager(project)
|
|
667
|
+
if manager.name != tool:
|
|
668
|
+
fail(f"This project uses {manager.name}; use ship {manager.name} or ship package-manager.")
|
|
669
|
+
return nodes[0].service_name
|
|
670
|
+
|
|
671
|
+
|
|
479
672
|
def _adapter_command(name: str, command_prefix: list[str]) -> Callable[[typer.Context], int]:
|
|
480
673
|
def command(ctx: typer.Context) -> int:
|
|
481
674
|
def action() -> int:
|
|
@@ -496,11 +689,19 @@ def up() -> int:
|
|
|
496
689
|
fail(" ".join(problems))
|
|
497
690
|
warning = stub_version_warning(project)
|
|
498
691
|
if warning:
|
|
499
|
-
|
|
500
|
-
|
|
692
|
+
terminal.warning(warning)
|
|
693
|
+
for item in setup_advice(config, project):
|
|
694
|
+
if item.before_up:
|
|
695
|
+
terminal.warning(item.message)
|
|
696
|
+
prefix = compose_prefix(project, config, regenerate=True)
|
|
501
697
|
# A session left by an earlier container must go before Compose recreates it.
|
|
502
698
|
stop_mutagen(project, required=mutagen_enabled())
|
|
503
|
-
code =
|
|
699
|
+
code = build_images(prefix + ["--progress", "plain", "build"], project,
|
|
700
|
+
f"Building development images for {config.name or project.name}…", verbose=_verbose_builds.get())
|
|
701
|
+
if code != 0:
|
|
702
|
+
return code
|
|
703
|
+
with built_stack_prefix(prefix, project) as startup:
|
|
704
|
+
code = run(startup + ["up", "--no-build", "--detach"], project)
|
|
504
705
|
if code != 0:
|
|
505
706
|
return code
|
|
506
707
|
model = build_compose(config, project)
|
|
@@ -510,8 +711,10 @@ def up() -> int:
|
|
|
510
711
|
except ConfigError:
|
|
511
712
|
run(prefix + ["down"], project)
|
|
512
713
|
raise
|
|
513
|
-
port = wait_for_stack(prefix, {name for name, service in model["services"].items() if not service.get("profiles")},
|
|
514
|
-
|
|
714
|
+
port = wait_for_stack(prefix, {name for name, service in model["services"].items() if not service.get("profiles")},
|
|
715
|
+
config.app_service, require_port=app_port_expected(config))
|
|
716
|
+
terminal.success(f"The stack is running: http://127.0.0.1:{port}" if port else
|
|
717
|
+
"The stack is running. The app is available on the Docker network.")
|
|
515
718
|
return 0
|
|
516
719
|
|
|
517
720
|
|
|
@@ -568,46 +771,56 @@ def uv(arguments: list[str]) -> int:
|
|
|
568
771
|
return run(command + [image, "uv", *arguments], project)
|
|
569
772
|
|
|
570
773
|
|
|
774
|
+
def app_port_expected(config: ShipConfig) -> bool:
|
|
775
|
+
return config.port_publishing is None or f"{config.app_service}:8000" in config.port_publishing["development"]
|
|
776
|
+
|
|
777
|
+
|
|
571
778
|
def doctor() -> int:
|
|
779
|
+
terminal.heading("Ship doctor")
|
|
572
780
|
project = root()
|
|
573
781
|
problems = config_problems(project, production=False)
|
|
574
|
-
for problem in problems:
|
|
575
|
-
typer.echo(f"ship: {problem}", err=True)
|
|
576
782
|
if problems:
|
|
783
|
+
terminal.diagnostics("Configuration problems", problems)
|
|
577
784
|
return 1
|
|
578
785
|
config = read_config(project)
|
|
579
786
|
model = build_compose(config, project)
|
|
580
|
-
|
|
581
|
-
|
|
582
|
-
|
|
787
|
+
terminal.table("Project", ("Setting", "Value"), [
|
|
788
|
+
("Name", model["name"]),
|
|
789
|
+
("Python", config.python),
|
|
790
|
+
("Node.js", config.node),
|
|
791
|
+
("Framework", config.framework),
|
|
792
|
+
("Server", server_for(config, project).key),
|
|
793
|
+
("Ship", f"python-ship {__version__}"),
|
|
794
|
+
("Published stubs", published_version(project) or "Unknown"),
|
|
795
|
+
])
|
|
583
796
|
warning = stub_version_warning(project)
|
|
584
797
|
if warning:
|
|
585
|
-
|
|
586
|
-
|
|
587
|
-
from .compose import compose_path
|
|
588
|
-
path = compose_path(project)
|
|
589
|
-
if not path.is_file():
|
|
590
|
-
fail("The development Compose file is missing; run ship up first.")
|
|
591
|
-
prefix = ["docker", "compose", "--project-directory", str(project), "-f", str(path)]
|
|
592
|
-
override = override_file(project)
|
|
593
|
-
if override:
|
|
594
|
-
prefix += ["-f", str(override)]
|
|
798
|
+
terminal.warning(warning)
|
|
799
|
+
prefix = existing_compose_prefix(project)
|
|
595
800
|
result = subprocess.run(prefix + ["ps", "--all", "--format", "json"], cwd=project, capture_output=True, text=True, check=False)
|
|
596
801
|
if result.returncode != 0:
|
|
597
802
|
fail(f"Could not inspect Docker Compose: {result.stderr.strip()}. Check that Docker is running.")
|
|
598
803
|
found = records(result.stdout)
|
|
599
|
-
fatal, pending, port = status(found, {name for name, service in model["services"].items() if not service.get("profiles")},
|
|
804
|
+
fatal, pending, port = status(found, {name for name, service in model["services"].items() if not service.get("profiles")},
|
|
805
|
+
config.app_service, require_port=app_port_expected(config))
|
|
806
|
+
rows = []
|
|
600
807
|
for name, service in model["services"].items():
|
|
601
808
|
record = found.get(name, {})
|
|
602
|
-
|
|
603
|
-
|
|
604
|
-
|
|
809
|
+
source = record.get("Image") or service.get("image")
|
|
810
|
+
if not source:
|
|
811
|
+
source = service.get("build", {}).get("dockerfile", "Built from a Dockerfile")
|
|
812
|
+
ports = [
|
|
813
|
+
f"{binding.get('URL') or '*'}:{binding['PublishedPort']} → {binding.get('TargetPort')}/{binding.get('Protocol', 'tcp')}"
|
|
814
|
+
for binding in record.get("Publishers") or [] if binding.get("PublishedPort")
|
|
815
|
+
]
|
|
816
|
+
rows.append((name, record.get("State") or "missing", record.get("Health") or "—", source, ", ".join(ports) or "—"))
|
|
817
|
+
terminal.table("Development services", ("Service", "State", "Health", "Image or build source", "Published ports"), rows)
|
|
605
818
|
if fatal or pending:
|
|
606
|
-
|
|
607
|
-
|
|
608
|
-
typer.echo("ship: run `ship logs SERVICE` to see why, then `ship up` to rebuild or restart the stack.", err=True)
|
|
819
|
+
terminal.diagnostics("Needs attention", [*fatal, *pending])
|
|
820
|
+
terminal.note("Run `ship logs SERVICE` for details, then `ship up` to rebuild or restart the stack.", err=True)
|
|
609
821
|
return 1
|
|
610
|
-
|
|
822
|
+
terminal.success(f"Every service is running. App URL: http://127.0.0.1:{port}" if port else
|
|
823
|
+
"Every service is running. The app is available on the Docker network.")
|
|
611
824
|
return 0
|
|
612
825
|
|
|
613
826
|
|
|
@@ -644,6 +857,7 @@ def main(argv: list[str] | None = None) -> int:
|
|
|
644
857
|
argv = list(sys.argv[1:] if argv is None else argv)
|
|
645
858
|
token = _raw_argv.set(argv)
|
|
646
859
|
root_token = _project_root.set(None)
|
|
860
|
+
verbose_token = _verbose_builds.set(False)
|
|
647
861
|
# Typer detects the shell from the parent process; accept an explicit one for scripts.
|
|
648
862
|
explicit_completion = argv[:1] == ["--show-completion"] and len(argv) > 1 and argv[1] in {
|
|
649
863
|
"bash", "zsh", "fish", "powershell", "pwsh",
|
|
@@ -675,6 +889,7 @@ def main(argv: list[str] | None = None) -> int:
|
|
|
675
889
|
finally:
|
|
676
890
|
_raw_argv.reset(token)
|
|
677
891
|
_project_root.reset(root_token)
|
|
892
|
+
_verbose_builds.reset(verbose_token)
|
|
678
893
|
if explicit_completion:
|
|
679
894
|
if previous is None:
|
|
680
895
|
os.environ.pop("_TYPER_COMPLETE_TEST_DISABLE_SHELL_DETECTION", None)
|