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.
Files changed (37) hide show
  1. python_ship/__init__.py +1 -1
  2. python_ship/adapters.py +28 -3
  3. python_ship/capabilities.py +26 -1
  4. python_ship/cli.py +305 -90
  5. python_ship/compose.py +40 -14
  6. python_ship/config.py +26 -11
  7. python_ship/contracts.py +13 -1
  8. python_ship/environment.py +252 -38
  9. python_ship/image_build.py +143 -0
  10. python_ship/init.py +298 -76
  11. python_ship/layout.py +50 -0
  12. python_ship/mutagen.py +1 -1
  13. python_ship/package_managers.py +1 -1
  14. python_ship/plugins.py +22 -2
  15. python_ship/portable.py +7 -0
  16. python_ship/ports.py +120 -0
  17. python_ship/production.py +1 -0
  18. python_ship/release.py +4 -2
  19. python_ship/runtime.py +9 -7
  20. python_ship/schema/ship.schema.json +22 -0
  21. python_ship/security.py +2 -1
  22. python_ship/service_setup.py +80 -0
  23. python_ship/services.py +63 -4
  24. python_ship/storage.py +9 -3
  25. python_ship/stubs.py +23 -21
  26. python_ship/templates/Dockerfile +12 -2
  27. python_ship/templates/check-python-security-floor.py +1 -1
  28. python_ship/templates/launcher +49 -0
  29. python_ship/terminal.py +77 -0
  30. python_ship/wizard.py +52 -6
  31. {python_ship-0.2.0.dist-info → python_ship-0.3.0.dist-info}/METADATA +363 -178
  32. python_ship-0.3.0.dist-info/RECORD +47 -0
  33. python_ship-0.2.0.dist-info/RECORD +0 -41
  34. {python_ship-0.2.0.dist-info → python_ship-0.3.0.dist-info}/WHEEL +0 -0
  35. {python_ship-0.2.0.dist-info → python_ship-0.3.0.dist-info}/entry_points.txt +0 -0
  36. {python_ship-0.2.0.dist-info → python_ship-0.3.0.dist-info}/licenses/LICENSE.md +0 -0
  37. {python_ship-0.2.0.dist-info → python_ship-0.3.0.dist-info}/top_level.txt +0 -0
python_ship/compose.py CHANGED
@@ -15,8 +15,10 @@ from typing import Any
15
15
  from . import __version__
16
16
  from .config import ConfigError, ShipConfig, command_argv, http_problem, process_definition
17
17
  from .contracts import APP_PROCESS, Interface, ServiceContext, ServiceDefinition, ShipEnvironment, WebServer
18
+ from .layout import LEGACY_BACKUP, docker_directory, docker_path
18
19
  from .mutagen import enabled as mutagen_enabled
19
- from .plugins import Registry, load_extensions
20
+ from .plugins import Registry, load_extensions, supports_named_instances
21
+ from .ports import available_ports, port_segments
20
22
  from .security import build_arg as python_floor
21
23
  from .services import BROWSER_APP_HOST
22
24
 
@@ -80,6 +82,8 @@ def selection_problems(config: ShipConfig, registry: Registry) -> list[str]:
80
82
  f"Additional instance {entry.name!r}: {entry.service!r} belongs to the "
81
83
  f"{service.group!r} group, not {entry.group!r}."
82
84
  )
85
+ elif not supports_named_instances(service):
86
+ problems.append(f"Service {entry.service!r} doesn't support additional instances.")
83
87
  renamable = {"app", *config.services.values(), *(f"{entry.service}-{entry.name}" for entry in config.additional_services)}
84
88
  for old in config.service_names:
85
89
  if old not in renamable:
@@ -124,7 +128,7 @@ def _local_ports(ports: list[Any], service_name: str) -> list[Any]:
124
128
  localized.append({"target": port, "host_ip": "127.0.0.1"})
125
129
  elif isinstance(port, str):
126
130
  endpoint, separator, protocol = port.partition("/")
127
- if endpoint.count(":") == 1 and not endpoint.startswith("["):
131
+ if len(port_segments(endpoint)) == 2:
128
132
  endpoint = "127.0.0.1:" + endpoint
129
133
  elif endpoint.isdigit():
