python-ship 0.1.0__py3-none-any.whl → 0.2.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 CHANGED
@@ -1,3 +1,3 @@
1
1
  """Docker development environments and portable releases for Python web apps."""
2
2
 
3
- __version__ = "0.1.0"
3
+ __version__ = "0.2.0"
python_ship/adapters.py CHANGED
@@ -9,7 +9,7 @@ import re
9
9
  from .config import ShipConfig
10
10
  from .contracts import Interface
11
11
 
12
- TARGET = re.compile(r"[A-Za-z_]\w*(?:\.[A-Za-z_]\w*)*:[A-Za-z_]\w*")
12
+ TARGET = re.compile(r"[A-Za-z_][A-Za-z0-9_]*(?:\.[A-Za-z_][A-Za-z0-9_]*)*:[A-Za-z_][A-Za-z0-9_]*(?:\(\))?")
13
13
  # Directories never searched when detecting a project's app module.
14
14
  _SKIP = {".git", ".venv", "venv", "node_modules", "__pycache__", "dist", "build", "ship", "tests", ".tox"}
15
15
 
@@ -58,7 +58,7 @@ def target_problems(project_root: Path, target: str, label: str, example: str) -
58
58
  except SyntaxError as exc:
59
59
  return [f"{label} module {module.relative_to(project_root)} has a syntax error at line {exc.lineno}: {exc.msg}."]
60
60
  names, wildcard = _bindings(module)
61
- callable_name = target.partition(":")[2]
61
+ callable_name = target.partition(":")[2].removesuffix("()")
62
62
  if callable_name not in names and not wildcard:
63
63
  return [f"{label} callable {callable_name!r} is not defined in {module.relative_to(project_root)}."]
64
64
  return []
@@ -104,7 +104,47 @@ def callable_interface(project_root: Path, target: str) -> Interface | None:
104
104
  return None
105
105
 
106
106
 
107
- class GenericAdapter:
107
+ class PythonCapabilities:
108
+ """Optional metadata and process suggestions, requiring actual project evidence."""
109
+
110
+ def describe_release(self, config: ShipConfig, root: Path) -> dict:
111
+ required = []
112
+ if config.framework in ("django", "flask"):
113
+ for path in python_files(root):
114
+ try:
115
+ tree = ast.parse(path.read_text(encoding="utf-8"))
116
+ except (OSError, SyntaxError):
117
+ continue
118
+ for node in ast.walk(tree):
119
+ if not isinstance(node, (ast.Assign, ast.AnnAssign)):
120
+ continue
121
+ targets = node.targets if isinstance(node, ast.Assign) else [node.target]
122
+ if not any(isinstance(target, ast.Name) and target.id == "SECRET_KEY" for target in targets):
123
+ continue
124
+ for child in ast.walk(node.value) if node.value is not None else []:
125
+ # Only explicit environment reads determine a setting name.
126
+ if isinstance(child, ast.Subscript) and isinstance(child.value, ast.Attribute) and child.value.attr == "environ":
127
+ if isinstance(child.slice, ast.Constant) and isinstance(child.slice.value, str):
128
+ required.append(child.slice.value)
129
+ elif isinstance(child, ast.Call) and isinstance(child.func, ast.Attribute) and child.args:
130
+ if child.func.attr in ("getenv", "get") and isinstance(child.args[0], ast.Constant) and isinstance(child.args[0].value, str):
131
+ owner = child.func.value
132
+ if child.func.attr == "getenv" or (isinstance(owner, ast.Attribute) and owner.attr == "environ"):
133
+ required.append(child.args[0].value)
134
+ return {"health": None, "urlSetting": None, "requiredEnv": sorted(set(required))}
135
+
136
+ def suggest_processes(self, config: ShipConfig, root: Path) -> dict:
137
+ manifests = [root / "pyproject.toml", root / "requirements.txt"]
138
+ if not any(path.is_file() and re.search(r"\bcelery\b", path.read_text(encoding="utf-8"), re.I) for path in manifests):
139
+ return {}
140
+ # The app supplies its Celery instance; the environment remains authoritative.
141
+ suggestions = {"celery-beat": "celery -A \"$CELERY_APP\" beat --loglevel=info --schedule=/tmp/celerybeat-schedule"}
142
+ if config.services.get("tasks") != "celery":
143
+ suggestions["celery-worker"] = "celery -A \"$CELERY_APP\" worker --loglevel=info"
144
+ return suggestions
145
+
146
+
147
+ class GenericAdapter(PythonCapabilities):
108
148
  """Serve any ASGI or WSGI callable; no web framework required."""
