python-ship 0.1.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 (44) hide show
  1. python_ship/__init__.py +1 -1
  2. python_ship/adapters.py +82 -8
  3. python_ship/build_environment.py +60 -0
  4. python_ship/capabilities.py +68 -0
  5. python_ship/cli.py +387 -77
  6. python_ship/compose.py +104 -25
  7. python_ship/config.py +92 -25
  8. python_ship/contracts.py +38 -1
  9. python_ship/environment.py +291 -0
  10. python_ship/image_build.py +143 -0
  11. python_ship/init.py +381 -54
  12. python_ship/layout.py +50 -0
  13. python_ship/mutagen.py +2 -2
  14. python_ship/package_managers.py +135 -0
  15. python_ship/plugins.py +22 -2
  16. python_ship/portable.py +119 -0
  17. python_ship/portable_data.py +512 -0
  18. python_ship/ports.py +120 -0
  19. python_ship/production.py +4 -3
  20. python_ship/release.py +199 -73
  21. python_ship/runtime.py +9 -7
  22. python_ship/schema/service-environment.json +22 -0
  23. python_ship/schema/ship-release.schema.json +145 -0
  24. python_ship/schema/ship.schema.json +501 -0
  25. python_ship/security.py +2 -1
  26. python_ship/servers.py +4 -4
  27. python_ship/service_setup.py +80 -0
  28. python_ship/services.py +120 -39
  29. python_ship/storage.py +15 -6
  30. python_ship/stubs.py +60 -24
  31. python_ship/templates/Dockerfile +26 -4
  32. python_ship/templates/app-entrypoint.py +39 -0
  33. python_ship/templates/check-python-security-floor.py +1 -1
  34. python_ship/templates/launcher +49 -0
  35. python_ship/terminal.py +77 -0
  36. python_ship/uv.py +3 -1
  37. python_ship/wizard.py +123 -0
  38. {python_ship-0.1.0.dist-info → python_ship-0.3.0.dist-info}/METADATA +442 -239
  39. python_ship-0.3.0.dist-info/RECORD +47 -0
  40. python_ship-0.1.0.dist-info/RECORD +0 -30
  41. {python_ship-0.1.0.dist-info → python_ship-0.3.0.dist-info}/WHEEL +0 -0
  42. {python_ship-0.1.0.dist-info → python_ship-0.3.0.dist-info}/entry_points.txt +0 -0
  43. {python_ship-0.1.0.dist-info → python_ship-0.3.0.dist-info}/licenses/LICENSE.md +0 -0
  44. {python_ship-0.1.0.dist-info → python_ship-0.3.0.dist-info}/top_level.txt +0 -0
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.3.0"
python_ship/adapters.py CHANGED
@@ -7,9 +7,9 @@ from pathlib import Path
7
7
  import re
8
8
 
9
9
  from .config import ShipConfig
10
- from .contracts import Interface
10
+ from .contracts import Interface, SetupAdvice, ShipEnvironment
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,56 @@ def callable_interface(project_root: Path, target: str) -> Interface | None:
104
104
  return None
105
105
 
106
106
 
