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,6 @@
1
+ """Django Native — Build Django. Compile. Package. Distribute."""
2
+
3
+ from __future__ import annotations
4
+
5
+ __version__ = "0.2.0"
6
+ __all__ = ["__version__"]
@@ -0,0 +1,4 @@
1
+ from django_native.cli.app import main
2
+
3
+ if __name__ == "__main__":
4
+ main()
@@ -0,0 +1,106 @@
1
+ """Dependency and import analysis."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import ast
6
+ import importlib.util
7
+ import importlib.metadata as md
8
+ from dataclasses import dataclass, field
9
+ from pathlib import Path
10
+
11
+ from django_native.diagnostics import DiagnosticReport
12
+
13
+ _IGNORE_PARTS = {".venv", "venv", "__pycache__", "dist", "build", "node_modules", ".git", ".tox", ".mypy_cache"}
14
+
15
+
16
+ @dataclass
17
+ class Distribution:
18
+ name: str
19
+ version: str
20
+
21
+
22
+ @dataclass
23
+ class ImportRecord:
24
+ module: str
25
+ source: Path
26
+ line: int
27
+ dynamic: bool = False
28
+
29
+
30
+ @dataclass
31
+ class AnalysisReport:
32
+ distributions: list[Distribution] = field(default_factory=list)
33
+ imports: list[ImportRecord] = field(default_factory=list)
34
+ dynamic_imports: list[ImportRecord] = field(default_factory=list)
35
+ missing: list[str] = field(default_factory=list)
36
+ installed_apps: list[str] = field(default_factory=list)
37
+ diagnostics: DiagnosticReport = field(default_factory=DiagnosticReport)
38
+
39
+
40
+ def inventory_distributions() -> list[Distribution]:
41
+ out: list[Distribution] = []
42
+ for dist in md.distributions():
43
+ name = dist.metadata["Name"] if "Name" in dist.metadata else "unknown"
44
+ out.append(Distribution(name=name, version=dist.version))
45
+ return sorted(out, key=lambda d: d.name.lower())
46
+
47
+
48
+ def scan_imports(root: Path) -> AnalysisReport:
49
+ report = AnalysisReport()
50
+ for py_file in _iter_python(root):
51
+ try:
52
+ tree = ast.parse(py_file.read_text(encoding="utf-8"))
53
+ except (SyntaxError, UnicodeDecodeError):
54
+ report.diagnostics.warn("DN3001", f"Could not parse {py_file}")
55
+ continue
56
+ for node in ast.walk(tree):
57
+ if isinstance(node, ast.Import):
58
+ for alias in node.names:
59
+ report.imports.append(ImportRecord(alias.name, py_file, node.lineno))
60
+ elif isinstance(node, ast.ImportFrom) and node.module:
61
+ report.imports.append(ImportRecord(node.module, py_file, node.lineno))
62
+ elif isinstance(node, ast.Call):
63
+ fname = _call_name(node.func)
64
+ if fname in {"import_module", "__import__", "import_string"}:
65
+ arg = node.args[0] if node.args else None
66
+ if isinstance(arg, ast.Constant) and isinstance(arg.value, str):
67
+ report.dynamic_imports.append(
68
+ ImportRecord(arg.value, py_file, node.lineno, dynamic=True)
69
+ )
70
+ else:
71
+ report.diagnostics.warn(
72
+ "DN3002",
73
+ f"Dynamic import with non-literal argument in {py_file}:{node.lineno}",
74
+ )
75
+ return report
76
+
77
+
78
+ def _call_name(node: ast.AST) -> str | None:
79
+ if isinstance(node, ast.Name):
80
+ return node.id
81
+ if isinstance(node, ast.Attribute):
82
+ return node.attr
83
+ return None
84
+
85
+
86
+ def _iter_python(root: Path):
87
+ for path in root.rglob("*.py"):
88
+ if any(part in _IGNORE_PARTS for part in path.parts):
89
+ continue
90
+ yield path
91
+
92
+
93
+ def resolve_missing(report: AnalysisReport) -> None:
94
+ """Flag imports not resolvable in the current environment."""
95
+ seen: set[str] = set()
96
+ for record in report.imports:
97
+ top = record.module.split(".")[0]
98
+ if not top or top == "__future__" or top in seen:
99
+ continue
100
+ seen.add(top)
101
+ try:
102
+ spec = importlib.util.find_spec(top)
103
+ except (ImportError, ValueError):
104
+ spec = None
105
+ if spec is None:
106
+ report.missing.append(top)
@@ -0,0 +1,65 @@
1
+ """Django resource analysis — templates, static, migrations, translations."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from dataclasses import dataclass, field
6
+ from pathlib import Path
7
+
8
+ _IGNORE = {"__pycache__", ".venv", "venv", "node_modules", ".git", "dist", "build"}
9
+
10
+
11
+ @dataclass
12
+ class ResourceItem:
13
+ kind: str
14
+ path: Path
15
+ exists: bool = True
16
+
17
+
18
+ @dataclass
19
+ class ResourceReport:
20
+ templates: list[ResourceItem] = field(default_factory=list)
21
+ static: list[ResourceItem] = field(default_factory=list)
22
+ migrations: list[ResourceItem] = field(default_factory=list)
23
+ translations: list[ResourceItem] = field(default_factory=list)
24
+
25
+ def counts(self) -> dict[str, int]:
26
+ return {
27
+ "templates": len(self.templates),
28
+ "static": len(self.static),
29
+ "migrations": len(self.migrations),
30
+ "translations": len(self.translations),
31
+ }
32
+
33
+
34
+ def analyze_resources(project_root: Path) -> ResourceReport:
35
+ report = ResourceReport()
36
+ for templates_dir in _walk_dirs(project_root, "templates"):
37
+ for f in _files(templates_dir):
38
+ report.templates.append(ResourceItem("template", f))
39
+ for static_dir in _walk_dirs(project_root, "static"):
40
+ for f in _files(static_dir):
41
+ report.static.append(ResourceItem("static", f))
42
+ for mig_dir in _walk_dirs(project_root, "migrations"):
43
+ for f in _files(mig_dir, suffix=".py"):
44
+ report.migrations.append(ResourceItem("migration", f))
45
+ for loc_dir in _walk_dirs(project_root, "locale"):
46
+ for f in _files(loc_dir, suffixes={".po", ".mo"}):
47
+ report.translations.append(ResourceItem("translation", f))
48
+ return report
49
+
50
+
51
+ def _walk_dirs(root: Path, name: str):
52
+ for p in root.rglob(name):
53
+ if p.is_dir() and not any(part in _IGNORE for part in p.parts):
54
+ yield p
55
+
56
+
57
+ def _files(path: Path, suffix: str | None = None, suffixes: set[str] | None = None):
58
+ for f in path.rglob("*"):
59
+ if not f.is_file():
60
+ continue
61
+ if suffix and f.suffix != suffix:
62
+ continue
63
+ if suffixes and f.suffix not in suffixes:
64
+ continue
65
+ yield f
@@ -0,0 +1,163 @@
1
+ """Shared services — used by both CLI and Django management command."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from dataclasses import dataclass
6
+ from pathlib import Path
7
+
8
+ from django_native.analysis import inventory_distributions, resolve_missing, scan_imports
9
+ from django_native.analysis.resources import analyze_resources
10
+ from django_native.configuration import load_config
11
+ from django_native.diagnostics import DiagnosticReport, DjangoNativeError
12
+ from django_native.planning import build_manifest, write_manifest
13
+ from django_native.project import create_project, discover_project
14
+
15
+
16
+ @dataclass
17
+ class InitResult:
18
+ name: str
19
+ root: str
20
+ config_path: str
21
+
22
+
23
+ def init_project(name: str, directory: Path | None = None, force: bool = False) -> InitResult:
24
+ created = create_project(name, directory=directory, force=force)
25
+ return InitResult(name=created.name, root=str(created.root), config_path=str(created.config_path))
26
+
27
+
28
+ def _analyze(root: Path):
29
+ analysis = scan_imports(root)
30
+ analysis.distributions = inventory_distributions()
31
+ resolve_missing(analysis)
32
+ return analysis
33
+
34
+
35
+ @dataclass
36
+ class InspectResult:
37
+ project: dict
38
+ analysis: dict
39
+ resources: dict
40
+ diagnostics: list[str]
41
+
42
+
43
+ def inspect_project(root: Path | None = None) -> InspectResult:
44
+ project = discover_project(root)
45
+ cfg_path = project.root / "django-native.toml"
46
+ config = load_config(cfg_path) if cfg_path.exists() else load_config(Path("/nonexistent"))
47
+ analysis = _analyze(project.root)
48
+ analysis.installed_apps = project.apps
49
+ resources = analyze_resources(project.root)
50
+
51
+ return InspectResult(
52
+ project={
53
+ "name": config.project.name or project.root.name,
54
+ "root": str(project.root),
55
+ "settings": config.project.settings or project.settings_module,
56
+ "package": project.project_package,
57
+ "apps": project.apps,
58
+ "wsgi": project.wsgi_entry,
59
+ "asgi": project.asgi_entry,
60
+ "python": project.python_version,
61
+ "django": project.django_version,
62
+ },
63
+ analysis={
64
+ "distributions": len(analysis.distributions),
65
+ "imports": len(analysis.imports),
66
+ "dynamic_imports": [r.module for r in analysis.dynamic_imports],
67
+ "missing": analysis.missing,
68
+ },
69
+ resources=resources.counts(),
70
+ diagnostics=[d.render() for d in analysis.diagnostics.diagnostics],
71
+ )
72
+
73
+
74
+ @dataclass
75
+ class PlanResult:
76
+ manifest: dict
77
+ path: str | None
78
+
79
+
80
+ def _prepare_manifest(root: Path | None = None):
81
+ project = discover_project(root)
82
+ cfg_path = project.root / "django-native.toml"
83
+ config = load_config(cfg_path) if cfg_path.exists() else load_config(Path("/nonexistent"))
84
+ analysis = _analyze(project.root)
85
+ analysis.installed_apps = project.apps
86
+ resources = analyze_resources(project.root)
87
+ diag = DiagnosticReport()
88
+ for m in analysis.missing:
89
+ diag.warn("DN4001", f"Unresolved import: {m}")
90
+ manifest = build_manifest(project, config, analysis, resources, diag)
91
+ return project, config, analysis, resources, manifest, diag
92
+
93
+
94
+ def plan_project(root: Path | None = None, output: Path | None = None) -> PlanResult:
95
+ _, _, _, _, manifest, _ = _prepare_manifest(root)
96
+ path_str = None
97
+ if output:
98
+ write_manifest(manifest, output)
99
+ path_str = str(output)
100
+ return PlanResult(manifest=manifest.to_dict(), path=path_str)
101
+
102
+
103
+ @dataclass
104
+ class BuildResult:
105
+ ok: bool
106
+ output_dir: str | None
107
+ stderr: str = ""
108
+ duration_seconds: float = 0.0
109
+
110
+
111
+ def build_project(root: Path | None = None) -> BuildResult:
112
+ from django_native.backends import get_backend
113
+
114
+ project, config, _, _, manifest, _ = _prepare_manifest(root)
115
+ backend = get_backend(config.compiler.backend)
116
+ check = backend.check_environment()
117
+ if not check.ok:
118
+ return BuildResult(ok=False, output_dir=None, stderr="; ".join(check.messages))
119
+ result = backend.compile(manifest, project.root)
120
+ return BuildResult(
121
+ ok=result.ok,
122
+ output_dir=str(result.output_dir) if result.output_dir else None,
123
+ stderr=result.stderr,
124
+ duration_seconds=result.duration_seconds,
125
+ )
126
+
127
+
128
+ @dataclass
129
+ class PackageServiceResult:
130
+ ok: bool
131
+ root: str | None
132
+ archive: str | None
133
+ validation: dict
134
+
135
+
136
+ def package_project(root: Path | None = None) -> PackageServiceResult:
137
+ from django_native.packaging import assemble_package
138
+ from django_native.runtime import generate_launcher
139
+ from django_native.validation import validate_package
140
+
141
+ project, config, _, resources, manifest, _ = _prepare_manifest(root)
142
+ dist = project.root / config.build.output
143
+ dist.mkdir(parents=True, exist_ok=True)
144
+ generate_launcher(manifest, dist)
145
+ pkg = assemble_package(manifest, project.root, resources, dist)
146
+ report = validate_package(pkg)
147
+ return PackageServiceResult(
148
+ ok=report.passed,
149
+ root=str(pkg.root),
150
+ archive=str(pkg.archive) if pkg.archive else None,
151
+ validation={"passed": report.passed, "output": report.render()},
152
+ )
153
+
154
+
155
+ @dataclass
156
+ class TestResult:
157
+ ok: bool
158
+ output: str
159
+
160
+
161
+ def test_project(root: Path | None = None) -> TestResult:
162
+ result = package_project(root)
163
+ return TestResult(ok=result.ok, output=result.validation["output"])
@@ -0,0 +1,71 @@
1
+ """Compiler backend abstraction."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from abc import ABC, abstractmethod
6
+ from dataclasses import dataclass, field
7
+ from pathlib import Path
8
+
9
+ from django_native.planning import BuildManifest
10
+
11
+
12
+ @dataclass
13
+ class BackendCheckResult:
14
+ ok: bool
15
+ messages: list[str] = field(default_factory=list)
16
+
17
+
18
+ @dataclass
19
+ class CompileResult:
20
+ ok: bool
21
+ output_dir: Path | None = None
22
+ stdout: str = ""
23
+ stderr: str = ""
24
+ duration_seconds: float = 0.0
25
+
26
+
27
+ class CompilerBackend(ABC):
28
+ name: str = "abstract"
29
+
30
+ @abstractmethod
31
+ def check_environment(self) -> BackendCheckResult: ...
32
+ @abstractmethod
33
+ def get_version(self) -> str | None: ...
34
+ @abstractmethod
35
+ def compile(self, build_plan: BuildManifest, project_root: Path) -> CompileResult: ...
36
+
37
+
38
+ _REGISTRY: dict[str, type[CompilerBackend]] = {}
39
+
40
+
41
+ def register_backend(cls: type[CompilerBackend]) -> type[CompilerBackend]:
42
+ _REGISTRY[cls.name] = cls
43
+ return cls
44
+
45
+
46
+ def get_backend(name: str) -> CompilerBackend:
47
+ # Entry points first (third-party plugins), then built-ins.
48
+ try:
49
+ from importlib.metadata import entry_points
50
+ for ep in entry_points(group="django_native.backends"):
51
+ if ep.name == name:
52
+ return ep.load()()
53
+ except Exception:
54
+ pass
55
+ if name in _REGISTRY:
56
+ return _REGISTRY[name]()
57
+ from django_native.backends.nuitka import NuitkaBackend
58
+ if name == NuitkaBackend.name:
59
+ return NuitkaBackend()
60
+ raise ValueError(f"Unknown compiler backend: {name}")
61
+
62
+
63
+ def list_backends() -> list[str]:
64
+ names = set(_REGISTRY)
65
+ try:
66
+ from importlib.metadata import entry_points
67
+ for ep in entry_points(group="django_native.backends"):
68
+ names.add(ep.name)
69
+ except Exception:
70
+ pass
71
+ return sorted(names)
@@ -0,0 +1,87 @@
1
+ """Nuitka compiler backend."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import shutil
6
+ import subprocess
7
+ import time
8
+ from pathlib import Path
9
+
10
+ from django_native.backends import (
11
+ BackendCheckResult,
12
+ CompileResult,
13
+ CompilerBackend,
14
+ register_backend,
15
+ )
16
+ from django_native.planning import BuildManifest
17
+
18
+
19
+ @register_backend
20
+ class NuitkaBackend(CompilerBackend):
21
+ name = "nuitka"
22
+
23
+ def check_environment(self) -> BackendCheckResult:
24
+ messages: list[str] = []
25
+ ok = True
26
+ if shutil.which("nuitka") is None:
27
+ try:
28
+ import nuitka # noqa: F401
29
+ messages.append("Nuitka available as Python module.")
30
+ except ImportError:
31
+ ok = False
32
+ messages.append(
33
+ "Nuitka not installed. Run: pip install 'django-native[compile]'"
34
+ )
35
+ else:
36
+ messages.append("Nuitka executable found.")
37
+ if not any(shutil.which(c) for c in ("cc", "gcc", "clang", "cl")):
38
+ ok = False
39
+ messages.append("No C compiler (cc/gcc/clang/cl) detected.")
40
+ return BackendCheckResult(ok=ok, messages=messages)
41
+
42
+ def get_version(self) -> str | None:
43
+ try:
44
+ import nuitka # noqa: F401
45
+ return getattr(nuitka, "__version__", "unknown")
46
+ except ImportError:
47
+ return None
48
+
49
+ def compile(self, build_plan: BuildManifest, project_root: Path) -> CompileResult:
50
+ start = time.monotonic()
51
+ output_dir = (
52
+ project_root
53
+ / build_plan.to_dict().get("project", {}).get("name", "app")
54
+ / "build"
55
+ )
56
+ output_dir.mkdir(parents=True, exist_ok=True)
57
+ entry = project_root / "manage.py"
58
+ cmd = [
59
+ "nuitka",
60
+ "--standalone",
61
+ "--follow-imports",
62
+ f"--output-dir={output_dir}",
63
+ str(entry),
64
+ ]
65
+ try:
66
+ proc = subprocess.run(
67
+ cmd, capture_output=True, text=True, check=False, timeout=1800
68
+ )
69
+ except FileNotFoundError:
70
+ return CompileResult(
71
+ ok=False, output_dir=output_dir,
72
+ stderr="nuitka executable not found",
73
+ duration_seconds=time.monotonic() - start,
74
+ )
75
+ except subprocess.TimeoutExpired as exc:
76
+ return CompileResult(
77
+ ok=False, output_dir=output_dir,
78
+ stderr=f"Compilation timed out: {exc}",
79
+ duration_seconds=time.monotonic() - start,
80
+ )
81
+ return CompileResult(
82
+ ok=proc.returncode == 0,
83
+ output_dir=output_dir,
84
+ stdout=proc.stdout,
85
+ stderr=proc.stderr,
86
+ duration_seconds=time.monotonic() - start,
87
+ )
File without changes