130
134
  localized.append({"target": int(endpoint), "host_ip": "127.0.0.1",
@@ -222,7 +226,7 @@ def adapter_problems(config: ShipConfig, root: Path, registry: Registry) -> list
222
226
 
223
227
 
224
228
  def build_compose(config: ShipConfig, project_root: Path, *, production: bool = False,
225
- registry: Registry | None = None) -> dict[str, Any]:
229
+ registry: Registry | None = None, direct_bind: bool = False) -> dict[str, Any]:
226
230
  environment = ShipEnvironment.PRODUCTION if production else ShipEnvironment.DEVELOPMENT
227
231
  registry = registry or load_extensions(config)
228
232
  problems = adapter_problems(config, project_root, registry)
@@ -236,7 +240,7 @@ def build_compose(config: ShipConfig, project_root: Path, *, production: bool =
236
240
  app: dict[str, Any] = {
237
241
  "build": {
238
242
  "context": ".",
239
- "dockerfile": "ship/Dockerfile",
243
+ "dockerfile": docker_path(project_root, "Dockerfile"),
240
244
  "target": environment.value,
241
245
  "args": {
242
246
  "PYTHON_VERSION": config.python,
@@ -259,14 +263,14 @@ def build_compose(config: ShipConfig, project_root: Path, *, production: bool =
259
263
  if production:
260
264
  # Never build a release on a stale, locally cached base image.
261
265
  app["build"]["pull"] = True
262
- if config.publish_ports:
266
+ if config.publish_ports or config.port_publishing is not None:
263
267
  app["ports"] = ["${APP_PORT:-8000}:8000"]
264
268
  else:
265
269
  app["volumes"] = [PROJECT_MOUNT]
266
270
  app["ports"] = ["127.0.0.1:${APP_PORT:-8000}:8000"]
267
271
  # Lets a debugger in the container (debugpy) reach the IDE on the host.
268
272
  app["extra_hosts"] = ["host.docker.internal:host-gateway"]
269
- user = host_user(config)
273
+ user = host_user(config, direct_bind=direct_bind)
270
274
  if user:
271
275
  app["user"] = user
272
276
 
@@ -342,10 +346,12 @@ def build_compose(config: ShipConfig, project_root: Path, *, production: bool =
342
346
  if "ports" in model:
343
347
  if not isinstance(model["ports"], list):
344
348
  raise ConfigError(f"Compose service {service_name!r} ports must be a list.")
345
- if environment.is_development:
349
+ if environment.is_development and config.port_publishing is None:
346
350
  model["ports"] = _local_ports(model["ports"], service_name)
347
- elif not config.publish_ports:
351
+ elif not config.publish_ports and config.port_publishing is None:
348
352
  model.pop("ports")
353
+ if "expose" in model and not isinstance(model["expose"], list):
354
+ raise ConfigError(f"Compose service {service_name!r} expose must be a list.")
349
355
  mounts = model.get("volumes", [])
350
356
  if not isinstance(mounts, list):
351
357
  raise ConfigError(f"Compose service {service_name!r} volumes must be a list.")
@@ -432,13 +438,20 @@ def build_compose(config: ShipConfig, project_root: Path, *, production: bool =
432
438
  model["stop_grace_period"] = PROCESS_STOP_GRACE
433
439
  _merge(model, extra, f"services.{process}")
434
440
  services[process] = model
441
+ if config.port_publishing is not None:
442
+ available = available_ports(services, production=production)
443
+ for service in services.values():
444
+ service.pop("ports", None)
445
+ for port_id in config.port_publishing[environment.value]:
446
+ if port := available.get(port_id):
447
+ services[port.service].setdefault("ports", []).append(port.mapping)
435
448
  # Every container that runs the app's code, for Mutagen sync and the deploy script.
436
449
  compose["x-ship"] = {"app_services": [app_name, *(process for process, _ in processes)]}
437
450
  if not production:
438
451
  # Every container that sees the project at /app (the app, its processes, Node for Vite).
439
452
  synced = [service_name for service_name, model in services.items() if PROJECT_MOUNT in model.get("volumes", [])]
440
453
  compose["x-ship"]["sync_services"] = synced
441
- if mutagen_enabled():
454
+ if mutagen_enabled() and not direct_bind:
442
455
  for service_name in synced:
443
456
  mounts = [mount for mount in services[service_name]["volumes"] if mount != PROJECT_MOUNT]
444
457
  if mounts:
@@ -462,9 +475,9 @@ def build_compose(config: ShipConfig, project_root: Path, *, production: bool =
462
475
  return compose
463
476
 
464
477
 
465
- def host_user(config: ShipConfig) -> str | None:
478
+ def host_user(config: ShipConfig, *, direct_bind: bool = False) -> str | None:
466
479
  """The host UID:GID the development app runs as, or None where it doesn't apply."""
467
- if not config.host_user or mutagen_enabled() or not sys.platform.startswith("linux"):
480
+ if not config.host_user or (mutagen_enabled() and not direct_bind) or not sys.platform.startswith("linux"):
468
481
  return None
469
482
  getuid = getattr(os, "getuid", None)
470
483
  getgid = getattr(os, "getgid", None)
@@ -474,7 +487,13 @@ def host_user(config: ShipConfig) -> str | None:
474
487
 
475
488
 
476
489
  def compose_path(project_root: Path, *, production: bool = False) -> Path:
477
- return project_root / "ship" / (PRODUCTION_FILE if production else DEVELOPMENT_FILE)
490
+ return docker_directory(project_root) / (PRODUCTION_FILE if production else DEVELOPMENT_FILE)
491
+
492
+
493
+ def current_development_compose_path(project_root: Path) -> Path:
494
+ path = compose_path(project_root)
495
+ backup = project_root / LEGACY_BACKUP / DEVELOPMENT_FILE
496
+ return backup if not path.is_file() and backup.is_file() else path
478
497
 
479
498
 
480
499
  def render(model: dict[str, Any]) -> str:
@@ -487,6 +506,13 @@ def write_compose(config: ShipConfig, project_root: Path, *, production: bool =
487
506
  model: dict[str, Any] | None = None) -> Path:
488
507
  model = build_compose(config, project_root, production=production) if model is None else model
489
508
  destination = compose_path(project_root, production=production)
490
- destination.parent.mkdir(exist_ok=True)
491
- destination.write_text(render(model), encoding="utf-8")
509
+ content = render(model).encode("utf-8")
510
+ # Development reloaders watch the project mount, including this generated file.
511
+ try:
512
+ if destination.read_bytes() == content:
513
+ return destination
514
+ except FileNotFoundError:
515
+ pass
516
+ destination.parent.mkdir(parents=True, exist_ok=True)
517
+ destination.write_bytes(content)
492
518
  return destination
python_ship/config.py CHANGED
@@ -2,7 +2,7 @@
2
2
 
3
3
  Field names follow PHP Ship's ship.json so a team using both reads one format:
4
4
  ``services``, ``additionalServices``, ``serviceNames``, ``externalNetwork``,
5
- ``publishPorts``, ``deployCommands``, ``processes``, ``siloImage``,
5
+ ``publishPorts``, ``portPublishing``, ``deployCommands``, ``processes``, ``siloImage``,
6
6
  ``hostUser``, ``name`` and ``extensions`` mean the same thing in both. The
7
7
  Python-specific fields are ``framework``, ``app``, ``python``, ``server``,
8
8
  ``nodeAssets`` and ``djangoCollectstatic``.
@@ -36,19 +36,19 @@ class ConfigError(ValueError):
36
36
  SERVICE_NAME = re.compile(r"[a-z][a-z0-9]*(?:[-_][a-z0-9]+)*")
37
37
  INSTANCE_NAME = re.compile(r"[a-z][a-z0-9_]*")
38
38
  NETWORK_NAME = re.compile(r"[A-Za-z0-9][A-Za-z0-9_.-]*")
39
+ PUBLISHED_PORT = re.compile(r"[A-Za-z0-9][A-Za-z0-9_.-]*:([1-9][0-9]{0,4})(?:/(?:udp|sctp))?")
39
40
  SILO_IMAGES = ("standard", "distroless")
40
- # Groups where a second, named instance is a coherent idea. A second app runtime,
41
- # frontend toolchain or browser driver is not.
41
+ # Default capability for providers that predate the supports_named_instances attribute.
42
42
  GROUPS_SUPPORTING_ADDITIONAL_INSTANCES = ("database", "cache", "storage", "search", "mail")
43
43
  # Ship's own commands; a process or a framework console command can't take these names.
44
44
  RESERVED_COMMANDS = frozenset({
45
- "init", "up", "down", "exec", "shell", "logs", "db", "config:test", "build", "release",
45
+ "init", "up", "down", "ps", "run", "exec", "shell", "logs", "db", "check", "config:test", "build", "release", "help",
46
46
  "npm", "pnpm", "yarn", "package-manager", "test", "uv", "doctor",
47
47
  })
48
48
 
49
49
  FIELDS = (
50
50
  "$schema", "framework", "app", "python", "server", "services", "additionalServices", "serviceNames",
51
- "externalNetwork", "extensions", "name", "siloImage", "publishPorts", "hostUser",
51
+ "externalNetwork", "extensions", "name", "siloImage", "publishPorts", "portPublishing", "hostUser",
52
52
  "processes", "deployCommands", "nodeAssets", "djangoCollectstatic", "node", "build",
53
53
  )
54
54
 
@@ -91,6 +91,7 @@ class ShipConfig:
91
91
  name: str | None = None
92
92
  silo_image: str = "standard"
93
93
  publish_ports: bool = False
94
+ port_publishing: dict[str, list[str]] | None = None
94
95
  host_user: bool = True
95
96
  processes: dict[str, Process] = field(default_factory=dict)
96
97
  deploy_commands: list[Command] = field(default_factory=list)
@@ -200,11 +201,6 @@ class ShipConfig:
200
201
  if not isinstance(group, str) or not group or not isinstance(service, str) or not service:
201
202
  problems.append(f"{where} requires a group and a service.")
202
203
  continue
203
- if group not in GROUPS_SUPPORTING_ADDITIONAL_INSTANCES:
204
- problems.append(
205
- f"{where}: the {group!r} group doesn't support additional instances; "
206
- f"only {', '.join(GROUPS_SUPPORTING_ADDITIONAL_INSTANCES)} do."
207
- )
208
204
  if not isinstance(name, str) or not INSTANCE_NAME.fullmatch(name):
209
205
  problems.append(
210
206
  f"{where} name {name!r} must use lowercase letters, digits and underscores, "
@@ -262,6 +258,17 @@ class ShipConfig:
262
258
  if booleans["djangoCollectstatic"] is True and framework != "django":
263
259
  problems.append("ship.json \"djangoCollectstatic\" requires \"framework\": \"django\".")
264
260
 
261
+ port_publishing = data.get("portPublishing")
262
+ if "portPublishing" in data:
263
+ if not isinstance(port_publishing, dict) or set(port_publishing) != {"development", "production"}:
264
+ problems.append('ship.json "portPublishing" requires development and production lists.')
265
+ else:
266
+ for environment, ports in port_publishing.items():
267
+ if not isinstance(ports, list) or not all(_valid_published_port(port) for port in ports):
268
+ problems.append(f'portPublishing.{environment} must list service:port IDs (optionally /udp or /sctp).')
269
+ elif len(ports) != len(set(ports)):
270
+ problems.append(f'portPublishing.{environment} contains duplicate ports.')
271
+
265
272
  processes = data.get("processes", {})
266
273
  if not isinstance(processes, dict):
267
274
  problems.append("ship.json \"processes\" must map process names to commands.")
@@ -300,6 +307,7 @@ class ShipConfig:
300
307
  name=name,
301
308
  silo_image=silo_image,
302
309
  publish_ports=booleans["publishPorts"],
310
+ port_publishing=port_publishing,
303
311
  host_user=booleans["hostUser"],
304
312
  processes=dict(processes),
305
313
  deploy_commands=list(deploy_commands),
@@ -333,6 +341,8 @@ class ShipConfig:
333
341
  payload["siloImage"] = self.silo_image
334
342
  if self.publish_ports:
335
343
  payload["publishPorts"] = True
344
+ if self.port_publishing is not None:
345
+ payload["portPublishing"] = {key: list(ports) for key, ports in self.port_publishing.items()}
336
346
  if not self.host_user:
337
347
  payload["hostUser"] = False
338
348
  if self.processes:
@@ -354,12 +364,17 @@ _ATTRIBUTES = {
354
364
  "services": "services", "additionalServices": "additional_services",
355
365
  "serviceNames": "service_names", "externalNetwork": "external_network",
356
366
  "extensions": "extensions", "name": "name", "siloImage": "silo_image",
357
- "publishPorts": "publish_ports", "hostUser": "host_user", "processes": "processes",
367
+ "publishPorts": "publish_ports", "portPublishing": "port_publishing", "hostUser": "host_user", "processes": "processes",
358
368
  "deployCommands": "deploy_commands", "nodeAssets": "node_assets",
359
369
  "djangoCollectstatic": "django_collectstatic", "node": "node", "build": "build",
360
370
  }
361
371
 
362
372
 
373
+ def _valid_published_port(value: object) -> bool:
374
+ match = PUBLISHED_PORT.fullmatch(value) if isinstance(value, str) else None
375
+ return match is not None and int(match[1]) <= 65535
376
+
377
+
363
378
  def _valid_command(command: object) -> bool:
364
379
  if isinstance(command, str):
365
380
  return bool(command.strip()) and "\0" not in command
python_ship/contracts.py CHANGED
@@ -48,6 +48,14 @@ class ShipEnvironment(StrEnum):
48
48
  return self is ShipEnvironment.PRODUCTION
49
49
 
50
50
 
51
+ @dataclass(frozen=True)
52
+ class SetupAdvice:
53
+ """Framework setup instructions, optionally repeated before the first startup."""
54
+
55
+ message: str
56
+ before_up: bool = False
57
+
58
+
51
59
  @dataclass(frozen=True)
52
60
  class ServiceContext:
53
61
  """Everything a service needs to build its fragment for one selection.
@@ -105,7 +113,11 @@ class ServiceContext:
105
113
 
106
114
  @runtime_checkable
107
115
  class ServiceDefinition(Protocol):
108
- """One optional piece of the stack, selected per group in ship.json."""
116
+ """One optional piece of the stack, selected per group in ship.json.
117
+
118
+ Providers can declare the optional boolean ``supports_named_instances`` to
119
+ enable or disable named instances independently of their group.
120
+ """
109
121
 
110
122
  key: str
111
123
  """Unique key used in ship.json, such as ``"postgres"``."""
@@ -1,77 +1,291 @@
1
- """Append missing application settings without rewriting user values or comments."""
1
+ """Describe the generated settings and complete each environment file."""
2
+ from collections.abc import Iterator
3
+ import os
2
4
  from pathlib import Path
3
5
  import re
6
+ from stat import S_IMODE
7
+ from tempfile import NamedTemporaryFile
8
+ from typing import Any
4
9
 
5
- from .capabilities import release_description
10
+ from .capabilities import environment_defaults, release_description
6
11
  from .compose import build_compose
7
12
  from .config import ShipConfig
13
+ from .contracts import ShipEnvironment
8
14
  from .plugins import load_extensions
9
15
  from .production import read_env, required_variables
16
+ from .services import MercureService
10
17
 
18
+ _EXPRESSION = re.compile(r"(?<!\$)\$\{([A-Za-z_][A-Za-z0-9_]*)(?::-([^}]*)|:\?[^}]*)?\}")
19
+ _REFERENCE = re.compile(r"\$\{([A-Za-z_][A-Za-z0-9_]*)\}")
20
+ _SENSITIVE = re.compile(r"(?:^|_)(?:key|password|passwd|passcode|pwd|pass|secret|token|credentials?|auth|dsn|pin)(?:_|$)", re.I)
21
+ _URL_CREDENTIALS = re.compile(r"://[^/?#\s]+@|[?&](?:token|secret|password|api[_-]?key)=", re.I)
22
+ _ASSIGNMENT = re.compile(r"^([\ufeff \t]*(?:export[ \t]+)?([A-Za-z_][A-Za-z0-9_]*)[ \t]*=[ \t]*)", re.MULTILINE)
23
+ _QUOTED = re.compile(r"'[^']*'|\"(?:[^\"\\]|\\.)*\"")
24
+ _DEVELOPMENT_TOOLS = frozenset({
25
+ "VITE_PORT", "CHOKIDAR_USEPOLLING", "NPM_CONFIG_USERCONFIG", "SELENIUM_REMOTE_URL", "PLAYWRIGHT_WS_URL",
26
+ "PW_TEST_CONNECT_WS_ENDPOINT", "PLAYWRIGHT_BASE_URL", "CYPRESS_BASE_URL", "MAILPIT_WEB_PORT",
27
+ })
28
+ _SECTIONS = {
29
+ "Application": ("APP_", "DJANGO_", "FLASK_", "DEBUG", "FORWARDED_ALLOW_IPS"),
30
+ "Database": ("DB_", "MONGODB_"), "Cache": ("REDIS_", "MEMCACHED_", "VALKEY_"),
31
+ "Object storage": ("AWS_", "GARAGE_", "RUSTFS_", "SEAWEEDFS_", "SILO_"),
32
+ "Search": ("MEILISEARCH_", "ELASTICSEARCH_", "TYPESENSE_"), "Mail": ("MAIL_", "MAILPIT_"),
33
+ "Messaging and events": ("AMQP_", "RABBITMQ_", "CELERY_", "CENTRIFUGO_", "MERCURE_"),
34
+ "Development tools": ("VITE_", "SELENIUM_", "PLAYWRIGHT_", "PW_TEST_", "CYPRESS_", "CHOKIDAR_"),
35
+ }
36
+ _SECTION_ORDER = {label: index for index, label in enumerate((*_SECTIONS, "Published ports", "Project settings"))}
11
37
 
12
- def development_settings(config: ShipConfig, root: Path) -> dict[str, str]:
13
- model = build_compose(config, root)
14
- values = dict(model["services"][config.app_service]["environment"])
15
- # Include administrative credentials needed to provision the servers, without passing them to the app.
38
+
39
+ def _strings(value: Any) -> Iterator[str]:
40
+ if isinstance(value, str):
41
+ yield value
42
+ elif isinstance(value, dict):
43
+ for child in value.values():
44
+ yield from _strings(child)
45
+ elif isinstance(value, list):
46
+ for child in value:
47
+ yield from _strings(child)
48
+
49
+
50
+ def _model_settings(config: ShipConfig, model: dict[str, Any]) -> tuple[dict[str, str], dict[str, str]]:
51
+ references: dict[str, str] = {}
16
52
  for service in model["services"].values():
17
- for variable, default in re.findall(r"\$\{([A-Za-z_][A-Za-z0-9_]*):-([^}]*)\}", str(service.get("environment", {}))):
18
- values.setdefault(variable, default)
19
- for key, value in list(values.items()):
20
- if not isinstance(value, str):
21
- values.pop(key)
22
- continue
23
- match = re.fullmatch(r"\$\{([A-Za-z_][A-Za-z0-9_]*):-([^}]*)\}", value)
24
- if match:
25
- values[key] = match[2]
26
- else:
27
- # Preserve references in composite URLs, rather than resolving a password into them.
28
- values[key] = re.sub(r"\$\{([A-Za-z_][A-Za-z0-9_]*):-[^}]*\}", r"${\1}", value)
29
- return values
53
+ for text in _strings([service.get("environment", {}), service.get("ports", [])]):
54
+ for match in _EXPRESSION.finditer(text):
55
+ references.setdefault(match[1], match[2] or "")
56
+ app = model["services"][config.app_service]["environment"]
57
+ fixed = {key: value for key, value in app.items()
58
+ if isinstance(value, str) and value and not _EXPRESSION.search(value)}
59
+ values = dict(references)
60
+ for key, value in app.items():
61
+ if isinstance(value, str) and key not in references:
62
+ values[key] = _EXPRESSION.sub(lambda match: f"${{{match[1]}}}", value)
63
+ return values, fixed
64
+
65
+
66
+ def _section(key: str) -> str:
67
+ if "_HOST_PORT_" in key or key == "APP_PORT":
68
+ return "Published ports"
69
+ return next((label for label, prefixes in _SECTIONS.items() if key.startswith(prefixes)), "Project settings")
70
+
71
+
72
+ def _contains_credentials(key: str, value: str) -> bool:
73
+ return bool(_SENSITIVE.search(key) or _URL_CREDENTIALS.search(value))
74
+
75
+
76
+ def _quote(value: str) -> str:
77
+ return '"' + value.replace("\\", "\\\\").replace('"', '\\"').replace("\n", "\\n") + '"'
78
+
79
+
80
+ def _managed_connections(fixed: dict[str, str]) -> dict[str, str]:
81
+ return {key: value for key, value in fixed.items()
82
+ if key.endswith(("_HOST", "_PORT", "_URL", "_ENDPOINT", "_PROTOCOL")) and not _contains_credentials(key, value)}
83
+
84
+
85
+ def _ordered_keys(keys: set[str], values: dict[str, str]) -> list[str]:
86
+ ordered: list[str] = []
87
+ seen: set[str] = set()
88
+
89
+ def emit(key: str) -> None:
90
+ if key in seen:
91
+ return
92
+ seen.add(key)
93
+ for dependency in _REFERENCE.findall(values[key]):
94
+ if dependency in keys:
95
+ emit(dependency)
96
+ ordered.append(key)
97
+
98
+ for key in sorted(keys, key=lambda key: (_SECTION_ORDER[_section(key)], key)):
99
+ emit(key)
100
+ return ordered
101
+
102
+
103
+ def _development_environment(config: ShipConfig, root: Path) -> tuple[dict[str, str], dict[str, str]]:
104
+ registry = load_extensions(config)
105
+ values, fixed = _model_settings(config, build_compose(config, root, registry=registry))
106
+ return {**environment_defaults(registry.adapter(config), config, root, ShipEnvironment.DEVELOPMENT), **values}, fixed
107
+
108
+
109
+ def development_settings(config: ShipConfig, root: Path) -> dict[str, str]:
110
+ return _development_environment(config, root)[0]
30
111
 
31
112
 
32
113
  def append_missing(path: Path, values: dict[str, str], *, private: bool = False) -> list[str]:
33
114
  present = read_env(path)
34
- missing = sorted(set(values) - set(present))
115
+ missing = _ordered_keys(set(values) - set(present), values)
35
116
  if not missing:
36
117
  return []
37
118
  current = path.read_text(encoding="utf-8") if path.is_file() else ""
38
- def quote(value: str) -> str:
39
- return '"' + value.replace("\\", "\\\\").replace('"', '\\"').replace("\n", "\\n") + '"'
40
119
  # Private creation from the first byte, including on POSIX systems with permissive umasks.
41
- import os
42
120
  descriptor = os.open(path, os.O_WRONLY | os.O_CREAT | os.O_APPEND, 0o600 if private else 0o644)
43
121
  with os.fdopen(descriptor, "a", encoding="utf-8") as stream:
44
122
  stream.write(("\n" if current and not current.endswith("\n") else "") + "\n# Added by ship init\n")
45
- stream.write("".join(f"{key}={quote(values[key]) if values[key] else ''}\n" for key in missing))
123
+ section = None
124
+ for key in missing:
125
+ group = _section(key)
126
+ if group != section:
127
+ stream.write(f"\n# {group}\n")
128
+ section = group
129
+ stream.write(f"{key}={_quote(values[key]) if values[key] else ''}\n")
46
130
  return missing
47
131
 
48
132
 
49
- def ensure_environment(config: ShipConfig, root: Path) -> None:
50
- development = development_settings(config, root)
51
- (root / ".env.example").touch(exist_ok=True)
52
- append_missing(root / ".env.example", development)
133
+ def update_settings(path: Path, values: dict[str, str], *, private: bool = False) -> None:
134
+ """Update explicitly chosen values while preserving other assignments and comments."""
135
+ if path.is_symlink():
136
+ path = path.resolve()
137
+ append_missing(path, values, private=private)
138
+ current_values = read_env(path)
139
+ changed = {key: value for key, value in values.items() if current_values.get(key) != value}
140
+ if not changed:
141
+ return
142
+ with path.open(encoding="utf-8", newline="") as stream:
143
+ current = stream.read()
144
+ for key, value in changed.items():
145
+ assignment = re.compile(rf"^([\ufeff \t]*(?:export[ \t]+)?{re.escape(key)}[ \t]*=[ \t]*)[^\r\n]*", re.MULTILINE)
146
+ matches = list(assignment.finditer(current))
147
+ if matches:
148
+ match = matches[-1]
149
+ previous = match[0][len(match[1]):]
150
+ if previous.startswith(("'", '"')):
151
+ quoted = _QUOTED.match(previous)
152
+ if not quoted:
153
+ continue
154
+ previous = previous[quoted.end():]
155
+ comment = re.search(r"[ \t]+#.*$", previous)
156
+ rendered = value if re.fullmatch(r"[A-Za-z0-9_./:\[\]-]*", value) else _quote(value)
157
+ current = current[:match.start()] + match[1] + rendered + (comment[0] if comment else "") + current[match.end():]
158
+ _replace_contents(path, current)
159
+
160
+
161
+ def _replace_contents(path: Path, current: str) -> None:
162
+ mode = S_IMODE(path.stat().st_mode)
163
+ pending = NamedTemporaryFile(mode="w", encoding="utf-8", newline="", dir=path.parent, delete=False)
164
+ temporary = Path(pending.name)
165
+ try:
166
+ with pending as stream:
167
+ stream.write(current)
168
+ temporary.chmod(mode)
169
+ temporary.replace(path)
170
+ finally:
171
+ temporary.unlink(missing_ok=True)
172
+
173
+
174
+ def ensure_environment(config: ShipConfig, root: Path, host_ports: dict[str, dict[str, str]] | None = None) -> dict[str, set[str]]:
175
+ development, fixed = _development_environment(config, root)
176
+ if host_ports:
177
+ development.update(host_ports["development"])
178
+ mercure_port = (host_ports or {}).get("development", {}).get("MERCURE_PORT") if config.services.get("broadcasting") == "mercure" else None
179
+ if mercure_port:
180
+ development["MERCURE_PUBLIC_URL"] = MercureService.development_url(mercure_port)
181
+ example = root / ".env.example"
182
+ example.touch(exist_ok=True)
53
183
  env = root / ".env"
54
184
  if not env.exists():
55
- import shutil
56
- shutil.copyfile(root / ".env.example", env)
57
- env.chmod(0o600)
185
+ with os.fdopen(os.open(env, os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o600), "wb") as stream:
186
+ stream.write(example.read_bytes())
58
187
  append_missing(env, development, private=True)
188
+ development_updates = _managed_connections(fixed)
189
+ update_settings(env, development_updates, private=True)
190
+ current = read_env(env)
191
+ append_missing(example, {
192
+ **dict.fromkeys(current, ""),
193
+ **{key: "" if _contains_credentials(key, value) else value for key, value in development.items()},
194
+ })
195
+ update_settings(example, development_updates)
59
196
  registry = load_extensions(config)
60
197
  production = build_compose(config, root, production=True, registry=registry)
61
- required = set(required_variables(production)) | set(release_description(registry.adapter(config), config, root).get("requiredEnv", []))
62
- append_missing(root / ".env.production", dict.fromkeys(required, ""), private=True)
198
+ adapter = registry.adapter(config)
199
+ defaults = environment_defaults(adapter, config, root, ShipEnvironment.PRODUCTION)
200
+ values, production_fixed = _model_settings(config, production)
201
+ required = set(required_variables(production)) | set(release_description(adapter, config, root).get("requiredEnv", []))
202
+ dev_only = development.keys() - (values.keys() | defaults.keys() | required)
203
+ placeholders = dict.fromkeys(current.keys() - dev_only - _DEVELOPMENT_TOOLS, "")
204
+ production_settings = {
205
+ **placeholders, **defaults,
206
+ **{key: "" if _contains_credentials(key, value) else value for key, value in values.items()},
207
+ **dict.fromkeys(required, ""),
208
+ **(host_ports["production"] if host_ports else {}),
209
+ }
210
+ production_file = root / ".env.production"
211
+ if not production_file.exists() and not production_file.is_symlink():
212
+ os.close(os.open(production_file, os.O_WRONLY | os.O_CREAT, 0o600))
213
+ append_missing(production_file, production_settings, private=True)
214
+ update_settings(production_file, {key: value for key, value in _managed_connections(production_fixed).items() if key not in required},
215
+ private=True)
216
+ _remove_dev_only(production_file, (set(development) & _DEVELOPMENT_TOOLS) - production_settings.keys())
217
+ if host_ports:
218
+ for filename in (".env", ".env.example"):
219
+ path = root / filename
220
+ changes = dict(host_ports["development"])
221
+ values = read_env(path)
222
+ if mercure_port and values.get("MERCURE_PUBLIC_URL", "") in (
223
+ "", MercureService.development_url(), MercureService.development_url(values.get("MERCURE_PORT", ""))
224
+ ):
225
+ changes["MERCURE_PUBLIC_URL"] = development["MERCURE_PUBLIC_URL"]
226
+ update_settings(path, changes, private=filename == ".env")
227
+ update_settings(production_file, host_ports["production"], private=True)
228
+ private_required = {key for key in required if not key.endswith(("_URL", "_ISSUER", "_ORIGINS"))}
229
+ public_production = (set(values) | set(defaults) | required) - private_required
230
+ return {".env": set(development), ".env.example": set(development), ".env.production": public_production}
231
+
232
+
233
+ def _remove_dev_only(path: Path, keys: set[str]) -> None:
234
+ if not keys:
235
+ return
236
+ path = path.resolve()
237
+ with path.open(encoding="utf-8", newline="") as stream:
238
+ lines = stream.readlines()
239
+ kept = []
240
+ for line in lines:
241
+ match = _ASSIGNMENT.match(line)
242
+ if match and match[2] in keys:
243
+ value = line[match.end():].rstrip("\r\n")
244
+ # Leave multiline quoted entries intact.
245
+ if not value.startswith(("'", '"')) or _QUOTED.match(value):
246
+ continue
247
+ kept.append(line)
248
+ if len(kept) != len(lines):
249
+ _replace_contents(path, "".join(kept))
63
250
 
64
251
 
65
252
  def environment_warnings(config: ShipConfig, root: Path) -> list[str]:
66
253
  desired = development_settings(config, root)
254
+ _, fixed = _model_settings(config, build_compose(config, root))
67
255
  warnings = []
68
256
  for filename in (".env", ".env.example"):
69
257
  values = read_env(root / filename)
70
- for key, value in desired.items():
258
+ for key in desired:
71
259
  if key not in values:
72
260
  warnings.append(f"{filename} is missing {key}; run ship init to append it.")
73
- elif "${" not in value and values[key] != value:
74
- # Defaults can be overridden, but fixed protocol/host settings are controlled by Compose.
75
- if key.endswith(("_HOST", "_PORT", "_URL")):
76
- warnings.append(f"{filename}'s {key} differs from Ship's managed connection; the container setting takes precedence.")
261
+ elif key in fixed and values[key] != fixed[key] and key.endswith(("_HOST", "_PORT", "_URL")):
262
+ warnings.append(f"{filename}'s {key} differs from Ship's managed connection; the container setting takes precedence.")
77
263
  return warnings
264
+
265
+
266
+ ENV_FILES = (".env", ".env.example", ".env.production")
267
+
268
+
269
+ def environment_rows(config: ShipConfig, root: Path, filename: str, previous: dict[str, str],
270
+ managed: set[str]) -> list[tuple[str, str, str, str]]:
271
+ """Show resolved values for Ship's known settings and mask credentials and custom values."""
272
+ current = read_env(root / filename)
273
+ rows = []
274
+ instances = sorted(config.additional_services, key=lambda entry: len(entry.name), reverse=True)
275
+ for key in dict.fromkeys([*current, *previous]):
276
+ value = current.get(key, "")
277
+ if key not in current:
278
+ status = "Removed"
279
+ elif key not in previous:
280
+ status = "Added"
281
+ else:
282
+ status = "Updated" if value != previous[key] else "Unchanged"
283
+ if value and (key not in managed or _contains_credentials(key, value)):
284
+ shown = "******"
285
+ else:
286
+ shown = re.sub(r"[\x00-\x1f\x7f-\x9f]", " ", value)
287
+ shown = shown if len(shown) <= 56 else shown[:55] + "…"
288
+ source = next((f"{entry.service} ({entry.name})" for entry in instances if key.startswith(entry.name.upper() + "_")),
289
+ _section(key))
290
+ rows.append((key, shown, source, status))
291
+ return rows