django-native 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.
@@ -0,0 +1,98 @@
1
+ """Build planning and versioned manifest generation."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import hashlib
6
+ import json
7
+ import platform
8
+ import sys
9
+ from dataclasses import asdict, dataclass, field
10
+ from datetime import datetime, timezone
11
+ from pathlib import Path
12
+ from typing import Any
13
+
14
+ from django_native.analysis import AnalysisReport
15
+ from django_native.analysis.resources import ResourceReport
16
+ from django_native.configuration import Config
17
+ from django_native.diagnostics import DiagnosticReport
18
+ from django_native.project import DiscoveredProject
19
+
20
+ SCHEMA_VERSION = "1.0"
21
+
22
+
23
+ @dataclass
24
+ class BuildManifest:
25
+ project: dict[str, Any]
26
+ environment: dict[str, Any]
27
+ compiler: dict[str, Any]
28
+ resources: dict[str, Any]
29
+ runtime: dict[str, Any]
30
+ analysis: dict[str, Any]
31
+ created_at: str
32
+ plan_hash: str = ""
33
+ schema_version: str = SCHEMA_VERSION
34
+ status: str = "planned"
35
+
36
+ def to_dict(self) -> dict[str, Any]:
37
+ return asdict(self)
38
+
39
+ def canonical_json(self) -> str:
40
+ return json.dumps(self.to_dict(), sort_keys=True, separators=(",", ":"))
41
+
42
+ def compute_hash(self) -> str:
43
+ return hashlib.sha256(self.canonical_json().encode("utf-8")).hexdigest()
44
+
45
+
46
+ def build_manifest(
47
+ project: DiscoveredProject,
48
+ config: Config,
49
+ analysis: AnalysisReport,
50
+ resources: ResourceReport,
51
+ diagnostics: DiagnosticReport,
52
+ ) -> BuildManifest:
53
+ manifest = BuildManifest(
54
+ project={
55
+ "name": config.project.name or project.root.name,
56
+ "settings": config.project.settings or project.settings_module,
57
+ "package": project.project_package,
58
+ },
59
+ environment={
60
+ "python": ".".join(map(str, sys.version_info[:3])),
61
+ "platform": sys.platform,
62
+ "platform_name": platform.system().lower(),
63
+ "architecture": platform.machine(),
64
+ },
65
+ compiler={
66
+ "backend": config.compiler.backend,
67
+ "mode": config.compiler.mode,
68
+ },
69
+ resources={
70
+ "templates": config.resources.include_templates,
71
+ "static": config.resources.collect_static,
72
+ "migrations": config.resources.include_migrations,
73
+ "translations": config.resources.include_translations,
74
+ "counts": resources.counts(),
75
+ },
76
+ runtime={
77
+ "profile": config.runtime.profile,
78
+ "host": config.runtime.host,
79
+ "port": config.runtime.port,
80
+ "database": config.database.strategy,
81
+ },
82
+ analysis={
83
+ "distributions": len(analysis.distributions),
84
+ "dynamic_imports": [r.module for r in analysis.dynamic_imports],
85
+ "missing": analysis.missing,
86
+ "installed_apps": analysis.installed_apps or project.apps,
87
+ },
88
+ created_at=datetime.now(timezone.utc).isoformat(),
89
+ )
90
+ manifest.plan_hash = manifest.compute_hash()
91
+ if diagnostics.has_errors:
92
+ manifest.status = "invalid"
93
+ return manifest
94
+
95
+
96
+ def write_manifest(manifest: BuildManifest, path: Path) -> Path:
97
+ path.write_text(json.dumps(manifest.to_dict(), indent=2) + "\n", encoding="utf-8")
98
+ return path
@@ -0,0 +1,31 @@
1
+ """Plugin discovery via Python entry points."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from dataclasses import dataclass
6
+
7
+ GROUPS = (
8
+ "django_native.backends",
9
+ "django_native.resources",
10
+ "django_native.runtimes",
11
+ "django_native.packagers",
12
+ )
13
+
14
+
15
+ @dataclass
16
+ class PluginInfo:
17
+ name: str
18
+ group: str
19
+ value: str
20
+
21
+
22
+ def list_plugins() -> list[PluginInfo]:
23
+ try:
24
+ from importlib.metadata import entry_points
25
+ except Exception: # pragma: no cover
26
+ return []
27
+ out: list[PluginInfo] = []
28
+ for group in GROUPS:
29
+ for ep in entry_points(group=group):
30
+ out.append(PluginInfo(name=ep.name, group=group, value=ep.value))
31
+ return out
@@ -0,0 +1,220 @@
1
+ """Project scaffolding (init) and discovery (inspect)."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import ast
6
+ import re
7
+ import shutil
8
+ import sys
9
+ from dataclasses import dataclass, field
10
+ from pathlib import Path
11
+
12
+ from django_native.diagnostics import DjangoNativeError
13
+
14
+ PROJECT_NAME_RE = re.compile(r"^[A-Za-z_][A-Za-z0-9_]*$")
15
+
16
+ CONFIG_TEMPLATE = """\
17
+ [project]
18
+ name = "{name}"
19
+ settings = "{name}.settings"
20
+
21
+ [compiler]
22
+ backend = "nuitka"
23
+ mode = "standalone"
24
+
25
+ [build]
26
+ output = "dist"
27
+ clean = true
28
+ jobs = 4
29
+
30
+ [target]
31
+ platform = "native"
32
+ architecture = "native"
33
+
34
+ [resources]
35
+ collect_static = true
36
+ include_templates = true
37
+ include_migrations = true
38
+ include_translations = true
39
+
40
+ [runtime]
41
+ profile = "local"
42
+ host = "127.0.0.1"
43
+ port = 8000
44
+ open_browser = true
45
+ migrations_on_startup = false
46
+
47
+ [database]
48
+ strategy = "persistent"
49
+
50
+ [analysis]
51
+ strict = false
52
+ """
53
+
54
+
55
+ @dataclass
56
+ class CreatedProject:
57
+ name: str
58
+ root: Path
59
+ config_path: Path
60
+
61
+
62
+ @dataclass
63
+ class DiscoveredProject:
64
+ root: Path
65
+ manage_py: Path
66
+ settings_module: str
67
+ project_package: str
68
+ apps: list[str] = field(default_factory=list)
69
+ wsgi_entry: str | None = None
70
+ asgi_entry: str | None = None
71
+ python_version: str | None = None
72
+ django_version: str | None = None
73
+ dependency_files: list[Path] = field(default_factory=list)
74
+
75
+
76
+ def validate_project_name(name: str) -> None:
77
+ if not PROJECT_NAME_RE.match(name):
78
+ raise DjangoNativeError(
79
+ f"Invalid project name {name!r}: must match [A-Za-z_][A-Za-z0-9_]*",
80
+ code="DN2001",
81
+ )
82
+
83
+
84
+ def create_project(
85
+ name: str,
86
+ directory: Path | None = None,
87
+ *,
88
+ force: bool = False,
89
+ ) -> CreatedProject:
90
+ """Scaffold a new Django project using Django's startproject."""
91
+ validate_project_name(name)
92
+ base = (directory or Path.cwd()).resolve()
93
+ target = base / name
94
+
95
+ if target.exists() and any(target.iterdir()) and not force:
96
+ raise DjangoNativeError(
97
+ f"Directory {target} is not empty; refusing to overwrite.",
98
+ code="DN2002",
99
+ )
100
+
101
+ try:
102
+ import django
103
+ from django.core.management import call_command
104
+ except ImportError as exc: # pragma: no cover
105
+ raise DjangoNativeError(
106
+ "Django is required for project creation. Install: pip install django",
107
+ code="DN2003",
108
+ ) from exc
109
+
110
+ base.mkdir(parents=True, exist_ok=True)
111
+ try:
112
+ # Django creates <directory>/<name>. We want target = base/name.
113
+ call_command("startproject", name, str(base))
114
+
115
+ config_path = target / "django-native.toml"
116
+ config_path.write_text(CONFIG_TEMPLATE.format(name=name), encoding="utf-8")
117
+
118
+ (target / "requirements.txt").write_text(f"Django>={django.get_version()}\n", encoding="utf-8")
119
+
120
+ (target / "README.md").write_text(
121
+ f"# {name}\n\nGenerated with Django Native "
122
+ f"{_version()}.\n\n## Run\n\n```\npython manage.py runserver\n```\n\n"
123
+ "## Inspect and plan\n\n```\ndjango-native inspect\n"
124
+ "django-native plan --output build-plan.json\n```\n",
125
+ encoding="utf-8",
126
+ )
127
+ return CreatedProject(name=name, root=target, config_path=config_path)
128
+ except Exception:
129
+ if target.exists():
130
+ shutil.rmtree(target, ignore_errors=True)
131
+ raise
132
+
133
+
134
+ def _version() -> str:
135
+ from django_native import __version__
136
+ return __version__
137
+
138
+
139
+ def discover_project(start: Path | None = None) -> DiscoveredProject:
140
+ root = (start or Path.cwd()).resolve()
141
+ manage_py = root / "manage.py"
142
+ if not manage_py.exists():
143
+ raise DjangoNativeError(
144
+ f"No manage.py found in {root}. Run from a Django project root.",
145
+ code="DN2004",
146
+ )
147
+ settings_module = _detect_settings_module(manage_py, root)
148
+ project_package = settings_module.split(".")[0]
149
+
150
+ # Respect explicit config if present.
151
+ cfg_file = root / "django-native.toml"
152
+ if cfg_file.exists():
153
+ try:
154
+ from django_native.configuration import load_config
155
+ cfg = load_config(cfg_file)
156
+ if cfg.project.settings:
157
+ settings_module = cfg.project.settings
158
+ project_package = settings_module.split(".")[0]
159
+ except DjangoNativeError:
160
+ pass
161
+
162
+ apps = _parse_installed_apps(root, settings_module)
163
+
164
+ wsgi = f"{project_package}.wsgi" if (root / project_package / "wsgi.py").exists() else None
165
+ asgi = f"{project_package}.asgi" if (root / project_package / "asgi.py").exists() else None
166
+
167
+ dep_files = [p for p in (root / "requirements.txt", root / "pyproject.toml", root / "setup.py") if p.exists()]
168
+
169
+ django_ver = None
170
+ try:
171
+ import django # noqa: F401
172
+ django_ver = django.get_version()
173
+ except ImportError:
174
+ pass
175
+
176
+ return DiscoveredProject(
177
+ root=root,
178
+ manage_py=manage_py,
179
+ settings_module=settings_module,
180
+ project_package=project_package,
181
+ apps=apps,
182
+ wsgi_entry=wsgi,
183
+ asgi_entry=asgi,
184
+ python_version=f"{sys.version_info.major}.{sys.version_info.minor}",
185
+ django_version=django_ver,
186
+ dependency_files=dep_files,
187
+ )
188
+
189
+
190
+ def _detect_settings_module(manage_py: Path, root: Path) -> str:
191
+ text = manage_py.read_text(encoding="utf-8")
192
+ match = re.search(r"DJANGO_SETTINGS_MODULE[\"'\s,=]+([\w\.]+)", text)
193
+ if match:
194
+ return match.group(1)
195
+ for child in root.iterdir():
196
+ if child.is_dir() and (child / "settings.py").exists():
197
+ return f"{child.name}.settings"
198
+ return "settings"
199
+
200
+
201
+ def _parse_installed_apps(root: Path, settings_module: str) -> list[str]:
202
+ settings_path = root / (settings_module.replace(".", "/") + ".py")
203
+ if not settings_path.exists():
204
+ return []
205
+ try:
206
+ tree = ast.parse(settings_path.read_text(encoding="utf-8"))
207
+ except SyntaxError:
208
+ return []
209
+ for node in tree.body:
210
+ if (
211
+ isinstance(node, ast.Assign)
212
+ and any(isinstance(t, ast.Name) and t.id == "INSTALLED_APPS" for t in node.targets)
213
+ and isinstance(node.value, (ast.List, ast.Tuple))
214
+ ):
215
+ return [
216
+ elt.value
217
+ for elt in node.value.elts
218
+ if isinstance(elt, ast.Constant) and isinstance(elt.value, str)
219
+ ]
220
+ return []
File without changes
@@ -0,0 +1,75 @@
1
+ """Runtime launcher generation."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from dataclasses import dataclass
6
+ from pathlib import Path
7
+
8
+ from django_native.planning import BuildManifest
9
+
10
+ LAUNCHER_TEMPLATE = '''\
11
+ """Generated Django Native launcher for {name}."""
12
+
13
+ import os
14
+ import sys
15
+ import threading
16
+ import webbrowser
17
+ from pathlib import Path
18
+
19
+ BASE_DIR = Path(__file__).resolve().parent
20
+ os.environ.setdefault("DJANGO_SETTINGS_MODULE", "{settings}")
21
+
22
+ DATA_DIR = BASE_DIR / "data"
23
+ DATA_DIR.mkdir(parents=True, exist_ok=True)
24
+ os.environ.setdefault("DJANGO_NATIVE_DATA_DIR", str(DATA_DIR))
25
+
26
+
27
+ def _open_browser(url: str) -> None:
28
+ threading.Timer(1.5, lambda: webbrowser.open(url)).start()
29
+
30
+
31
+ def main() -> int:
32
+ try:
33
+ from django.core.management import execute_from_command_line
34
+ except Exception as exc:
35
+ print("Failed to initialise Django:", exc, file=sys.stderr)
36
+ return 1
37
+
38
+ if {migrations}:
39
+ execute_from_command_line(["manage.py", "migrate", "--noinput"])
40
+
41
+ if {open_browser}:
42
+ _open_browser("http://{host}:{port}/")
43
+
44
+ execute_from_command_line(["manage.py", "runserver", "{host}:{port}", "--noreload"])
45
+ return 0
46
+
47
+
48
+ if __name__ == "__main__":
49
+ raise SystemExit(main())
50
+ '''
51
+
52
+
53
+ @dataclass
54
+ class RuntimeScript:
55
+ path: Path
56
+ host: str
57
+ port: int
58
+
59
+
60
+ def generate_launcher(manifest: BuildManifest, output_dir: Path) -> RuntimeScript:
61
+ data = manifest.to_dict()
62
+ project = data.get("project", {})
63
+ runtime = data.get("runtime", {})
64
+ script = LAUNCHER_TEMPLATE.format(
65
+ name=project.get("name", "app"),
66
+ settings=project.get("settings", "settings"),
67
+ host=runtime.get("host", "127.0.0.1"),
68
+ port=runtime.get("port", 8000),
69
+ open_browser=bool(runtime.get("open_browser", True)),
70
+ migrations=bool(runtime.get("migrations_on_startup", False)),
71
+ )
72
+ output_dir.mkdir(parents=True, exist_ok=True)
73
+ path = output_dir / "launcher.py"
74
+ path.write_text(script, encoding="utf-8")
75
+ return RuntimeScript(path=path, host=runtime.get("host", "127.0.0.1"), port=runtime.get("port", 8000))
@@ -0,0 +1,44 @@
1
+ """Artifact validation."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from dataclasses import dataclass, field
6
+
7
+ from django_native.packaging import PackageResult
8
+
9
+
10
+ @dataclass
11
+ class Check:
12
+ name: str
13
+ passed: bool
14
+ detail: str = ""
15
+
16
+
17
+ @dataclass
18
+ class ValidationReport:
19
+ checks: list[Check] = field(default_factory=list)
20
+
21
+ @property
22
+ def passed(self) -> bool:
23
+ return all(c.passed for c in self.checks)
24
+
25
+ def render(self) -> str:
26
+ lines = []
27
+ for c in self.checks:
28
+ marker = "[PASS]" if c.passed else "[FAIL]"
29
+ line = f" {marker} {c.name}"
30
+ if c.detail:
31
+ line += f" — {c.detail}"
32
+ lines.append(line)
33
+ status = "PASS" if self.passed else "FAIL"
34
+ return "\n".join(lines) + f"\n\nOverall: {status}"
35
+
36
+
37
+ def validate_package(result: PackageResult) -> ValidationReport:
38
+ report = ValidationReport()
39
+ report.checks.append(Check("Package root exists", result.root.is_dir()))
40
+ report.checks.append(Check("Package manifest present", result.manifest_path.is_file()))
41
+ report.checks.append(Check("Checksums present", result.checksums_path.is_file()))
42
+ report.checks.append(Check("Resources collected", (result.root / "resources").is_dir()))
43
+ report.checks.append(Check("Files enumerated", result.file_count > 0, f"{result.file_count} files"))
44
+ return report