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.
- django_native/__init__.py +6 -0
- django_native/__main__.py +4 -0
- django_native/analysis/__init__.py +106 -0
- django_native/analysis/resources.py +65 -0
- django_native/application/__init__.py +163 -0
- django_native/backends/__init__.py +71 -0
- django_native/backends/nuitka.py +87 -0
- django_native/cli/__init__.py +0 -0
- django_native/cli/app.py +202 -0
- django_native/configuration/__init__.py +193 -0
- django_native/diagnostics/__init__.py +71 -0
- django_native/django_app/__init__.py +1 -0
- django_native/django_app/apps.py +7 -0
- django_native/django_app/management/__init__.py +0 -0
- django_native/django_app/management/commands/__init__.py +0 -0
- django_native/django_app/management/commands/native.py +56 -0
- django_native/environments/__init__.py +54 -0
- django_native/packaging/__init__.py +103 -0
- django_native/planning/__init__.py +98 -0
- django_native/plugins/__init__.py +31 -0
- django_native/project/__init__.py +220 -0
- django_native/resources/__init__.py +0 -0
- django_native/runtime/__init__.py +75 -0
- django_native/validation/__init__.py +44 -0
- django_native-0.2.0.dist-info/METADATA +764 -0
- django_native-0.2.0.dist-info/RECORD +29 -0
- django_native-0.2.0.dist-info/WHEEL +4 -0
- django_native-0.2.0.dist-info/entry_points.txt +5 -0
- django_native-0.2.0.dist-info/licenses/LICENSE +0 -0
django_native/cli/app.py
ADDED
|
@@ -0,0 +1,202 @@
|
|
|
1
|
+
"""Command-line interface for Django Native."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import json
|
|
6
|
+
import shutil
|
|
7
|
+
import sys
|
|
8
|
+
from pathlib import Path
|
|
9
|
+
|
|
10
|
+
import click
|
|
11
|
+
|
|
12
|
+
from django_native import __version__
|
|
13
|
+
from django_native.application import (
|
|
14
|
+
build_project,
|
|
15
|
+
init_project,
|
|
16
|
+
inspect_project,
|
|
17
|
+
package_project,
|
|
18
|
+
plan_project,
|
|
19
|
+
test_project,
|
|
20
|
+
)
|
|
21
|
+
from django_native.backends import list_backends
|
|
22
|
+
from django_native.diagnostics import DjangoNativeError
|
|
23
|
+
from django_native.plugins import list_plugins
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
@click.group(context_settings={"help_option_names": ["-h", "--help"]})
|
|
27
|
+
@click.version_option(__version__, "-V", "--version", prog_name="django-native")
|
|
28
|
+
def main() -> None:
|
|
29
|
+
"""Build Django. Compile. Package. Distribute."""
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
@main.command()
|
|
33
|
+
@click.argument("name")
|
|
34
|
+
@click.option("--directory", type=click.Path(path_type=Path), default=None)
|
|
35
|
+
@click.option("--force", is_flag=True, help="Overwrite a non-empty target directory.")
|
|
36
|
+
def init(name: str, directory: Path | None, force: bool) -> None:
|
|
37
|
+
"""Create a new Django project."""
|
|
38
|
+
try:
|
|
39
|
+
result = init_project(name, directory=directory, force=force)
|
|
40
|
+
except DjangoNativeError as exc:
|
|
41
|
+
click.echo(f"error: {exc}", err=True)
|
|
42
|
+
sys.exit(1)
|
|
43
|
+
click.echo(f"Created {result.name} at {result.root}")
|
|
44
|
+
click.echo(f"Configuration: {result.config_path}")
|
|
45
|
+
click.echo(f"\nNext:\n cd {result.root}\n python manage.py runserver")
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
@main.command()
|
|
49
|
+
@click.option("--json", "as_json", is_flag=True)
|
|
50
|
+
def inspect(as_json: bool) -> None:
|
|
51
|
+
"""Inspect the current Django project."""
|
|
52
|
+
try:
|
|
53
|
+
result = inspect_project()
|
|
54
|
+
except DjangoNativeError as exc:
|
|
55
|
+
click.echo(f"error: {exc}", err=True)
|
|
56
|
+
sys.exit(1)
|
|
57
|
+
if as_json:
|
|
58
|
+
click.echo(json.dumps(
|
|
59
|
+
{"project": result.project, "analysis": result.analysis, "resources": result.resources},
|
|
60
|
+
indent=2,
|
|
61
|
+
))
|
|
62
|
+
return
|
|
63
|
+
click.echo("Django Native — Project Inspection\n")
|
|
64
|
+
click.echo(f"Project: {result.project['name']}")
|
|
65
|
+
click.echo(f"Settings: {result.project['settings']}")
|
|
66
|
+
click.echo(f"Python: {result.project['python']}")
|
|
67
|
+
if result.project.get("django"):
|
|
68
|
+
click.echo(f"Django: {result.project['django']}")
|
|
69
|
+
click.echo("\nApplications:")
|
|
70
|
+
for app in result.project["apps"]:
|
|
71
|
+
click.echo(f" {app}")
|
|
72
|
+
click.echo(f"\nResources: {result.resources}")
|
|
73
|
+
click.echo(
|
|
74
|
+
f"\nAnalysis: {result.analysis['distributions']} distributions, "
|
|
75
|
+
f"{result.analysis['imports']} imports"
|
|
76
|
+
)
|
|
77
|
+
if result.analysis["dynamic_imports"]:
|
|
78
|
+
click.echo(f"\nDynamic imports ({len(result.analysis['dynamic_imports'])}):")
|
|
79
|
+
for di in result.analysis["dynamic_imports"]:
|
|
80
|
+
click.echo(f" - {di}")
|
|
81
|
+
if result.diagnostics:
|
|
82
|
+
click.echo("\nDiagnostics:")
|
|
83
|
+
for d in result.diagnostics:
|
|
84
|
+
click.echo(f" {d}")
|
|
85
|
+
|
|
86
|
+
|
|
87
|
+
@main.command()
|
|
88
|
+
@click.option("--output", type=click.Path(path_type=Path), default=None)
|
|
89
|
+
@click.option("--json", "as_json", is_flag=True)
|
|
90
|
+
def plan(output: Path | None, as_json: bool) -> None:
|
|
91
|
+
"""Produce a build manifest without compiling."""
|
|
92
|
+
try:
|
|
93
|
+
result = plan_project(output=output)
|
|
94
|
+
except DjangoNativeError as exc:
|
|
95
|
+
click.echo(f"error: {exc}", err=True)
|
|
96
|
+
sys.exit(1)
|
|
97
|
+
if as_json:
|
|
98
|
+
click.echo(json.dumps(result.manifest, indent=2))
|
|
99
|
+
return
|
|
100
|
+
m = result.manifest
|
|
101
|
+
click.echo("Django Native — Build Plan\n")
|
|
102
|
+
click.echo(f"Project: {m['project']['name']}")
|
|
103
|
+
click.echo(f"Compiler: {m['compiler']['backend']} ({m['compiler']['mode']})")
|
|
104
|
+
click.echo(f"Platform: {m['environment']['platform']} / {m['environment']['architecture']}")
|
|
105
|
+
click.echo(f"Resources: {m['resources']['counts']}")
|
|
106
|
+
click.echo(f"Status: {m['status']}")
|
|
107
|
+
click.echo(f"Plan hash: {m['plan_hash']}")
|
|
108
|
+
if result.path:
|
|
109
|
+
click.echo(f"\nWrote manifest to {result.path}")
|
|
110
|
+
|
|
111
|
+
|
|
112
|
+
@main.command()
|
|
113
|
+
def build() -> None:
|
|
114
|
+
"""Compile the current project."""
|
|
115
|
+
result = build_project()
|
|
116
|
+
if result.ok:
|
|
117
|
+
click.echo(f"Build succeeded in {result.duration_seconds:.1f}s -> {result.output_dir}")
|
|
118
|
+
else:
|
|
119
|
+
click.echo(f"Build failed: {result.stderr}", err=True)
|
|
120
|
+
sys.exit(1)
|
|
121
|
+
|
|
122
|
+
|
|
123
|
+
@main.command()
|
|
124
|
+
def test() -> None:
|
|
125
|
+
"""Validate the packaged application."""
|
|
126
|
+
result = test_project()
|
|
127
|
+
click.echo(result.output)
|
|
128
|
+
if not result.ok:
|
|
129
|
+
sys.exit(1)
|
|
130
|
+
|
|
131
|
+
|
|
132
|
+
@main.command()
|
|
133
|
+
def package() -> None:
|
|
134
|
+
"""Package compiled output into a distributable artifact."""
|
|
135
|
+
result = package_project()
|
|
136
|
+
click.echo(result.validation["output"])
|
|
137
|
+
if result.ok:
|
|
138
|
+
click.echo(f"\nPackage: {result.root}")
|
|
139
|
+
if result.archive:
|
|
140
|
+
click.echo(f"Archive: {result.archive}")
|
|
141
|
+
else:
|
|
142
|
+
sys.exit(1)
|
|
143
|
+
|
|
144
|
+
|
|
145
|
+
@main.command()
|
|
146
|
+
def doctor() -> None:
|
|
147
|
+
"""Check the local environment."""
|
|
148
|
+
from django_native.environments import detect_environment
|
|
149
|
+
env = detect_environment()
|
|
150
|
+
click.echo("Django Native — Doctor\n")
|
|
151
|
+
click.echo(f"Python: {env.python_version} ({env.python_executable})")
|
|
152
|
+
click.echo(f"OS: {env.os_name} / {env.architecture}")
|
|
153
|
+
click.echo(f"C compiler: {env.c_compiler or 'not found'}")
|
|
154
|
+
click.echo(f"Nuitka: {env.nuitka_version or 'not installed'}")
|
|
155
|
+
click.echo(f"Django: {env.django_version or 'not installed'}")
|
|
156
|
+
if env.diagnostics:
|
|
157
|
+
click.echo("\nDiagnostics:")
|
|
158
|
+
for d in env.diagnostics:
|
|
159
|
+
click.echo(f" - {d}")
|
|
160
|
+
|
|
161
|
+
|
|
162
|
+
@main.command()
|
|
163
|
+
def config() -> None:
|
|
164
|
+
"""Show the effective configuration."""
|
|
165
|
+
from django_native.configuration import load_config
|
|
166
|
+
cfg = load_config()
|
|
167
|
+
click.echo(json.dumps(cfg.to_dict(), indent=2))
|
|
168
|
+
|
|
169
|
+
|
|
170
|
+
@main.group(name="backend")
|
|
171
|
+
def backend_group() -> None:
|
|
172
|
+
"""Compiler backend commands."""
|
|
173
|
+
|
|
174
|
+
|
|
175
|
+
@backend_group.command("list")
|
|
176
|
+
def backend_list() -> None:
|
|
177
|
+
for name in list_backends():
|
|
178
|
+
click.echo(name)
|
|
179
|
+
|
|
180
|
+
|
|
181
|
+
@main.group(name="plugin")
|
|
182
|
+
def plugin_group() -> None:
|
|
183
|
+
"""Plugin commands."""
|
|
184
|
+
|
|
185
|
+
|
|
186
|
+
@plugin_group.command("list")
|
|
187
|
+
def plugin_list() -> None:
|
|
188
|
+
for p in list_plugins():
|
|
189
|
+
click.echo(f"{p.group}:{p.name} -> {p.value}")
|
|
190
|
+
|
|
191
|
+
|
|
192
|
+
@main.command()
|
|
193
|
+
def clean() -> None:
|
|
194
|
+
"""Remove build artifacts."""
|
|
195
|
+
from django_native.configuration import load_config
|
|
196
|
+
cfg = load_config()
|
|
197
|
+
dist = Path.cwd() / cfg.build.output
|
|
198
|
+
if dist.exists():
|
|
199
|
+
shutil.rmtree(dist)
|
|
200
|
+
click.echo(f"Removed {dist}")
|
|
201
|
+
else:
|
|
202
|
+
click.echo("Nothing to clean.")
|
|
@@ -0,0 +1,193 @@
|
|
|
1
|
+
"""Configuration: TOML loading, schema validation, precedence."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import os
|
|
6
|
+
from dataclasses import dataclass, field, fields
|
|
7
|
+
from pathlib import Path
|
|
8
|
+
from typing import Any
|
|
9
|
+
|
|
10
|
+
try:
|
|
11
|
+
import tomllib # Python >= 3.11
|
|
12
|
+
except ImportError: # pragma: no cover
|
|
13
|
+
import tomli as tomllib # type: ignore[no-redef]
|
|
14
|
+
|
|
15
|
+
from django_native.diagnostics import DjangoNativeError
|
|
16
|
+
|
|
17
|
+
CONFIG_FILENAME = "django-native.toml"
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
@dataclass
|
|
21
|
+
class ProjectConfig:
|
|
22
|
+
name: str = ""
|
|
23
|
+
settings: str = ""
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
@dataclass
|
|
27
|
+
class CompilerConfig:
|
|
28
|
+
backend: str = "nuitka"
|
|
29
|
+
mode: str = "standalone"
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
@dataclass
|
|
33
|
+
class BuildConfig:
|
|
34
|
+
output: str = "dist"
|
|
35
|
+
clean: bool = True
|
|
36
|
+
jobs: int = 0
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
@dataclass
|
|
40
|
+
class TargetConfig:
|
|
41
|
+
platform: str = "native"
|
|
42
|
+
architecture: str = "native"
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
@dataclass
|
|
46
|
+
class ResourcesConfig:
|
|
47
|
+
collect_static: bool = True
|
|
48
|
+
include_templates: bool = True
|
|
49
|
+
include_migrations: bool = True
|
|
50
|
+
include_translations: bool = True
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
@dataclass
|
|
54
|
+
class RuntimeConfig:
|
|
55
|
+
profile: str = "local"
|
|
56
|
+
host: str = "127.0.0.1"
|
|
57
|
+
port: int = 8000
|
|
58
|
+
open_browser: bool = True
|
|
59
|
+
migrations_on_startup: bool = False
|
|
60
|
+
|
|
61
|
+
|
|
62
|
+
@dataclass
|
|
63
|
+
class DatabaseConfig:
|
|
64
|
+
strategy: str = "persistent"
|
|
65
|
+
|
|
66
|
+
|
|
67
|
+
@dataclass
|
|
68
|
+
class AnalysisConfig:
|
|
69
|
+
strict: bool = False
|
|
70
|
+
include_modules: list[str] = field(default_factory=list)
|
|
71
|
+
include_packages: list[str] = field(default_factory=list)
|
|
72
|
+
exclude_modules: list[str] = field(default_factory=list)
|
|
73
|
+
exclude_packages: list[str] = field(default_factory=list)
|
|
74
|
+
|
|
75
|
+
|
|
76
|
+
@dataclass
|
|
77
|
+
class Config:
|
|
78
|
+
project: ProjectConfig = field(default_factory=ProjectConfig)
|
|
79
|
+
compiler: CompilerConfig = field(default_factory=CompilerConfig)
|
|
80
|
+
build: BuildConfig = field(default_factory=BuildConfig)
|
|
81
|
+
target: TargetConfig = field(default_factory=TargetConfig)
|
|
82
|
+
resources: ResourcesConfig = field(default_factory=ResourcesConfig)
|
|
83
|
+
runtime: RuntimeConfig = field(default_factory=RuntimeConfig)
|
|
84
|
+
database: DatabaseConfig = field(default_factory=DatabaseConfig)
|
|
85
|
+
analysis: AnalysisConfig = field(default_factory=AnalysisConfig)
|
|
86
|
+
_source: Path | None = None
|
|
87
|
+
|
|
88
|
+
def to_dict(self) -> dict[str, Any]:
|
|
89
|
+
out: dict[str, Any] = {}
|
|
90
|
+
for f in fields(self):
|
|
91
|
+
if f.name.startswith("_"):
|
|
92
|
+
continue
|
|
93
|
+
value = getattr(self, f.name)
|
|
94
|
+
if hasattr(value, "__dataclass_fields__"):
|
|
95
|
+
out[f.name] = {k: v for k, v in vars(value).items()}
|
|
96
|
+
else:
|
|
97
|
+
out[f.name] = value
|
|
98
|
+
return out
|
|
99
|
+
|
|
100
|
+
|
|
101
|
+
_SECTION_MAP = {
|
|
102
|
+
"project": ProjectConfig,
|
|
103
|
+
"compiler": CompilerConfig,
|
|
104
|
+
"build": BuildConfig,
|
|
105
|
+
"target": TargetConfig,
|
|
106
|
+
"resources": ResourcesConfig,
|
|
107
|
+
"runtime": RuntimeConfig,
|
|
108
|
+
"database": DatabaseConfig,
|
|
109
|
+
"analysis": AnalysisConfig,
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
|
|
113
|
+
def _apply_section(target: Any, data: dict[str, Any]) -> None:
|
|
114
|
+
for key, value in data.items():
|
|
115
|
+
if hasattr(target, key):
|
|
116
|
+
setattr(target, key, value)
|
|
117
|
+
|
|
118
|
+
|
|
119
|
+
def find_config() -> Path | None:
|
|
120
|
+
for parent in [Path.cwd(), *Path.cwd().parents]:
|
|
121
|
+
candidate = parent / CONFIG_FILENAME
|
|
122
|
+
if candidate.exists():
|
|
123
|
+
return candidate
|
|
124
|
+
return None
|
|
125
|
+
|
|
126
|
+
|
|
127
|
+
def load_config(path: Path | None = None) -> Config:
|
|
128
|
+
"""Load config from TOML, apply env overrides, then validate."""
|
|
129
|
+
cfg = Config()
|
|
130
|
+
path = path if path is not None else find_config()
|
|
131
|
+
if path is not None and path.exists():
|
|
132
|
+
try:
|
|
133
|
+
with path.open("rb") as fh:
|
|
134
|
+
data = tomllib.load(fh)
|
|
135
|
+
except tomllib.TOMLDecodeError as exc:
|
|
136
|
+
raise DjangoNativeError(f"Invalid TOML in {path}: {exc}", code="DN1001") from exc
|
|
137
|
+
for name, cls in _SECTION_MAP.items():
|
|
138
|
+
if name == "analysis":
|
|
139
|
+
continue
|
|
140
|
+
_apply_section(getattr(cfg, name), data.get(name, {}))
|
|
141
|
+
analysis = data.get("analysis", {})
|
|
142
|
+
_apply_section(cfg.analysis, {k: v for k, v in analysis.items() if not isinstance(v, dict)})
|
|
143
|
+
if "include" in analysis:
|
|
144
|
+
cfg.analysis.include_modules = analysis["include"].get("modules", [])
|
|
145
|
+
cfg.analysis.include_packages = analysis["include"].get("packages", [])
|
|
146
|
+
if "exclude" in analysis:
|
|
147
|
+
cfg.analysis.exclude_modules = analysis["exclude"].get("modules", [])
|
|
148
|
+
cfg.analysis.exclude_packages = analysis["exclude"].get("packages", [])
|
|
149
|
+
cfg._source = path
|
|
150
|
+
|
|
151
|
+
_apply_env_overrides(cfg)
|
|
152
|
+
validate_config(cfg)
|
|
153
|
+
return cfg
|
|
154
|
+
|
|
155
|
+
|
|
156
|
+
def _apply_env_overrides(cfg: Config) -> None:
|
|
157
|
+
"""Environment override precedence: DJANGO_NATIVE_<SECTION>_<FIELD>=value."""
|
|
158
|
+
for env_key, env_value in os.environ.items():
|
|
159
|
+
if not env_key.startswith("DJANGO_NATIVE_"):
|
|
160
|
+
continue
|
|
161
|
+
parts = env_key[len("DJANGO_NATIVE_"):].lower().split("_", 1)
|
|
162
|
+
if len(parts) != 2:
|
|
163
|
+
continue
|
|
164
|
+
section_name, field_name = parts
|
|
165
|
+
if not hasattr(cfg, section_name):
|
|
166
|
+
continue
|
|
167
|
+
section = getattr(cfg, section_name)
|
|
168
|
+
if hasattr(section, field_name):
|
|
169
|
+
current = getattr(section, field_name)
|
|
170
|
+
try:
|
|
171
|
+
if isinstance(current, bool):
|
|
172
|
+
coerced: Any = env_value.lower() in ("1", "true", "yes", "on")
|
|
173
|
+
elif isinstance(current, int):
|
|
174
|
+
coerced = int(env_value)
|
|
175
|
+
else:
|
|
176
|
+
coerced = env_value
|
|
177
|
+
setattr(section, field_name, coerced)
|
|
178
|
+
except ValueError:
|
|
179
|
+
raise DjangoNativeError(
|
|
180
|
+
f"Invalid environment override {env_key}={env_value!r}",
|
|
181
|
+
code="DN1002",
|
|
182
|
+
) from None
|
|
183
|
+
|
|
184
|
+
|
|
185
|
+
def validate_config(cfg: Config) -> None:
|
|
186
|
+
if cfg.compiler.backend not in ("nuitka",):
|
|
187
|
+
raise DjangoNativeError(f"Unsupported backend: {cfg.compiler.backend}", code="DN1003")
|
|
188
|
+
if cfg.compiler.mode not in ("standalone", "onefile"):
|
|
189
|
+
raise DjangoNativeError(f"Unsupported compiler mode: {cfg.compiler.mode}", code="DN1004")
|
|
190
|
+
if cfg.runtime.profile not in ("local", "server", "portable"):
|
|
191
|
+
raise DjangoNativeError(f"Unsupported runtime profile: {cfg.runtime.profile}", code="DN1005")
|
|
192
|
+
if not (1 <= cfg.runtime.port <= 65535):
|
|
193
|
+
raise DjangoNativeError(f"Invalid port: {cfg.runtime.port}", code="DN1006")
|
|
@@ -0,0 +1,71 @@
|
|
|
1
|
+
"""Structured diagnostics, error codes and report rendering."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from dataclasses import dataclass, field
|
|
6
|
+
from enum import Enum
|
|
7
|
+
from typing import Any
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
class Severity(str, Enum):
|
|
11
|
+
INFO = "info"
|
|
12
|
+
WARNING = "warning"
|
|
13
|
+
ERROR = "error"
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
@dataclass(slots=True)
|
|
17
|
+
class Diagnostic:
|
|
18
|
+
severity: Severity
|
|
19
|
+
code: str
|
|
20
|
+
message: str
|
|
21
|
+
context: dict[str, Any] = field(default_factory=dict)
|
|
22
|
+
|
|
23
|
+
def render(self) -> str:
|
|
24
|
+
prefix = {
|
|
25
|
+
Severity.INFO: "[INFO] ",
|
|
26
|
+
Severity.WARNING: "[WARN] ",
|
|
27
|
+
Severity.ERROR: "[ERROR]",
|
|
28
|
+
}[self.severity]
|
|
29
|
+
return f"{prefix} {self.code}: {self.message}"
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
@dataclass
|
|
33
|
+
class DiagnosticReport:
|
|
34
|
+
diagnostics: list[Diagnostic] = field(default_factory=list)
|
|
35
|
+
|
|
36
|
+
def add(self, severity: Severity, code: str, message: str, **context: Any) -> None:
|
|
37
|
+
self.diagnostics.append(Diagnostic(severity, code, message, context))
|
|
38
|
+
|
|
39
|
+
def info(self, code: str, message: str, **context: Any) -> None:
|
|
40
|
+
self.add(Severity.INFO, code, message, **context)
|
|
41
|
+
|
|
42
|
+
def warn(self, code: str, message: str, **context: Any) -> None:
|
|
43
|
+
self.add(Severity.WARNING, code, message, **context)
|
|
44
|
+
|
|
45
|
+
def error(self, code: str, message: str, **context: Any) -> None:
|
|
46
|
+
self.add(Severity.ERROR, code, message, **context)
|
|
47
|
+
|
|
48
|
+
@property
|
|
49
|
+
def has_errors(self) -> bool:
|
|
50
|
+
return any(d.severity == Severity.ERROR for d in self.diagnostics)
|
|
51
|
+
|
|
52
|
+
@property
|
|
53
|
+
def has_warnings(self) -> bool:
|
|
54
|
+
return any(d.severity == Severity.WARNING for d in self.diagnostics)
|
|
55
|
+
|
|
56
|
+
def render(self) -> str:
|
|
57
|
+
if not self.diagnostics:
|
|
58
|
+
return "No diagnostics."
|
|
59
|
+
return "\n".join(d.render() for d in self.diagnostics)
|
|
60
|
+
|
|
61
|
+
|
|
62
|
+
class DjangoNativeError(Exception):
|
|
63
|
+
"""Base exception for all recoverable Django Native failures."""
|
|
64
|
+
|
|
65
|
+
def __init__(self, message: str, code: str = "DN0000") -> None:
|
|
66
|
+
super().__init__(message)
|
|
67
|
+
self.code = code
|
|
68
|
+
self.message = message
|
|
69
|
+
|
|
70
|
+
def __str__(self) -> str: # pragma: no cover
|
|
71
|
+
return f"{self.code}: {self.message}"
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
"""Django app exposing `python manage.py native <action>`."""
|
|
File without changes
|
|
File without changes
|
|
@@ -0,0 +1,56 @@
|
|
|
1
|
+
"""Django management command wrapping shared services."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import json
|
|
6
|
+
from pathlib import Path
|
|
7
|
+
|
|
8
|
+
from django.core.management.base import BaseCommand, CommandError
|
|
9
|
+
|
|
10
|
+
from django_native.application import (
|
|
11
|
+
build_project,
|
|
12
|
+
inspect_project,
|
|
13
|
+
package_project,
|
|
14
|
+
plan_project,
|
|
15
|
+
test_project,
|
|
16
|
+
)
|
|
17
|
+
from django_native.diagnostics import DjangoNativeError
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
class Command(BaseCommand):
|
|
21
|
+
help = "Run Django Native operations from within a Django project."
|
|
22
|
+
|
|
23
|
+
def add_arguments(self, parser):
|
|
24
|
+
parser.add_argument(
|
|
25
|
+
"action", choices=["inspect", "plan", "build", "test", "package"]
|
|
26
|
+
)
|
|
27
|
+
parser.add_argument("--output", type=Path, default=None)
|
|
28
|
+
|
|
29
|
+
def handle(self, *args, **options):
|
|
30
|
+
action = options["action"]
|
|
31
|
+
try:
|
|
32
|
+
if action == "inspect":
|
|
33
|
+
result = inspect_project()
|
|
34
|
+
self.stdout.write(json.dumps(
|
|
35
|
+
{"project": result.project, "analysis": result.analysis}, indent=2
|
|
36
|
+
))
|
|
37
|
+
elif action == "plan":
|
|
38
|
+
result = plan_project(output=options.get("output"))
|
|
39
|
+
self.stdout.write(json.dumps(result.manifest, indent=2))
|
|
40
|
+
elif action == "build":
|
|
41
|
+
result = build_project()
|
|
42
|
+
if not result.ok:
|
|
43
|
+
raise CommandError(result.stderr)
|
|
44
|
+
self.stdout.write(f"Build succeeded: {result.output_dir}")
|
|
45
|
+
elif action == "test":
|
|
46
|
+
result = test_project()
|
|
47
|
+
self.stdout.write(result.output)
|
|
48
|
+
if not result.ok:
|
|
49
|
+
raise CommandError("Validation failed")
|
|
50
|
+
elif action == "package":
|
|
51
|
+
result = package_project()
|
|
52
|
+
self.stdout.write(result.validation["output"])
|
|
53
|
+
if not result.ok:
|
|
54
|
+
raise CommandError("Packaging failed")
|
|
55
|
+
except DjangoNativeError as exc:
|
|
56
|
+
raise CommandError(f"{exc.code}: {exc.message}") from exc
|
|
@@ -0,0 +1,54 @@
|
|
|
1
|
+
"""Build environment detection."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import platform
|
|
6
|
+
import shutil
|
|
7
|
+
import sys
|
|
8
|
+
from dataclasses import dataclass, field
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
@dataclass
|
|
12
|
+
class BuildEnvironment:
|
|
13
|
+
python_version: str
|
|
14
|
+
python_executable: str
|
|
15
|
+
os_name: str
|
|
16
|
+
architecture: str
|
|
17
|
+
c_compiler: str | None = None
|
|
18
|
+
nuitka_version: str | None = None
|
|
19
|
+
django_version: str | None = None
|
|
20
|
+
diagnostics: list[str] = field(default_factory=list)
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
def detect_environment() -> BuildEnvironment:
|
|
24
|
+
env = BuildEnvironment(
|
|
25
|
+
python_version=".".join(map(str, sys.version_info[:3])),
|
|
26
|
+
python_executable=sys.executable,
|
|
27
|
+
os_name=platform.system().lower(),
|
|
28
|
+
architecture=platform.machine(),
|
|
29
|
+
)
|
|
30
|
+
for candidate in ("cc", "gcc", "clang", "cl"):
|
|
31
|
+
found = shutil.which(candidate)
|
|
32
|
+
if found:
|
|
33
|
+
env.c_compiler = found
|
|
34
|
+
break
|
|
35
|
+
if not env.c_compiler:
|
|
36
|
+
env.diagnostics.append(
|
|
37
|
+
"No C compiler found; Nuitka cannot build native binaries."
|
|
38
|
+
)
|
|
39
|
+
|
|
40
|
+
try:
|
|
41
|
+
import nuitka # noqa: F401
|
|
42
|
+
env.nuitka_version = getattr(nuitka, "__version__", "unknown")
|
|
43
|
+
except ImportError:
|
|
44
|
+
env.diagnostics.append(
|
|
45
|
+
"Nuitka not installed. Install with: pip install 'django-native[compile]'"
|
|
46
|
+
)
|
|
47
|
+
|
|
48
|
+
try:
|
|
49
|
+
import django # noqa: F401
|
|
50
|
+
env.django_version = django.get_version()
|
|
51
|
+
except ImportError:
|
|
52
|
+
env.diagnostics.append("Django not installed in the current environment.")
|
|
53
|
+
|
|
54
|
+
return env
|
|
@@ -0,0 +1,103 @@
|
|
|
1
|
+
"""Packaging pipeline: assemble compiled output + resources into artifacts."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import hashlib
|
|
6
|
+
import json
|
|
7
|
+
import shutil
|
|
8
|
+
import zipfile
|
|
9
|
+
from dataclasses import dataclass
|
|
10
|
+
from pathlib import Path
|
|
11
|
+
|
|
12
|
+
from django_native.analysis.resources import ResourceReport
|
|
13
|
+
from django_native.planning import BuildManifest
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
@dataclass
|
|
17
|
+
class PackageResult:
|
|
18
|
+
root: Path
|
|
19
|
+
manifest_path: Path
|
|
20
|
+
checksums_path: Path
|
|
21
|
+
file_count: int
|
|
22
|
+
archive: Path | None
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
def assemble_package(
|
|
26
|
+
manifest: BuildManifest,
|
|
27
|
+
project_root: Path,
|
|
28
|
+
resources: ResourceReport,
|
|
29
|
+
output_dir: Path,
|
|
30
|
+
*,
|
|
31
|
+
make_zip: bool = True,
|
|
32
|
+
) -> PackageResult:
|
|
33
|
+
data = manifest.to_dict()
|
|
34
|
+
name = data.get("project", {}).get("name", "app")
|
|
35
|
+
pkg_root = output_dir / name
|
|
36
|
+
if pkg_root.exists():
|
|
37
|
+
shutil.rmtree(pkg_root)
|
|
38
|
+
pkg_root.mkdir(parents=True)
|
|
39
|
+
|
|
40
|
+
# Resources
|
|
41
|
+
resource_root = pkg_root / "resources"
|
|
42
|
+
resource_root.mkdir()
|
|
43
|
+
for kind, items in (
|
|
44
|
+
("templates", resources.templates),
|
|
45
|
+
("static", resources.static),
|
|
46
|
+
("migrations", resources.migrations),
|
|
47
|
+
("translations", resources.translations),
|
|
48
|
+
):
|
|
49
|
+
dest = resource_root / kind
|
|
50
|
+
for item in items:
|
|
51
|
+
if not item.exists:
|
|
52
|
+
continue
|
|
53
|
+
try:
|
|
54
|
+
rel = item.path.relative_to(project_root)
|
|
55
|
+
except ValueError:
|
|
56
|
+
rel = Path(item.path.name)
|
|
57
|
+
target = dest / rel
|
|
58
|
+
target.parent.mkdir(parents=True, exist_ok=True)
|
|
59
|
+
try:
|
|
60
|
+
shutil.copy2(item.path, target)
|
|
61
|
+
except (FileNotFoundError, shutil.SameFileError):
|
|
62
|
+
pass
|
|
63
|
+
|
|
64
|
+
# Launcher (if generated in dist/)
|
|
65
|
+
launcher = project_root / "dist" / "launcher.py"
|
|
66
|
+
if launcher.exists():
|
|
67
|
+
shutil.copy2(launcher, pkg_root / "launcher.py")
|
|
68
|
+
|
|
69
|
+
# Package manifest
|
|
70
|
+
manifest_path = pkg_root / "package-manifest.json"
|
|
71
|
+
manifest_path.write_text(json.dumps(data, indent=2), encoding="utf-8")
|
|
72
|
+
|
|
73
|
+
# Checksums
|
|
74
|
+
lines = []
|
|
75
|
+
for f in sorted(pkg_root.rglob("*")):
|
|
76
|
+
if f.is_file() and f.name != "checksums.txt":
|
|
77
|
+
lines.append(f"{_sha256(f)} {f.relative_to(pkg_root)}")
|
|
78
|
+
checksums_path = pkg_root / "checksums.txt"
|
|
79
|
+
checksums_path.write_text("\n".join(lines) + "\n", encoding="utf-8")
|
|
80
|
+
|
|
81
|
+
archive = None
|
|
82
|
+
if make_zip:
|
|
83
|
+
archive = output_dir / f"{name}.zip"
|
|
84
|
+
with zipfile.ZipFile(archive, "w", zipfile.ZIP_DEFLATED) as zf:
|
|
85
|
+
for f in pkg_root.rglob("*"):
|
|
86
|
+
if f.is_file():
|
|
87
|
+
zf.write(f, f.relative_to(output_dir))
|
|
88
|
+
|
|
89
|
+
return PackageResult(
|
|
90
|
+
root=pkg_root,
|
|
91
|
+
manifest_path=manifest_path,
|
|
92
|
+
checksums_path=checksums_path,
|
|
93
|
+
file_count=len(lines),
|
|
94
|
+
archive=archive,
|
|
95
|
+
)
|
|
96
|
+
|
|
97
|
+
|
|
98
|
+
def _sha256(path: Path) -> str:
|
|
99
|
+
h = hashlib.sha256()
|
|
100
|
+
with path.open("rb") as fh:
|
|
101
|
+
for chunk in iter(lambda: fh.read(8192), b""):
|
|
102
|
+
h.update(chunk)
|
|
103
|
+
return h.hexdigest()
|