107
- class GenericAdapter:
107
+ def _declares_celery(root: Path) -> bool:
108
+ return any(path.is_file() and re.search(r"\bcelery\b", path.read_text(encoding="utf-8"), re.I)
109
+ for path in (root / "pyproject.toml", root / "requirements.txt"))
110
+
111
+
112
+ class PythonCapabilities:
113
+ """Optional metadata and process suggestions, requiring actual project evidence."""
114
+
115
+ def describe_release(self, config: ShipConfig, root: Path) -> dict:
116
+ required = []
117
+ if config.framework in ("django", "flask"):
118
+ for path in python_files(root):
119
+ try:
120
+ tree = ast.parse(path.read_text(encoding="utf-8"))
121
+ except (OSError, SyntaxError):
122
+ continue
123
+ for node in ast.walk(tree):
124
+ if not isinstance(node, (ast.Assign, ast.AnnAssign)):
125
+ continue
126
+ targets = node.targets if isinstance(node, ast.Assign) else [node.target]
127
+ if not any(isinstance(target, ast.Name) and target.id == "SECRET_KEY" for target in targets):
128
+ continue
129
+ for child in ast.walk(node.value) if node.value is not None else []:
130
+ # Only explicit environment reads determine a setting name.
131
+ if isinstance(child, ast.Subscript) and isinstance(child.value, ast.Attribute) and child.value.attr == "environ":
132
+ if isinstance(child.slice, ast.Constant) and isinstance(child.slice.value, str):
133
+ required.append(child.slice.value)
134
+ elif isinstance(child, ast.Call) and isinstance(child.func, ast.Attribute) and child.args:
135
+ if child.func.attr in ("getenv", "get") and isinstance(child.args[0], ast.Constant) and isinstance(child.args[0].value, str):
136
+ owner = child.func.value
137
+ if child.func.attr == "getenv" or (isinstance(owner, ast.Attribute) and owner.attr == "environ"):
138
+ required.append(child.args[0].value)
139
+ return {"health": None, "urlSetting": None, "requiredEnv": sorted(set(required))}
140
+
141
+ def suggest_processes(self, config: ShipConfig, root: Path) -> dict:
142
+ if not _declares_celery(root):
143
+ return {}
144
+ # The app supplies its Celery instance; the environment remains authoritative.
145
+ suggestions = {"celery-beat": "celery -A \"$CELERY_APP\" beat --loglevel=info --schedule=/tmp/celerybeat-schedule"}
146
+ if config.services.get("tasks") != "celery":
147
+ suggestions["celery-worker"] = "celery -A \"$CELERY_APP\" worker --loglevel=info"
148
+ return suggestions
149
+
150
+ def setup_advice(self, config: ShipConfig, root: Path) -> list[SetupAdvice]:
151
+ if config.services.get("tasks") == "celery" and not _declares_celery(root):
152
+ return [SetupAdvice("Declare Celery in your project dependencies and set CELERY_APP before starting the worker.", before_up=True)]
153
+ return []
154
+
155
+
156
+ class GenericAdapter(PythonCapabilities):
108
157
  """Serve any ASGI or WSGI callable; no web framework required."""
109
158
 
110
159
  key = "generic"
@@ -140,13 +189,29 @@ class GenericAdapter:
140
189
  return []
141
190
 
142
191
 
143
- class DjangoAdapter:
192
+ class DjangoAdapter(PythonCapabilities):
144
193
  key = "django"
145
194
  label = "Django"
146
195
 
147
196
  def detect(self, project_root: Path) -> bool:
148
197
  return (project_root / "manage.py").is_file()
149
198
 
199
+ def environment_defaults(self, config: ShipConfig, root: Path, environment: ShipEnvironment) -> dict[str, str]:
200
+ for path in (module_file(root, config.app), root / "manage.py"):
201
+ if not path.is_file():
202
+ continue
203
+ found = re.search(r"""DJANGO_SETTINGS_MODULE['"]\s*,\s*['"]([\w.]+)['"]""",
204
+ path.read_text(encoding="utf-8", errors="replace"))
205
+ if found:
206
+ return {"DJANGO_SETTINGS_MODULE": found[1]}
207
+ return {}
208
+
209
+ def setup_advice(self, config: ShipConfig, root: Path) -> list[SetupAdvice]:
210
+ advice = super().setup_advice(config, root)
211
+ if config.services.get("database"):
212
+ advice.append(SetupAdvice("Configure Django DATABASES from the DB_* settings, then run `ship manage migrate` after `ship up`."))
213
+ return advice
214
+
150
215
  def default_app(self, project_root: Path) -> str | None:
151
216
  manage = project_root / "manage.py"
152
217
  package = None
