python-ship 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
python_ship/cli.py ADDED
@@ -0,0 +1,588 @@
1
+ """The `ship` command line, built on Typer.
2
+
3
+ The command set mirrors PHP Ship: init, up, down, exec, shell, logs, db,
4
+ config:test, build and release, plus proxies (npm, uv, and each framework
5
+ adapter's console commands such as Django's `manage`).
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ from collections.abc import Callable
11
+ from contextvars import ContextVar
12
+ import os
13
+ from pathlib import Path
14
+ import re
15
+ import shutil
16
+ import subprocess
17
+ import sys
18
+ from typing import Annotated, Any, NoReturn
19
+
20
+ import typer
21
+
22
+ from . import __version__
23
+ from .compose import (
24
+ adapter_problems,
25
+ build_compose,
26
+ resolve_selections,
27
+ selection_problems,
28
+ server_for,
29
+ write_compose,
30
+ )
31
+ from .config import ConfigError, ShipConfig
32
+ from .contracts import ShipEnvironment
33
+ from .init import InitOptions, ensure_dockerignore, ensure_gitignore, interactive_terminal, run_init
34
+ from .mutagen import enabled as mutagen_enabled
35
+ from .mutagen import start as start_mutagen
36
+ from .mutagen import stop as stop_mutagen
37
+ from .plugins import Registry, console_commands, load_extensions
38
+ from .production import credential_problems, read_env
39
+ from .release import TAG_PATTERN, assemble_release, plan_images
40
+ from .runtime import records, status, wait_for_stack
41
+ from .stubs import asset_problems, production_stub_problem, published_version, stub_problems, stub_version_warning
42
+ from .uv import UV_VERSION
43
+
44
+ OVERRIDE_FILES = (
45
+ "docker-compose.override.yml", "docker-compose.override.yaml", "compose.override.yml", "compose.override.yaml",
46
+ )
47
+ PROXY_CONTEXT = {"allow_extra_args": True, "ignore_unknown_options": True, "help_option_names": []}
48
+ UV_STATEFUL = {"sync", "run", "pip", "python", "tool", "venv"}
49
+
50
+ _raw_argv: ContextVar[list[str] | None] = ContextVar("ship_raw_argv", default=None)
51
+ _project_root: ContextVar[Path | None] = ContextVar("ship_project_root", default=None)
52
+
53
+
54
+ # Helpers ----------------------------------------------------------------------------------------
55
+
56
+ def root() -> Path:
57
+ return _project_root.get() or Path.cwd()
58
+
59
+
60
+ def proxy_tail(command: str, count: int) -> list[str]:
61
+ """The raw arguments after a proxy command, untouched by option parsing."""
62
+ argv = _raw_argv.get() or []
63
+ index = 0
64
+ while index < len(argv):
65
+ if argv[index] == "--project-directory":
66
+ index += 2
67
+ elif argv[index].startswith("--project-directory="):
68
+ index += 1
69
+ else:
70
+ break
71
+ if index >= len(argv) or argv[index] != command:
72
+ raise ConfigError(f"Could not locate the raw arguments of `ship {command}`.")
73
+ return argv[index + count:]
74
+
75
+
76
+ def fail(message: str) -> NoReturn:
77
+ raise ConfigError(message)
78
+
79
+
80
+ def warn(message: str) -> None:
81
+ typer.echo(f"ship: warning: {message}", err=True)
82
+
83
+
84
+ def require_docker() -> None:
85
+ if shutil.which("docker") is None:
86
+ fail("Docker is required for this command; install Docker Desktop or Docker Engine with Compose v2.")
87
+
88
+
89
+ def override_file(project: Path) -> Path | None:
90
+ return next((project / name for name in OVERRIDE_FILES if (project / name).is_file()), None)
91
+
92
+
93
+ def compose_prefix(project: Path, config: ShipConfig) -> list[str]:
94
+ """The `docker compose` prefix every development command shares, with the override file applied."""
95
+ path = write_compose(config, project)
96
+ require_docker()
97
+ prefix = ["docker", "compose", "--project-directory", str(project), "-f", str(path)]
98
+ override = override_file(project)
99
+ if override is not None:
100
+ prefix += ["-f", str(override)]
101
+ return prefix
102
+
103
+
104
+ def tty_flags() -> list[str]:
105
+ # Without a terminal (CI, piped input) `docker compose exec` must not allocate one.
106
+ return [] if sys.stdin.isatty() else ["-T"]
107
+
108
+
109
+ def run(command: list[str], project: Path) -> int:
110
+ return subprocess.run(command, cwd=project, check=False).returncode
111
+
112
+
113
+ def execute(action: Callable[[], int]) -> int:
114
+ try:
115
+ return action()
116
+ except (ConfigError, OSError) as exc:
117
+ typer.echo(f"ship: {exc}", err=True)
118
+ return 1
119
+
120
+
121
+ def read_config(project: Path) -> ShipConfig:
122
+ return ShipConfig.read(project)
123
+
124
+
125
+ # Checks shared by config:test, doctor, up, build and release -------------------------------------
126
+
127
+ def config_problems(project: Path, *, production: bool = True) -> list[str]:
128
+ """Every independent problem with ship.json, ship/ and both Compose models, in one pass.
129
+
130
+ ``production=False`` skips the production model, for development-only diagnostics.
131
+ """
132
+ config, problems = ShipConfig.inspect(project)
133
+ problems = list(problems)
134
+ problems.extend(stub_problems(project, config))
135
+ if config is None:
136
+ return problems
137
+ try:
138
+ registry = load_extensions(config)
139
+ except ConfigError as exc:
140
+ return [*problems, str(exc)]
141
+ problems.extend(adapter_problems(config, project, registry))
142
+ if not problems:
143
+ try:
144
+ server_for(config, project, registry)
145
+ except ConfigError as exc:
146
+ problems.append(str(exc))
147
+ problems.extend(selection_problems(config, registry))
148
+ try:
149
+ console_commands(registry.adapter(config))
150
+ except ConfigError as exc:
151
+ problems.append(str(exc))
152
+ if not problems:
153
+ for model_production in ((False, True) if production else (False,)):
154
+ try:
155
+ model = build_compose(config, project, production=model_production, registry=registry)
156
+ except ConfigError as exc:
157
+ problems.append(f"{'Production' if model_production else 'Development'} Compose model: {exc}")
158
+ continue
159
+ if model_production:
160
+ problems.extend(credential_problems(model, project))
161
+ problems.extend(asset_problems(project, config))
162
+ return list(dict.fromkeys(problems))
163
+
164
+
165
+ # Production -------------------------------------------------------------------------------------
166
+
167
+ def build_production(project: Path, config: ShipConfig, tag: str) -> tuple[dict[str, Any], list[dict[str, Any]]]:
168
+ problem = production_stub_problem(project)
169
+ if problem:
170
+ fail(problem)
171
+ problems = stub_problems(project, config)
172
+ model = build_compose(config, project, production=True)
173
+ problems += credential_problems(model, project) + asset_problems(project, config)
174
+ if problems:
175
+ fail(" ".join(problems))
176
+ require_docker()
177
+ ensure_dockerignore(project)
178
+ ensure_gitignore(project)
179
+ planned, images = plan_images(model, tag)
180
+ path = write_compose(config, project, production=True, model=planned)
181
+ env_file = project / ".env.production"
182
+ # The override file is deliberately not applied: a dev-only override has no business
183
+ # reaching a production image.
184
+ prefix = ["docker", "compose", "--project-directory", str(project)]
185
+ if env_file.is_file():
186
+ prefix += ["--env-file", str(env_file)]
187
+ command = prefix + ["-f", str(path), "build", *(image["owner"] for image in images)]
188
+ environment = {**os.environ, **read_env(env_file)}
189
+ if subprocess.run(command, cwd=project, env=environment, check=False).returncode != 0:
190
+ fail("Building the production images failed; see the Docker output above.")
191
+ return planned, images
192
+
193
+
194
+ # Commands ---------------------------------------------------------------------------------------
195
+
196
+ def version_callback(value: bool) -> None:
197
+ if value:
198
+ typer.echo(f"ship (python-ship) {__version__}")
199
+ raise typer.Exit()
200
+
201
+
202
+ def create_app(adapter_commands: dict[str, list[str]] | None = None) -> typer.Typer:
203
+ app = typer.Typer(
204
+ help="Docker development environments and portable releases for Python web apps.",
205
+ no_args_is_help=True,
206
+ add_completion=True,
207
+ rich_markup_mode=None,
208
+ pretty_exceptions_enable=False,
209
+ )
210
+
211
+ @app.callback()
212
+ def main_options(
213
+ project_directory: Annotated[Path | None, typer.Option(
214
+ "--project-directory", help="Run against the project in this directory instead of the current one.",
215
+ )] = None,
216
+ version: Annotated[bool, typer.Option(
217
+ "--version", "-V", callback=version_callback, is_eager=True, help="Show the python-ship version and exit.",
218
+ )] = False,
219
+ ) -> None:
220
+ if project_directory is not None:
221
+ _project_root.set(project_directory.resolve())
222
+
223
+ @app.command("init")
224
+ def init_command(
225
+ app_target: Annotated[str | None, typer.Option("--app", help="App import target, such as main:app.")] = None,
226
+ framework: Annotated[str | None, typer.Option(help="Framework adapter: generic, django, fastapi, flask, or an extension.")] = None,
227
+ 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,
228
+ python_version: Annotated[str | None, typer.Option("--python", help="Python branch for the image, such as 3.13.")] = None,
229
+ database: Annotated[str | None, typer.Option(help="Database service, or none.")] = None,
230
+ cache: Annotated[str | None, typer.Option(help="Cache service, or none.")] = None,
231
+ storage: Annotated[str | None, typer.Option(help="Object storage service, or none.")] = None,
232
+ search: Annotated[str | None, typer.Option(help="Search service, or none.")] = None,
233
+ mail: Annotated[str | None, typer.Option(help="Mail capture service, or none.")] = None,
234
+ testing: Annotated[str | None, typer.Option(help="Browser testing service, or none.")] = None,
235
+ frontend: Annotated[str | None, typer.Option(help="Frontend tooling service, or none.")] = None,
236
+ broker: Annotated[str | None, typer.Option(help="Message broker service (rabbitmq), or none.")] = None,
237
+ tasks: Annotated[str | None, typer.Option(help="Background task queue (celery), or none.")] = None,
238
+ silo_image: Annotated[str | None, typer.Option("--silo-image", help="Silo image: standard or distroless.")] = None,
239
+ node_assets: Annotated[bool | None, typer.Option("--node-assets/--no-node-assets", help="Build npm assets into the production image.")] = None,
240
+ force: Annotated[bool, typer.Option("--force", help="Republish ship/Dockerfile, replacing local edits.")] = False,
241
+ no_interaction: Annotated[bool, typer.Option("--no-interaction", "-n", help="Don't prompt; use options, the existing ship.json and detection.")] = False,
242
+ ) -> int:
243
+ """Pick services, write ship.json and publish the ship/ directory."""
244
+ options = InitOptions(
245
+ app=app_target, framework=framework, server=server, python=python_version,
246
+ selections={"database": database, "cache": cache, "broker": broker, "tasks": tasks,
247
+ "storage": storage, "search": search,
248
+ "mail": mail, "testing": testing, "frontend": frontend},
249
+ silo_image=silo_image, node_assets=node_assets, force=force,
250
+ interactive=not no_interaction and interactive_terminal(),
251
+ )
252
+ return execute(lambda: run_init(root(), options))
253
+
254
+ @app.command("up")
255
+ def up_command() -> int:
256
+ """Generate ship/docker-compose.generated.yml and start the development stack."""
257
+ return execute(up)
258
+
259
+ @app.command("down")
260
+ def down_command(
261
+ volumes: Annotated[bool, typer.Option("--volumes", "-v", help="Also delete named volumes (database and storage data).")] = False,
262
+ ) -> int:
263
+ """Stop and remove the development stack."""
264
+ def action() -> int:
265
+ project = root()
266
+ config = read_config(project)
267
+ prefix = compose_prefix(project, config)
268
+ stop_mutagen(project, required=mutagen_enabled())
269
+ return run(prefix + ["down", *(["--volumes"] if volumes else [])], project)
270
+ return execute(action)
271
+
272
+ @app.command("exec", context_settings=PROXY_CONTEXT)
273
+ def exec_command(ctx: typer.Context, service: Annotated[str, typer.Argument(help="Compose service name.")]) -> int:
274
+ """Run a command in a running service; every following argument is passed through."""
275
+ def action() -> int:
276
+ arguments = proxy_tail("exec", 2)
277
+ if not arguments:
278
+ fail("ship exec requires a command after the service name, such as `ship exec app python -V`.")
279
+ project = root()
280
+ prefix = compose_prefix(project, read_config(project))
281
+ return run(prefix + ["exec", *tty_flags(), service, *arguments], project)
282
+ return execute(action)
283
+
284
+ @app.command("shell")
285
+ def shell_command(service: Annotated[str | None, typer.Argument(help="Compose service name; defaults to the app.")] = None) -> int:
286
+ """Open an interactive shell (sh) in a running service."""
287
+ def action() -> int:
288
+ project = root()
289
+ config = read_config(project)
290
+ prefix = compose_prefix(project, config)
291
+ return run(prefix + ["exec", *tty_flags(), service or config.app_service, "sh"], project)
292
+ return execute(action)
293
+
294
+ @app.command("logs")
295
+ def logs_command(
296
+ service: Annotated[str | None, typer.Argument(help="Compose service name; all services when omitted.")] = None,
297
+ follow: Annotated[bool, typer.Option("--follow", "-f", help="Stream new log output.")] = False,
298
+ ) -> int:
299
+ """Show container logs."""
300
+ def action() -> int:
301
+ project = root()
302
+ prefix = compose_prefix(project, read_config(project))
303
+ return run(prefix + ["logs", *(["--follow"] if follow else []), *([service] if service else [])], project)
304
+ return execute(action)
305
+
306
+ @app.command("db")
307
+ def db_command(instance: Annotated[str | None, typer.Argument(help="Name of an additionalServices database; the default database when omitted.")] = None) -> int:
308
+ """Open a database's interactive client, using credentials from its own container."""
309
+ return execute(lambda: database_shell(instance))
310
+
311
+ @app.command("config:test")
312
+ def config_test_command() -> int:
313
+ """Validate ship.json, ship/ and both Compose models without starting Docker."""
314
+ def action() -> int:
315
+ project = root()
316
+ problems = config_problems(project)
317
+ for problem in problems:
318
+ typer.echo(f"ship: {problem}", err=True)
319
+ if problems:
320
+ typer.echo(f"ship: {len(problems)} problem{'s' if len(problems) != 1 else ''} found.", err=True)
321
+ return 1
322
+ warning = stub_version_warning(project)
323
+ if warning:
324
+ warn(warning)
325
+ typer.echo("ship.json, ship/ and both Compose models are valid.")
326
+ return 0
327
+ return execute(action)
328
+
329
+ @app.command("build")
330
+ def build_command() -> int:
331
+ """Build every project-owned production image, tagged locally."""
332
+ def action() -> int:
333
+ project = root()
334
+ _, images = build_production(project, read_config(project), "local")
335
+ for image in images:
336
+ typer.echo(f"Built {image['image']} ({', '.join(image['services'])})")
337
+ return 0
338
+ return execute(action)
339
+
340
+ @app.command("release")
341
+ def release_command(tag: Annotated[str | None, typer.Option("--tag", help="Release tag, such as 1.2.0.")] = None) -> int:
342
+ """Build the production images and assemble the portable release in dist/ship/<tag>/."""
343
+ def action() -> int:
344
+ chosen = tag
345
+ if chosen is None:
346
+ if not sys.stdin.isatty():
347
+ fail("ship release requires --tag when it isn't run from a terminal.")
348
+ chosen = str(typer.prompt("Release tag")).strip()
349
+ if not re.fullmatch(TAG_PATTERN, chosen):
350
+ fail("Invalid release tag; use letters, digits, _, . or -, starting with a letter, digit or _.")
351
+ project = root()
352
+ 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.")
355
+ model, _ = build_production(project, config, chosen)
356
+ destination = assemble_release(project, config, model, chosen)
357
+ typer.echo(f"Release ready at {destination}")
358
+ return 0
359
+ return execute(action)
360
+
361
+ @app.command("doctor")
362
+ def doctor_command() -> int:
363
+ """Report versions, stub freshness and the state and health of every container."""
364
+ return execute(doctor)
365
+
366
+ @app.command("npm", context_settings=PROXY_CONTEXT)
367
+ def npm_command(ctx: typer.Context) -> int:
368
+ """Run npm in the Node frontend service; arguments pass through."""
369
+ def action() -> int:
370
+ project = root()
371
+ config = read_config(project)
372
+ 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`.")
376
+ prefix = compose_prefix(project, config)
377
+ return run(prefix + ["exec", *tty_flags(), nodes[0].service_name, "npm", *proxy_tail("npm", 1)], project)
378
+ return execute(action)
379
+
380
+ @app.command("uv", context_settings=PROXY_CONTEXT)
381
+ def uv_command(ctx: typer.Context) -> int:
382
+ """Run uv dependency commands (add, remove, lock, tree, ...) in a temporary container."""
383
+ return execute(lambda: uv(proxy_tail("uv", 1)))
384
+
385
+ for name, command_prefix in (adapter_commands or {}).items():
386
+ app.command(name, context_settings=PROXY_CONTEXT, help=f"Run `{' '.join(command_prefix)}` in the app container; arguments pass through.")(
387
+ _adapter_command(name, command_prefix)
388
+ )
389
+ return app
390
+
391
+
392
+ def _adapter_command(name: str, command_prefix: list[str]) -> Callable[[typer.Context], int]:
393
+ def command(ctx: typer.Context) -> int:
394
+ def action() -> int:
395
+ project = root()
396
+ config = read_config(project)
397
+ prefix = compose_prefix(project, config)
398
+ return run(prefix + ["exec", *tty_flags(), config.app_service, *command_prefix, *proxy_tail(name, 1)], project)
399
+ return execute(action)
400
+ command.__name__ = f"{name}_command"
401
+ return command
402
+
403
+
404
+ def up() -> int:
405
+ project = root()
406
+ config = read_config(project)
407
+ problems = stub_problems(project, config)
408
+ if problems:
409
+ fail(" ".join(problems))
410
+ warning = stub_version_warning(project)
411
+ if warning:
412
+ warn(warning)
413
+ prefix = compose_prefix(project, config)
414
+ # A session left by an earlier container must go before Compose recreates it.
415
+ stop_mutagen(project, required=mutagen_enabled())
416
+ code = run(prefix + ["up", "--build", "--detach"], project)
417
+ if code != 0:
418
+ return code
419
+ model = build_compose(config, project)
420
+ if mutagen_enabled():
421
+ try:
422
+ start_mutagen(prefix, project, tuple(model["x-ship"]["sync_services"]))
423
+ except ConfigError:
424
+ run(prefix + ["down"], project)
425
+ raise
426
+ port = wait_for_stack(prefix, set(model["services"]), config.app_service)
427
+ typer.echo(f"The stack is running: http://127.0.0.1:{port}")
428
+ return 0
429
+
430
+
431
+ def database_shell(instance: str | None) -> int:
432
+ project = root()
433
+ config = read_config(project)
434
+ registry = load_extensions(config)
435
+ databases = [item for item in resolve_selections(config, registry) if item.group == "database"]
436
+ if not databases:
437
+ fail("No database is selected; add one with `ship init --database postgres` (or mysql).")
438
+ if instance is None:
439
+ chosen = next((item for item in databases if item.instance_name is None), None)
440
+ if chosen is None:
441
+ names = ", ".join(str(item.instance_name) for item in databases)
442
+ fail(f"No default database is selected; name one of the additional instances: {names}.")
443
+ else:
444
+ chosen = next((item for item in databases if item.instance_name == instance), None)
445
+ if chosen is None:
446
+ names = ", ".join(str(item.instance_name) for item in databases if item.instance_name) or "none"
447
+ fail(f"No database instance named {instance!r}; additional database instances: {names}.")
448
+ assert chosen is not None
449
+ shell = getattr(chosen.service, "database_shell", None)
450
+ if shell is None:
451
+ fail(f"The {chosen.service.key!r} service doesn't provide a database shell.")
452
+ command = shell(chosen.context(config, project, ShipEnvironment.DEVELOPMENT))
453
+ prefix = compose_prefix(project, config)
454
+ return run(prefix + ["exec", *tty_flags(), chosen.service_name, *command], project)
455
+
456
+
457
+ def uv(arguments: list[str]) -> int:
458
+ project = root()
459
+ config = read_config(project)
460
+ if not arguments:
461
+ fail("ship uv requires uv arguments, such as `ship uv add httpx` or `ship uv lock`.")
462
+ if arguments[0] in UV_STATEFUL:
463
+ fail(
464
+ f"`uv {arguments[0]}` would change an environment that disappears with the temporary container. "
465
+ "Run `ship up` to install dependencies into the app image, or `ship exec app ...` to run app commands."
466
+ )
467
+ require_docker()
468
+ python = ".".join(config.python.split(".")[:2])
469
+ image = f"ghcr.io/astral-sh/uv:{UV_VERSION}-python{python}-trixie-slim"
470
+ command = [
471
+ "docker", "run", "--rm", "--interactive",
472
+ "--volume", f"{project.resolve()}:/app", "--workdir", "/app",
473
+ "--env", "HOME=/tmp", "--env", "UV_CACHE_DIR=/tmp/ship-uv-cache",
474
+ "--env", "UV_PROJECT_ENVIRONMENT=/tmp/ship-uv-venv",
475
+ "--env", "UV_NO_SYNC=1", "--env", f"UV_PYTHON=python{python}",
476
+ ]
477
+ if sys.platform.startswith("linux") and hasattr(os, "getuid"):
478
+ command += ["--user", f"{os.getuid()}:{os.getgid()}"]
479
+ if sys.stdin.isatty() and sys.stdout.isatty():
480
+ command.append("--tty")
481
+ return run(command + [image, "uv", *arguments], project)
482
+
483
+
484
+ def doctor() -> int:
485
+ project = root()
486
+ problems = config_problems(project, production=False)
487
+ for problem in problems:
488
+ typer.echo(f"ship: {problem}", err=True)
489
+ if problems:
490
+ return 1
491
+ config = read_config(project)
492
+ model = build_compose(config, project)
493
+ typer.echo(f"python-ship {__version__}; project {model['name']}; Python {config.python}; "
494
+ f"framework {config.framework}; server {server_for(config, project).key}")
495
+ typer.echo(f"Published ship/Dockerfile: python-ship {published_version(project) or 'unknown'}")
496
+ warning = stub_version_warning(project)
497
+ if warning:
498
+ warn(warning)
499
+ prefix = compose_prefix(project, config)
500
+ result = subprocess.run(prefix + ["ps", "--all", "--format", "json"], cwd=project, capture_output=True, text=True, check=False)
501
+ if result.returncode != 0:
502
+ fail(f"Could not inspect Docker Compose: {result.stderr.strip()}. Check that Docker is running.")
503
+ found = records(result.stdout)
504
+ fatal, pending, port = status(found, set(model["services"]), config.app_service)
505
+ for name, service in model["services"].items():
506
+ record = found.get(name, {})
507
+ health = record.get("Health")
508
+ typer.echo(f"{name}: {service.get('image', 'built from ' + service.get('build', {}).get('dockerfile', 'a Dockerfile'))}; "
509
+ f"{record.get('State', 'missing')}" + (f"; health {health}" if health else ""))
510
+ if fatal or pending:
511
+ for problem in (*fatal, *pending):
512
+ typer.echo(f"ship: {problem}", err=True)
513
+ typer.echo("ship: run `ship logs SERVICE` to see why, then `ship up` to rebuild or restart the stack.", err=True)
514
+ return 1
515
+ typer.echo(f"Every service is running; the app is published at http://127.0.0.1:{port}")
516
+ return 0
517
+
518
+
519
+ # Entry point ------------------------------------------------------------------------------------
520
+
521
+ def _root_from_argv(argv: list[str]) -> Path:
522
+ for index, argument in enumerate(argv):
523
+ if argument == "--project-directory" and index + 1 < len(argv):
524
+ return Path(argv[index + 1]).resolve()
525
+ if argument.startswith("--project-directory="):
526
+ return Path(argument.split("=", 1)[1]).resolve()
527
+ if not argument.startswith("-"):
528
+ break
529
+ return Path.cwd()
530
+
531
+
532
+ def discover_adapter_commands(project: Path) -> dict[str, list[str]]:
533
+ """The selected adapter's console commands, registered like PHP Ship's artisan/console.
534
+
535
+ A project whose ship.json can't be read yet simply gets no extra commands;
536
+ `ship config:test` reports why.
537
+ """
538
+ if not (project / "ship.json").is_file():
539
+ return {}
540
+ try:
541
+ config = ShipConfig.read(project)
542
+ registry: Registry = load_extensions(config)
543
+ return console_commands(registry.adapter(config))
544
+ except (ConfigError, OSError):
545
+ return {}
546
+
547
+
548
+ def main(argv: list[str] | None = None) -> int:
549
+ argv = list(sys.argv[1:] if argv is None else argv)
550
+ token = _raw_argv.set(argv)
551
+ root_token = _project_root.set(None)
552
+ # Typer detects the shell from the parent process; accept an explicit one for scripts.
553
+ explicit_completion = argv[:1] == ["--show-completion"] and len(argv) > 1 and argv[1] in {
554
+ "bash", "zsh", "fish", "powershell", "pwsh",
555
+ }
556
+ previous = os.environ.get("_TYPER_COMPLETE_TEST_DISABLE_SHELL_DETECTION")
557
+ if explicit_completion:
558
+ os.environ["_TYPER_COMPLETE_TEST_DISABLE_SHELL_DETECTION"] = "1"
559
+ try:
560
+ app = create_app(discover_adapter_commands(_root_from_argv(argv)))
561
+ # A bare `ship` lists the commands and succeeds, like PHP Ship.
562
+ result = app(args=argv or ["--help"], prog_name="ship", standalone_mode=False)
563
+ return result if isinstance(result, int) else 0
564
+ except KeyboardInterrupt:
565
+ typer.echo("\nInterrupted.", err=True)
566
+ return 130
567
+ except Exception as exc:
568
+ # Typer's (and, before 0.28, Click's) usage errors, Exit and Abort. Matched by shape
569
+ # because Typer 0.28+ vendors Click privately.
570
+ if type(exc).__name__ == "Abort":
571
+ typer.echo("\nAborted.", err=True)
572
+ return 130
573
+ exit_code = getattr(exc, "exit_code", None)
574
+ if isinstance(exit_code, int):
575
+ show = getattr(exc, "show", None)
576
+ if callable(show):
577
+ show()
578
+ return exit_code
579
+ raise
580
+ finally:
581
+ _raw_argv.reset(token)
582
+ _project_root.reset(root_token)
583
+ if explicit_completion:
584
+ if previous is None:
585
+ os.environ.pop("_TYPER_COMPLETE_TEST_DISABLE_SHELL_DETECTION", None)
586
+ else:
587
+ os.environ["_TYPER_COMPLETE_TEST_DISABLE_SHELL_DETECTION"] = previous
588
+