109
149
 
110
150
  key = "generic"
@@ -140,7 +180,7 @@ class GenericAdapter:
140
180
  return []
141
181
 
142
182
 
143
- class DjangoAdapter:
183
+ class DjangoAdapter(PythonCapabilities):
144
184
  key = "django"
145
185
  label = "Django"
146
186
 
@@ -204,7 +244,7 @@ def _framework_apps(project_root: Path, module: str, constructor: str) -> list[t
204
244
  return found
205
245
 
206
246
 
207
- class FastAPIAdapter:
247
+ class FastAPIAdapter(PythonCapabilities):
208
248
  key = "fastapi"
209
249
  label = "FastAPI"
210
250
 
@@ -231,17 +271,26 @@ class FastAPIAdapter:
231
271
  return []
232
272
 
233
273
 
234
- class FlaskAdapter:
274
+ class FlaskAdapter(PythonCapabilities):
235
275
  """Flask is WSGI, so it runs on Gunicorn (the suggestion) or Granian."""
236
276
 
237
277
  key = "flask"
238
278
  label = "Flask"
239
279
 
240
280
  def detect(self, project_root: Path) -> bool:
241
- return bool(_framework_apps(project_root, "flask", "Flask"))
281
+ return self.default_app(project_root) is not None
242
282
 
243
283
  def default_app(self, project_root: Path) -> str | None:
244
284
  found = _framework_apps(project_root, "flask", "Flask")
285
+ # Factories are common Flask layouts; detect their definition without importing the app.
286
+ for path in python_files(project_root):
287
+ try:
288
+ tree = ast.parse(path.read_text(encoding="utf-8"))
289
+ except (OSError, SyntaxError):
290
+ continue
291
+ if any(isinstance(node, ast.FunctionDef) and node.name == "create_app" for node in tree.body):
292
+ if "flask" in path.read_text(encoding="utf-8") and "Flask(" in path.read_text(encoding="utf-8"):
293
+ return f"{_module_name(project_root, path)}:create_app()"
245
294
  return f"{_module_name(project_root, found[0][0])}:{found[0][1]}" if found else None
246
295
 
247
296
  def interface(self, config: ShipConfig, project_root: Path) -> Interface:
@@ -0,0 +1,60 @@
1
+ """Explicit public build values and temporary BuildKit credentials."""
2
+ from pathlib import Path
3
+ import re
4
+ import shlex
5
+ from typing import Any
6
+
7
+ from .config import ShipConfig
8
+
9
+ NAME = re.compile(r"[A-Za-z_][A-Za-z0-9_]*")
10
+ PUBLIC_PREFIXES = ("VITE_", "NEXT_PUBLIC_", "NUXT_PUBLIC_", "PUBLIC_", "GATSBY_", "REACT_APP_")
11
+
12
+
13
+ def validate_build(value: Any) -> list[str]:
14
+ if not isinstance(value, dict) or set(value) - {"publicEnv", "secrets", "npmrc"}:
15
+ return ["build must contain publicEnv, secrets and optional npmrc only."]
16
+ problems = []
17
+ public, secrets = value.get("publicEnv", {}), value.get("secrets", [])
18
+ if not isinstance(public, dict) or any(not isinstance(key, str) or not NAME.fullmatch(key) or
19
+ key in {"PATH", "HOME", "PYTHONPATH", "VIRTUAL_ENV", "UV_PROJECT_ENVIRONMENT"} or
20
+ not isinstance(item, str) or "\0" in item for key, item in public.items()):
21
+ problems.append("build.publicEnv must map safe environment names to public strings.")
22
+ if not isinstance(secrets, list) or any(not isinstance(key, str) or not NAME.fullmatch(key) or
23
+ key in {"PATH", "HOME", "PYTHONPATH", "VIRTUAL_ENV", "UV_PROJECT_ENVIRONMENT"} or key.startswith(PUBLIC_PREFIXES) for key in secrets):
24
+ problems.append("build.secrets must list private environment names; public frontend names cannot be secrets.")
25
+ elif len(set(secrets)) != len(secrets) or (isinstance(public, dict) and set(public) & set(secrets)):
26
+ problems.append("Build variables must have one unambiguous visibility.")
27
+ if not isinstance(value.get("npmrc", False), bool):
28
+ problems.append("build.npmrc must be a boolean.")
29
+ return problems
30
+
31
+
32
+ def build_problems(config: ShipConfig, root: Path) -> list[str]:
33
+ problems = []
34
+ for name in [*config.build.get("secrets", []), *(["npmrc"] if config.build.get("npmrc") else [])]:
35
+ path = root / ".ship-secrets" / name
36
+ if not path.is_file() or path.is_symlink():
37
+ problems.append(f"Required build secret file .ship-secrets/{name} is missing or is a symlink.")
38
+ return problems
39
+
40
+
41
+ def protect_runs(text: str, config: ShipConfig) -> str:
42
+ """Mount credentials only for dependency installation/build RUNs; never ENV or COPY them."""
43
+ public = config.build.get("publicEnv", {})
44
+ secrets = config.build.get("secrets", [])
45
+ mounts = [f"--mount=type=secret,id=ship_build_{key},required=true" for key in secrets]
46
+ env = [f'{key}="$(cat /run/secrets/ship_build_{key})"' for key in secrets]
47
+ if config.build.get("npmrc"):
48
+ mounts.append("--mount=type=secret,id=ship_npmrc,target=/run/secrets/ship_npmrc,required=true")
49
+ env.append("NPM_CONFIG_USERCONFIG=/run/secrets/ship_npmrc")
50
+ # Join Dockerfile continuation lines before wrapping shell commands.
51
+ text = text.replace("\\\n", " ")
52
+ result = []
53
+ for line in text.splitlines():
54
+ result.append(line)
55
+ if line.startswith("FROM ") and (" AS builder" in line or " AS assets" in line or " AS production-dependencies" in line):
56
+ result.extend("ARG " + key for key in public)
57
+ if line.startswith("RUN ") and ("uv " in line or "npm " in line or "pnpm " in line or "yarn " in line):
58
+ script = line[4:]
59
+ result[-1] = "RUN " + " ".join(mounts) + " " + ("env " + " ".join(env) + " " if env else "") + "sh -c " + shlex.quote(script)
60
+ return "\n".join(result) + "\n"
@@ -0,0 +1,43 @@
1
+ """Optional adapter capabilities, shared by initialization, validation and releases."""
2
+ from pathlib import Path
3
+ from typing import Any
4
+
5
+ from .config import ConfigError, ShipConfig, http_problem, process_problem
6
+ from .production import DEVELOPMENT_DEFAULTS, read_env
7
+
8
+
9
+ def release_description(adapter: Any, config: ShipConfig, root: Path) -> dict[str, Any]:
10
+ hook = getattr(adapter, "describe_release", None)
11
+ if hook is None:
12
+ return {}
13
+ result = hook(config, root)
14
+ if not isinstance(result, dict) or set(result) - {"health", "urlSetting", "requiredEnv"}:
15
+ raise ConfigError(f"Adapter {adapter.key}: invalid release description.")
16
+ problem = http_problem({"port": 8000, "role": "site", "health": result.get("health"), "urlSetting": result.get("urlSetting")})
17
+ if problem:
18
+ raise ConfigError(problem)
19
+ import re
20
+ if not isinstance(result.get("requiredEnv", []), list) or any(
21
+ not isinstance(key, str) or not re.fullmatch(r"[A-Za-z_][A-Za-z0-9_]*", key) for key in result.get("requiredEnv", [])):
22
+ raise ConfigError("Adapter requiredEnv must list setting names.")
23
+ return result
24
+
25
+
26
+ def required_setting_problems(description: dict[str, Any], root: Path) -> list[str]:
27
+ values = read_env(root / ".env.production")
28
+ return [f"{key} is required in .env.production with a real value."
29
+ for key in description.get("requiredEnv", []) if not values.get(key) or values[key].lower() in DEVELOPMENT_DEFAULTS]
30
+
31
+
32
+ def process_suggestions(adapter: Any, config: ShipConfig, root: Path) -> dict[str, Any]:
33
+ hook = getattr(adapter, "suggest_processes", None)
34
+ if hook is None:
35
+ return {}
36
+ result = hook(config, root)
37
+ if not isinstance(result, dict):
38
+ raise ConfigError("Adapter process suggestions must map names to process definitions.")
39
+ for name, value in result.items():
40
+ _, issues = ShipConfig.from_data({"app": config.app, "processes": {name: value}})
41
+ if process_problem(value) or issues:
42
+ raise ConfigError(f"Invalid adapter process suggestion {name!r}.")
43
+ return result
python_ship/cli.py CHANGED
@@ -20,6 +20,8 @@ from typing import Annotated, Any, NoReturn
20
20
  import typer
21
21
 
22
22
  from . import __version__
23
+ from .build_environment import build_problems
24
+ from .capabilities import release_description, required_setting_problems
23
25
  from .compose import (
24
26
  adapter_problems,
25
27
  build_compose,
@@ -30,13 +32,15 @@ from .compose import (
30
32
  )
31
33
  from .config import ConfigError, ShipConfig
32
34
  from .contracts import ShipEnvironment
35
+ from .environment import environment_warnings
33
36
  from .init import InitOptions, ensure_dockerignore, ensure_gitignore, interactive_terminal, run_init
34
37
  from .mutagen import enabled as mutagen_enabled
35
38
  from .mutagen import start as start_mutagen
36
39
  from .mutagen import stop as stop_mutagen
40
+ from .package_managers import inspect_manager, switch_manager
37
41
  from .plugins import Registry, console_commands, load_extensions
38
42
  from .production import credential_problems, read_env
39
- from .release import TAG_PATTERN, assemble_release, plan_images
43
+ from .release import TAG_PATTERN, assemble_release, destination_for, plan_images, source_metadata
40
44
  from .runtime import records, status, wait_for_stack
41
45
  from .stubs import asset_problems, production_stub_problem, published_version, stub_problems, stub_version_warning
42
46
  from .uv import UV_VERSION
@@ -101,6 +105,14 @@ def compose_prefix(project: Path, config: ShipConfig) -> list[str]:
101
105
  return prefix
102
106
 
103
107
 
108
+ def application_argv(config: ShipConfig, service: str, arguments: list[str]) -> list[str]:
109
+ # Exec does not invoke Docker ENTRYPOINT; prepare the same service credentials as startup.
110
+ managed = set(config.services.values()) | {entry.service for entry in config.additional_services}
111
+ if service == config.app_service and managed & {"mongodb", "rabbitmq"}:
112
+ return ["python", "/usr/local/bin/ship-app-entrypoint.py", *arguments]
113
+ return arguments
114
+
115
+
104
116
  def tty_flags() -> list[str]:
105
117
  # Without a terminal (CI, piped input) `docker compose exec` must not allocate one.
106
118
  return [] if sys.stdin.isatty() else ["-T"]
@@ -158,7 +170,9 @@ def config_problems(project: Path, *, production: bool = True) -> list[str]:
158
170
  continue
159
171
  if model_production:
160
172
  problems.extend(credential_problems(model, project))
173
+ problems.extend(required_setting_problems(release_description(registry.adapter(config), config, project), project))
161
174
  problems.extend(asset_problems(project, config))
175
+ problems.extend(build_problems(config, project))
162
176
  return list(dict.fromkeys(problems))
163
177
 
164
178
 
@@ -170,7 +184,8 @@ def build_production(project: Path, config: ShipConfig, tag: str) -> tuple[dict[
170
184
  fail(problem)
171
185
  problems = stub_problems(project, config)
172
186
  model = build_compose(config, project, production=True)
173
- problems += credential_problems(model, project) + asset_problems(project, config)
187
+ problems += credential_problems(model, project) + asset_problems(project, config) + build_problems(config, project)
188
+ problems += required_setting_problems(release_description(load_extensions(config).adapter(config), config, project), project)
174
189
  if problems:
175
190
  fail(" ".join(problems))
176
191
  require_docker()
@@ -222,9 +237,19 @@ def create_app(adapter_commands: dict[str, list[str]] | None = None) -> typer.Ty
222
237
 
223
238
  @app.command("init")
224
239
  def init_command(
240
+ name: Annotated[str | None, typer.Option("--name", help="Stable application and release identity.")] = None,
241
+ additional_service: Annotated[list[str] | None, typer.Option("--additional-service", help="GROUP=PROVIDER:NAME; repeatable.")] = None,
242
+ remove_instance: Annotated[list[str] | None, typer.Option("--remove-instance")] = None,
243
+ process: Annotated[list[str] | None, typer.Option("--process", help="NAME=COMMAND or NAME=JSON; repeatable.")] = None,
244
+ remove_process: Annotated[list[str] | None, typer.Option("--remove-process")] = None,
245
+ network: Annotated[list[str] | None, typer.Option("--network", help="External network; repeatable.")] = None,
246
+ no_network: Annotated[bool, typer.Option("--no-network")] = False,
247
+ 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,
225
249
  app_target: Annotated[str | None, typer.Option("--app", help="App import target, such as main:app.")] = None,
226
250
  framework: Annotated[str | None, typer.Option(help="Framework adapter: generic, django, fastapi, flask, or an extension.")] = None,
227
251
  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,
252
+ node_version: Annotated[str | None, typer.Option("--node", help="Frontend Node branch: 22, 24 or 26.")] = None,
228
253
  python_version: Annotated[str | None, typer.Option("--python", help="Python branch for the image, such as 3.13.")] = None,
229
254
  database: Annotated[str | None, typer.Option(help="Database service, or none.")] = None,
230
255
  cache: Annotated[str | None, typer.Option(help="Cache service, or none.")] = None,
@@ -242,12 +267,14 @@ def create_app(adapter_commands: dict[str, list[str]] | None = None) -> typer.Ty
242
267
  ) -> int:
243
268
  """Pick services, write ship.json and publish the ship/ directory."""
244
269
  options = InitOptions(
270
+ name=name, node=node_version, additional=additional_service, remove_instances=remove_instance, process_options=process,
271
+ remove_processes=remove_process, networks=network, clear_networks=no_network, deploy=deploy_command,
245
272
  app=app_target, framework=framework, server=server, python=python_version,
246
- selections={"database": database, "cache": cache, "broker": broker, "tasks": tasks,
273
+ selections={"broadcasting": broadcasting, "database": database, "cache": cache, "broker": broker, "tasks": tasks,
247
274
  "storage": storage, "search": search,
248
275
  "mail": mail, "testing": testing, "frontend": frontend},
249
276
  silo_image=silo_image, node_assets=node_assets, force=force,
250
- interactive=not no_interaction and interactive_terminal(),
277
+ interactive=not no_interaction and not os.environ.get("CI"),
251
278
  )
252
279
  return execute(lambda: run_init(root(), options))
253
280
 
@@ -277,8 +304,9 @@ def create_app(adapter_commands: dict[str, list[str]] | None = None) -> typer.Ty
277
304
  if not arguments:
278
305
  fail("ship exec requires a command after the service name, such as `ship exec app python -V`.")
279
306
  project = root()
280
- prefix = compose_prefix(project, read_config(project))
281
- return run(prefix + ["exec", *tty_flags(), service, *arguments], project)
307
+ config = read_config(project)
308
+ prefix = compose_prefix(project, config)
309
+ return run(prefix + ["exec", *tty_flags(), service, *application_argv(config, service, arguments)], project)
282
310
  return execute(action)
283
311
 
284
312
  @app.command("shell")
@@ -288,7 +316,7 @@ def create_app(adapter_commands: dict[str, list[str]] | None = None) -> typer.Ty
288
316
  project = root()
289
317
  config = read_config(project)
290
318
  prefix = compose_prefix(project, config)
291
- return run(prefix + ["exec", *tty_flags(), service or config.app_service, "sh"], project)
319
+ return run(prefix + ["exec", *tty_flags(), service or config.app_service, *application_argv(config, service or config.app_service, ["sh"])], project)
292
320
  return execute(action)
293
321
 
294
322
  @app.command("logs")
@@ -319,6 +347,8 @@ def create_app(adapter_commands: dict[str, list[str]] | None = None) -> typer.Ty
319
347
  if problems:
320
348
  typer.echo(f"ship: {len(problems)} problem{'s' if len(problems) != 1 else ''} found.", err=True)
321
349
  return 1
350
+ for message in environment_warnings(read_config(project), project):
351
+ warn(message)
322
352
  warning = stub_version_warning(project)
323
353
  if warning:
324
354
  warn(warning)
@@ -338,7 +368,11 @@ def create_app(adapter_commands: dict[str, list[str]] | None = None) -> typer.Ty
338
368
  return execute(action)
339
369
 
340
370
  @app.command("release")
341
- def release_command(tag: Annotated[str | None, typer.Option("--tag", help="Release tag, such as 1.2.0.")] = None) -> int:
371
+ def release_command(
372
+ tag: Annotated[str | None, typer.Option("--tag", help="Release tag, such as 1.2.0.")] = None,
373
+ force: Annotated[bool, typer.Option("--force", help="Explicitly replace an existing release.")] = False,
374
+ no_env: Annotated[bool, typer.Option("--no-env", help="Leave production settings out of the artifact.")] = False,
375
+ ) -> int:
342
376
  """Build the production images and assemble the portable release in dist/ship/<tag>/."""
343
377
  def action() -> int:
344
378
  chosen = tag
@@ -350,10 +384,12 @@ def create_app(adapter_commands: dict[str, list[str]] | None = None) -> typer.Ty
350
384
  fail("Invalid release tag; use letters, digits, _, . or -, starting with a letter, digit or _.")
351
385
  project = root()
352
386
  config = read_config(project)
353
- if not (project / ".env.production").is_file():
354
- fail("ship release requires .env.production, even when no selected service needs credentials.")
387
+ destination_for(project, chosen, force)
388
+ if not config.name:
389
+ fail("Release requires an explicit stable name in ship.json; run ship init --name NAME.")
390
+ source = source_metadata(project)
355
391
  model, _ = build_production(project, config, chosen)
356
- destination = assemble_release(project, config, model, chosen)
392
+ destination = assemble_release(project, config, model, chosen, force=force, no_env=no_env, source=source)
357
393
  typer.echo(f"Release ready at {destination}")
358
394
  return 0
359
395
  return execute(action)
@@ -363,18 +399,69 @@ def create_app(adapter_commands: dict[str, list[str]] | None = None) -> typer.Ty
363
399
  """Report versions, stub freshness and the state and health of every container."""
364
400
  return execute(doctor)
365
401
 
402
+ def frontend_proxy(tool: str) -> int:
403
+ project = root()
404
+ config = read_config(project)
405
+ registry = load_extensions(config)
406
+ nodes = [item for item in resolve_selections(config, registry) if item.service.key == "node"]
407
+ if len(nodes) != 1:
408
+ fail(f"ship {tool} requires the Node frontend service; select it with ship init --frontend node.")
409
+ manager = inspect_manager(project)
410
+ if manager.name != tool:
411
+ fail(f"This project uses {manager.name}; use ship {manager.name} or ship package-manager.")
412
+ return run(compose_prefix(project, config) + ["exec", *tty_flags(), nodes[0].service_name, tool, *proxy_tail(tool, 1)], project)
413
+
366
414
  @app.command("npm", context_settings=PROXY_CONTEXT)
367
415
  def npm_command(ctx: typer.Context) -> int:
368
- """Run npm in the Node frontend service; arguments pass through."""
416
+ return execute(lambda: frontend_proxy("npm"))
417
+
418
+ @app.command("pnpm", context_settings=PROXY_CONTEXT)
419
+ def pnpm_command(ctx: typer.Context) -> int:
420
+ return execute(lambda: frontend_proxy("pnpm"))
421
+
422
+ @app.command("yarn", context_settings=PROXY_CONTEXT)
423
+ def yarn_command(ctx: typer.Context) -> int:
424
+ return execute(lambda: frontend_proxy("yarn"))
425
+
426
+ @app.command("package-manager")
427
+ def package_manager_command(
428
+ tool: Annotated[str, typer.Argument(help="npm, pnpm or yarn, optionally @EXACT_VERSION.")],
429
+ yes: Annotated[bool, typer.Option("--yes", "-y", help="Confirm lockfile and dependency replacement.")] = False,
430
+ ) -> int:
431
+ def action() -> int:
432
+ project = root()
433
+ config = read_config(project)
434
+ if config.services.get("frontend") != "node":
435
+ fail("Select the Node frontend service before switching package managers.")
436
+ if not yes and (not interactive_terminal() or not typer.confirm("Replace frontend lockfiles and reinstall dependencies?", default=False)):
437
+ fail("Switch cancelled; pass --yes to confirm in automation.")
438
+ prefix = compose_prefix(project, config)
439
+ node = config.service_names.get("node", "node")
440
+ switch_manager(project, tool, lambda argv: run(prefix + ["exec", "-T", node, *argv], project))
441
+ # Only the generated frontend image changes; preserve the application Dockerfile.
442
+ from .package_managers import node_dockerfile
443
+ (project / "ship/node/Dockerfile").write_text(node_dockerfile(project, config.node))
444
+ typer.echo("Package manager updated. Review the lockfile, then ship up to rebuild the frontend container.")
445
+ return 0
446
+ return execute(action)
447
+
448
+ @app.command("test", context_settings=PROXY_CONTEXT)
449
+ def test_command(ctx: typer.Context) -> int:
369
450
  def action() -> int:
370
451
  project = root()
371
452
  config = read_config(project)
372
453
  registry = load_extensions(config)
373
- nodes = [item for item in resolve_selections(config, registry) if item.service.key == "node"]
374
- if len(nodes) != 1:
375
- fail("ship npm requires the Node frontend service; select it with `ship init --frontend node`.")
454
+ selected = next((item for item in resolve_selections(config, registry) if item.group == "testing" and item.instance_name is None), None)
455
+ if selected is None:
456
+ fail("Select a browser testing service first.")
457
+ arguments = proxy_tail("test", 1)
458
+ if arguments[:1] == ["--"]:
459
+ arguments = arguments[1:]
376
460
  prefix = compose_prefix(project, config)
377
- return run(prefix + ["exec", *tty_flags(), nodes[0].service_name, "npm", *proxy_tail("npm", 1)], project)
461
+ if selected.service.key == "cypress":
462
+ return run(prefix + ["run", "--build", "--rm", "--no-deps", *tty_flags(), "--entrypoint", "sh", selected.service_name,
463
+ "-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
+ return run(prefix + ["exec", *tty_flags(), config.app_service, *application_argv(config, config.app_service, ["python", "-m", "pytest", *arguments])], project)
378
465
  return execute(action)
379
466
 
380
467
  @app.command("uv", context_settings=PROXY_CONTEXT)
@@ -395,7 +482,7 @@ def _adapter_command(name: str, command_prefix: list[str]) -> Callable[[typer.Co
395
482
  project = root()
396
483
  config = read_config(project)
397
484
  prefix = compose_prefix(project, config)
398
- return run(prefix + ["exec", *tty_flags(), config.app_service, *command_prefix, *proxy_tail(name, 1)], project)
485
+ return run(prefix + ["exec", *tty_flags(), config.app_service, *application_argv(config, config.app_service, [*command_prefix, *proxy_tail(name, 1)])], project)
399
486
  return execute(action)
400
487
  command.__name__ = f"{name}_command"
401
488
  return command
@@ -423,7 +510,7 @@ def up() -> int:
423
510
  except ConfigError:
424
511
  run(prefix + ["down"], project)
425
512
  raise
426
- port = wait_for_stack(prefix, set(model["services"]), config.app_service)
513
+ port = wait_for_stack(prefix, {name for name, service in model["services"].items() if not service.get("profiles")}, config.app_service)
427
514
  typer.echo(f"The stack is running: http://127.0.0.1:{port}")
428
515
  return 0
429
516
 
@@ -496,12 +583,20 @@ def doctor() -> int:
496
583
  warning = stub_version_warning(project)
497
584
  if warning:
498
585
  warn(warning)
499
- prefix = compose_prefix(project, config)
586
+ require_docker()
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)]
500
595
  result = subprocess.run(prefix + ["ps", "--all", "--format", "json"], cwd=project, capture_output=True, text=True, check=False)
501
596
  if result.returncode != 0:
502
597
  fail(f"Could not inspect Docker Compose: {result.stderr.strip()}. Check that Docker is running.")
503
598
  found = records(result.stdout)
504
- fatal, pending, port = status(found, set(model["services"]), config.app_service)
599
+ fatal, pending, port = status(found, {name for name, service in model["services"].items() if not service.get("profiles")}, config.app_service)
505
600
  for name, service in model["services"].items():
506
601
  record = found.get(name, {})
507
602
  health = record.get("Health")