@@ -204,7 +269,7 @@ def _framework_apps(project_root: Path, module: str, constructor: str) -> list[t
204
269
  return found
205
270
 
206
271
 
207
- class FastAPIAdapter:
272
+ class FastAPIAdapter(PythonCapabilities):
208
273
  key = "fastapi"
209
274
  label = "FastAPI"
210
275
 
@@ -231,17 +296,26 @@ class FastAPIAdapter:
231
296
  return []
232
297
 
233
298
 
234
- class FlaskAdapter:
299
+ class FlaskAdapter(PythonCapabilities):
235
300
  """Flask is WSGI, so it runs on Gunicorn (the suggestion) or Granian."""
236
301
 
237
302
  key = "flask"
238
303
  label = "Flask"
239
304
 
240
305
  def detect(self, project_root: Path) -> bool:
241
- return bool(_framework_apps(project_root, "flask", "Flask"))
306
+ return self.default_app(project_root) is not None
242
307
 
243
308
  def default_app(self, project_root: Path) -> str | None:
244
309
  found = _framework_apps(project_root, "flask", "Flask")
310
+ # Factories are common Flask layouts; detect their definition without importing the app.
311
+ for path in python_files(project_root):
312
+ try:
313
+ tree = ast.parse(path.read_text(encoding="utf-8"))
314
+ except (OSError, SyntaxError):
315
+ continue
316
+ if any(isinstance(node, ast.FunctionDef) and node.name == "create_app" for node in tree.body):
317
+ if "flask" in path.read_text(encoding="utf-8") and "Flask(" in path.read_text(encoding="utf-8"):
318
+ return f"{_module_name(project_root, path)}:create_app()"
245
319
  return f"{_module_name(project_root, found[0][0])}:{found[0][1]}" if found else None
246
320
 
247
321
  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,68 @@
1
+ """Optional adapter capabilities, shared by initialization, validation and releases."""
2
+ from pathlib import Path
3
+ import re
4
+ from typing import Any
5
+
6
+ from .config import ConfigError, ShipConfig, http_problem, process_problem
7
+ from .contracts import SetupAdvice, ShipEnvironment
8
+ from .production import DEVELOPMENT_DEFAULTS, read_env
9
+
10
+
11
+ def release_description(adapter: Any, config: ShipConfig, root: Path) -> dict[str, Any]:
12
+ hook = getattr(adapter, "describe_release", None)
13
+ if hook is None:
14
+ return {}
15
+ result = hook(config, root)
16
+ if not isinstance(result, dict) or set(result) - {"health", "urlSetting", "requiredEnv"}:
17
+ raise ConfigError(f"Adapter {adapter.key}: invalid release description.")
18
+ problem = http_problem({"port": 8000, "role": "site", "health": result.get("health"), "urlSetting": result.get("urlSetting")})
19
+ if problem:
20
+ raise ConfigError(problem)
21
+ if not isinstance(result.get("requiredEnv", []), list) or any(
22
+ not isinstance(key, str) or not re.fullmatch(r"[A-Za-z_][A-Za-z0-9_]*", key) for key in result.get("requiredEnv", [])):
23
+ raise ConfigError("Adapter requiredEnv must list setting names.")
24
+ return result
25
+
26
+
27
+ def environment_defaults(adapter: Any, config: ShipConfig, root: Path, environment: ShipEnvironment) -> dict[str, str]:
28
+ hook = getattr(adapter, "environment_defaults", None)
29
+ if hook is None:
30
+ return {}
31
+ result = hook(config, root, environment)
32
+ if not isinstance(result, dict) or any(not isinstance(key, str) or not re.fullmatch(r"[A-Za-z_][A-Za-z0-9_]*", key)
33
+ or not isinstance(value, str) for key, value in result.items()):
34
+ raise ConfigError(f"Adapter {adapter.key!r} environment defaults must map variable names to strings.")
35
+ return result
36
+
37
+
38
+ def setup_advice(config: ShipConfig, root: Path) -> list[SetupAdvice]:
39
+ from .plugins import load_extensions
40
+
41
+ adapter = load_extensions(config).adapter(config)
42
+ hook = getattr(adapter, "setup_advice", None)
43
+ if hook is None:
44
+ return []
45
+ result = hook(config, root)
46
+ if not isinstance(result, list) or any(not isinstance(item, SetupAdvice) or not item.message.strip() for item in result):
47
+ raise ConfigError(f"Adapter {adapter.key!r} setup advice must be a list of nonempty SetupAdvice entries.")
48
+ return result
49
+
50
+
51
+ def required_setting_problems(description: dict[str, Any], root: Path) -> list[str]:
52
+ values = read_env(root / ".env.production")
53
+ return [f"{key} is required in .env.production with a real value."
54
+ for key in description.get("requiredEnv", []) if not values.get(key) or values[key].lower() in DEVELOPMENT_DEFAULTS]
55
+
56
+
57
+ def process_suggestions(adapter: Any, config: ShipConfig, root: Path) -> dict[str, Any]:
58
+ hook = getattr(adapter, "suggest_processes", None)
59
+ if hook is None:
60
+ return {}
61
+ result = hook(config, root)
62
+ if not isinstance(result, dict):
63
+ raise ConfigError("Adapter process suggestions must map names to process definitions.")
64
+ for name, value in result.items():
65
+ _, issues = ShipConfig.from_data({"app": config.app, "processes": {name: value}})
66
+ if process_problem(value) or issues:
67
+ raise ConfigError(f"Invalid adapter process suggestion {name!r}.")
68
+ return result