django-compose 0.1.0.dev1__py3-none-any.whl → 0.1.0.dev3__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_compose/artifacts.py +21 -12
- django_compose/build.py +12 -27
- django_compose/cli.py +23 -2
- django_compose/{addons.py → components.py} +141 -25
- django_compose/conf.py +39 -12
- django_compose/management/__init__.py +8 -1
- django_compose/management/commands/provision.py +26 -0
- django_compose/migration_imports.py +5 -9
- django_compose/migrations.py +237 -56
- django_compose/model_composition.py +50 -18
- django_compose/provision.py +349 -0
- django_compose/snapshot.py +1 -1
- django_compose/typing.py +125 -16
- django_compose/urls.py +31 -10
- django_compose-0.1.0.dev3.dist-info/METADATA +98 -0
- {django_compose-0.1.0.dev1.dist-info → django_compose-0.1.0.dev3.dist-info}/RECORD +21 -19
- django_compose-0.1.0.dev1.dist-info/METADATA +0 -101
- {django_compose-0.1.0.dev1.dist-info → django_compose-0.1.0.dev3.dist-info}/WHEEL +0 -0
- {django_compose-0.1.0.dev1.dist-info → django_compose-0.1.0.dev3.dist-info}/entry_points.txt +0 -0
- {django_compose-0.1.0.dev1.dist-info → django_compose-0.1.0.dev3.dist-info}/licenses/COPYING +0 -0
- {django_compose-0.1.0.dev1.dist-info → django_compose-0.1.0.dev3.dist-info}/licenses/LICENSE +0 -0
- {django_compose-0.1.0.dev1.dist-info → django_compose-0.1.0.dev3.dist-info}/licenses/NOTICE +0 -0
django_compose/artifacts.py
CHANGED
|
@@ -17,7 +17,13 @@ from django_compose.serving import Receipt, _validate_output_root, read_receipt
|
|
|
17
17
|
from django_compose.serving import receipt_lock as receipt_lock
|
|
18
18
|
|
|
19
19
|
|
|
20
|
-
def atomic_write(path: Path, content: bytes) -> None:
|
|
20
|
+
def atomic_write(path: Path, content: bytes, *, exclusive: bool = False, mode: int | None = None) -> None:
|
|
21
|
+
"""Publish complete bytes, preserving existing permissions unless specified.
|
|
22
|
+
|
|
23
|
+
Exclusive publication fails atomically if the destination already exists.
|
|
24
|
+
An explicit mode also restores permissions when recreating a deleted file.
|
|
25
|
+
New files use ordinary creation permissions filtered by the process umask.
|
|
26
|
+
"""
|
|
21
27
|
# Native loaders may otherwise accept same-second, same-size stale bytecode.
|
|
22
28
|
caches: tuple[Path, ...] = ()
|
|
23
29
|
if path.suffix == ".py" and "migrations" not in path.parts:
|
|
@@ -27,25 +33,28 @@ def atomic_write(path: Path, content: bytes) -> None:
|
|
|
27
33
|
caches = tuple(sorted(cache_dir.glob(f"{path.stem}.*.pyc")))
|
|
28
34
|
if any(cache.is_symlink() or not cache.is_file() for cache in caches):
|
|
29
35
|
raise ValueError(f"Unsafe generated bytecode cache for {path}")
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
36
|
+
if mode is None:
|
|
37
|
+
try:
|
|
38
|
+
mode = stat.S_IMODE(path.stat().st_mode)
|
|
39
|
+
except FileNotFoundError:
|
|
40
|
+
pass
|
|
34
41
|
path.parent.mkdir(parents=True, exist_ok=True)
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
42
|
+
# The private directory protects incomplete bytes while native exclusive
|
|
43
|
+
# creation applies the umask, without changing process-wide permissions.
|
|
44
|
+
with tempfile.TemporaryDirectory(prefix=".compose-", dir=path.parent) as directory:
|
|
45
|
+
temporary = Path(directory) / path.name
|
|
46
|
+
with temporary.open("xb") as stream:
|
|
38
47
|
stream.write(content)
|
|
39
48
|
stream.flush()
|
|
40
49
|
if mode is not None:
|
|
41
50
|
os.fchmod(stream.fileno(), mode)
|
|
42
51
|
os.fsync(stream.fileno())
|
|
43
|
-
|
|
52
|
+
if exclusive:
|
|
53
|
+
os.link(temporary, path)
|
|
54
|
+
else:
|
|
55
|
+
os.replace(temporary, path)
|
|
44
56
|
for cache in caches:
|
|
45
57
|
cache.unlink(missing_ok=True)
|
|
46
|
-
finally:
|
|
47
|
-
if os.path.exists(temporary):
|
|
48
|
-
os.unlink(temporary)
|
|
49
58
|
|
|
50
59
|
|
|
51
60
|
@dataclass
|
django_compose/build.py
CHANGED
|
@@ -23,10 +23,6 @@ from django_compose.serving import Receipt, read_receipt, verify
|
|
|
23
23
|
from django_compose.snapshot import Snapshot
|
|
24
24
|
|
|
25
25
|
|
|
26
|
-
def discover(configs: Iterable[AppConfig]) -> ModelComposition:
|
|
27
|
-
return ModelComposition.discover(tuple(configs))
|
|
28
|
-
|
|
29
|
-
|
|
30
26
|
@dataclass(frozen=True)
|
|
31
27
|
class ConcreteModels:
|
|
32
28
|
composition: ModelComposition
|
|
@@ -111,7 +107,7 @@ class BuildPlan:
|
|
|
111
107
|
progress=True, hashes=GeneratedTree(self.output_dir, self.sources).hashes()
|
|
112
108
|
)
|
|
113
109
|
atomic_write(self.output_dir / "__init__.py", receipt.source().encode())
|
|
114
|
-
self.composition = discover(self.configs)
|
|
110
|
+
self.composition = ModelComposition.discover(self.configs)
|
|
115
111
|
models = {model for config in self.configs for model in (config.models or {}).values()}
|
|
116
112
|
models.update(self.composition.ordered_models)
|
|
117
113
|
for source in self.composition.ordered_models:
|
|
@@ -162,26 +158,11 @@ class BuildPlan:
|
|
|
162
158
|
)
|
|
163
159
|
if effective == f"{self.output_module}.{label}.migrations" and not migration_init.exists():
|
|
164
160
|
self.sources[Path(label) / "migrations" / "__init__.py"] = ""
|
|
165
|
-
|
|
166
|
-
changed = [
|
|
167
|
-
p
|
|
168
|
-
for p, value in self.sources.items()
|
|
169
|
-
if not (self.output_dir / p).is_file()
|
|
170
|
-
or (self.output_dir / p).read_bytes() != GeneratedTree._bytes(value)
|
|
171
|
-
]
|
|
172
|
-
if changed:
|
|
173
|
-
raise ImproperlyConfigured(f"Generated models are stale: {changed}; run compose")
|
|
174
|
-
else:
|
|
175
|
-
GeneratedTree(self.output_dir, self.sources).reconcile(prune=False)
|
|
176
|
-
provisional = dict(self.previous.OWNED_FILES) if self.previous else {}
|
|
177
|
-
provisional.update(GeneratedTree(self.output_dir, self.sources).hashes())
|
|
178
|
-
atomic_write(
|
|
179
|
-
self.output_dir / "__init__.py",
|
|
180
|
-
self._receipt(progress=True, hashes=provisional).source().encode(),
|
|
181
|
-
)
|
|
161
|
+
self._publish_sources()
|
|
182
162
|
importlib.invalidate_caches()
|
|
183
163
|
for label in self.labels:
|
|
184
164
|
importlib.import_module(f"{self.output_module}.{label}.models")
|
|
165
|
+
self.composition.validate_generated(apps, declarations)
|
|
185
166
|
return self
|
|
186
167
|
except BaseException:
|
|
187
168
|
self.close()
|
|
@@ -213,8 +194,15 @@ class BuildPlan:
|
|
|
213
194
|
if not isinstance(content, bytes):
|
|
214
195
|
raise ImproperlyConfigured(f"ArtifactHook must render bytes: {path}")
|
|
215
196
|
self.sources[path] = content
|
|
197
|
+
tree = self._publish_sources()
|
|
198
|
+
serving._publish_build_artifacts(
|
|
199
|
+
self.close, self.output_dir, self._receipt(progress=True, hashes=tree.hashes())
|
|
200
|
+
)
|
|
201
|
+
|
|
202
|
+
def _publish_sources(self) -> GeneratedTree:
|
|
203
|
+
"""Validate before claiming paths, then record ownership before any write."""
|
|
216
204
|
tree = GeneratedTree(self.output_dir, self.sources)
|
|
217
|
-
tree._validate()
|
|
205
|
+
current = tree._validate()
|
|
218
206
|
if self.mode == "check":
|
|
219
207
|
if any(
|
|
220
208
|
not (self.output_dir / path).is_file()
|
|
@@ -223,7 +211,6 @@ class BuildPlan:
|
|
|
223
211
|
):
|
|
224
212
|
raise ImproperlyConfigured("Generated artifacts are stale; run compose")
|
|
225
213
|
else:
|
|
226
|
-
current = read_receipt(self.output_dir)
|
|
227
214
|
provisional = dict(current.OWNED_FILES) if current else {}
|
|
228
215
|
provisional.update(tree.hashes())
|
|
229
216
|
atomic_write(
|
|
@@ -231,9 +218,7 @@ class BuildPlan:
|
|
|
231
218
|
self._receipt(progress=True, hashes=provisional).source().encode(),
|
|
232
219
|
)
|
|
233
220
|
tree.reconcile(prune=False)
|
|
234
|
-
|
|
235
|
-
self.close, self.output_dir, self._receipt(progress=True, hashes=tree.hashes())
|
|
236
|
-
)
|
|
221
|
+
return tree
|
|
237
222
|
|
|
238
223
|
def finalize(self) -> Receipt:
|
|
239
224
|
try:
|
django_compose/cli.py
CHANGED
|
@@ -1,12 +1,33 @@
|
|
|
1
|
-
"""
|
|
1
|
+
"""Settings-free app inspection and the native management entrypoint."""
|
|
2
2
|
|
|
3
3
|
from __future__ import annotations
|
|
4
4
|
|
|
5
|
+
import argparse
|
|
6
|
+
import json
|
|
5
7
|
import sys
|
|
6
8
|
|
|
9
|
+
from django.core.exceptions import ImproperlyConfigured
|
|
10
|
+
|
|
7
11
|
|
|
8
12
|
def main(argv: list[str] | None = None) -> int:
|
|
13
|
+
arguments = sys.argv[1:] if argv is None else argv
|
|
14
|
+
if arguments and arguments[0] == "inspect-apps":
|
|
15
|
+
from django_compose.components import inspect_apps
|
|
16
|
+
|
|
17
|
+
parser = argparse.ArgumentParser(prog="django-compose inspect-apps")
|
|
18
|
+
parser.add_argument("--group", help="Installed component entry-point group")
|
|
19
|
+
parser.add_argument("--timeout", type=float, default=30.0, metavar="SECONDS")
|
|
20
|
+
parser.add_argument("roots", nargs="*", help="Native app or AppConfig entries")
|
|
21
|
+
options = parser.parse_args(arguments[1:])
|
|
22
|
+
try:
|
|
23
|
+
result = inspect_apps(options.roots, group=options.group, timeout=options.timeout)
|
|
24
|
+
except ImproperlyConfigured as error:
|
|
25
|
+
print(str(error), file=sys.stderr)
|
|
26
|
+
return 1
|
|
27
|
+
print(json.dumps(result, sort_keys=True))
|
|
28
|
+
return 0
|
|
29
|
+
|
|
9
30
|
from django_compose.management import execute
|
|
10
31
|
|
|
11
|
-
execute(["django-compose", *
|
|
32
|
+
execute(["django-compose", *arguments])
|
|
12
33
|
return 0
|
|
@@ -1,12 +1,18 @@
|
|
|
1
|
-
"""
|
|
1
|
+
"""Index native component metadata and resolve ordered selections of Django apps."""
|
|
2
2
|
|
|
3
3
|
from __future__ import annotations
|
|
4
4
|
|
|
5
|
-
|
|
6
|
-
|
|
5
|
+
import json
|
|
6
|
+
import math
|
|
7
|
+
import os
|
|
8
|
+
import subprocess
|
|
9
|
+
import sys
|
|
10
|
+
from collections.abc import Iterable, Iterator, Mapping
|
|
11
|
+
from dataclasses import asdict, dataclass, field
|
|
7
12
|
from graphlib import CycleError, TopologicalSorter
|
|
8
13
|
from importlib import metadata
|
|
9
14
|
from types import MappingProxyType
|
|
15
|
+
from typing import TypedDict, cast
|
|
10
16
|
|
|
11
17
|
from django.apps import AppConfig
|
|
12
18
|
from django.core.exceptions import ImproperlyConfigured
|
|
@@ -23,7 +29,7 @@ class Closure:
|
|
|
23
29
|
App_entries captures native config identities in dependency order; entries
|
|
24
30
|
projects their compatible INSTALLED_APPS strings. Roots preserve the
|
|
25
31
|
project's authored order; required contains only dependency-selected apps.
|
|
26
|
-
|
|
32
|
+
Components maps canonical distribution names to selected native app names.
|
|
27
33
|
Dependencies maps selected native app names to their direct dependencies,
|
|
28
34
|
also native app names, independent of the selected config entry strings.
|
|
29
35
|
App_configs retains the same selected native instances for app-owned behavior;
|
|
@@ -33,7 +39,7 @@ class Closure:
|
|
|
33
39
|
app_entries: tuple[Entry, ...]
|
|
34
40
|
roots: tuple[str, ...]
|
|
35
41
|
required: frozenset[str]
|
|
36
|
-
|
|
42
|
+
components: Mapping[str, str]
|
|
37
43
|
dependencies: Mapping[str, tuple[str, ...]]
|
|
38
44
|
app_configs: tuple[AppConfig, ...] = field(compare=False, repr=False)
|
|
39
45
|
|
|
@@ -43,8 +49,99 @@ class Closure:
|
|
|
43
49
|
return tuple(entry.entry for entry in self.app_entries)
|
|
44
50
|
|
|
45
51
|
|
|
52
|
+
class AppSelection(TypedDict):
|
|
53
|
+
"""Detached JSON facts from a resolved Closure, without native app instances."""
|
|
54
|
+
|
|
55
|
+
app_entries: list[dict[str, str]]
|
|
56
|
+
roots: list[str]
|
|
57
|
+
required: list[str]
|
|
58
|
+
components: dict[str, str]
|
|
59
|
+
dependencies: dict[str, list[str]]
|
|
60
|
+
|
|
61
|
+
|
|
62
|
+
def inspect_apps(roots: Iterable[str], *, group: str | None = None, timeout: float = 30.0) -> AppSelection:
|
|
63
|
+
"""Resolve apps in a fresh interpreter without activating them in this process.
|
|
64
|
+
|
|
65
|
+
The child uses enabled_apps and ordinary pre-setup AppConfig imports. It
|
|
66
|
+
inherits this interpreter's import paths, but not Django settings or compose
|
|
67
|
+
mode selectors, and writes no bytecode. It performs no setup, model loading,
|
|
68
|
+
settings contributions, composition or database work. Native app/config
|
|
69
|
+
modules must remain safe to import before Django setup.
|
|
70
|
+
|
|
71
|
+
Identity dictionaries retain Entry's name, label, config, path and entry
|
|
72
|
+
fields in dependency order. Roots retain authored order; required contains
|
|
73
|
+
sorted native app names; components maps canonical distribution names to apps.
|
|
74
|
+
Selection, interpreter launch and timeout failures raise ImproperlyConfigured.
|
|
75
|
+
Timeout is a positive finite number of seconds (default 30).
|
|
76
|
+
"""
|
|
77
|
+
if (
|
|
78
|
+
isinstance(timeout, bool)
|
|
79
|
+
or not isinstance(timeout, (int, float))
|
|
80
|
+
or not math.isfinite(timeout)
|
|
81
|
+
or timeout <= 0
|
|
82
|
+
):
|
|
83
|
+
raise ImproperlyConfigured("App inspection timeout must be a positive finite number of seconds")
|
|
84
|
+
request = {"roots": list(roots), "group": group, "pythonpath": sys.path}
|
|
85
|
+
environment = {
|
|
86
|
+
key: value
|
|
87
|
+
for key, value in os.environ.items()
|
|
88
|
+
if key not in {"DJANGO_SETTINGS_MODULE", "DJANGO_COMPOSE_MODE"}
|
|
89
|
+
}
|
|
90
|
+
child = """import json
|
|
91
|
+
import os
|
|
92
|
+
import sys
|
|
93
|
+
from contextlib import redirect_stdout
|
|
94
|
+
response = os.fdopen(os.dup(1), 'w')
|
|
95
|
+
os.dup2(2, 1)
|
|
96
|
+
try:
|
|
97
|
+
request = json.load(sys.stdin)
|
|
98
|
+
sys.path[:] = request.pop('pythonpath')
|
|
99
|
+
with redirect_stdout(sys.stderr):
|
|
100
|
+
from django_compose.components import _inspect_apps
|
|
101
|
+
result = _inspect_apps(**request)
|
|
102
|
+
except Exception as error:
|
|
103
|
+
print(str(error), file=sys.stderr)
|
|
104
|
+
raise SystemExit(1)
|
|
105
|
+
with response:
|
|
106
|
+
print(json.dumps(result, sort_keys=True), file=response)
|
|
107
|
+
"""
|
|
108
|
+
try:
|
|
109
|
+
result = subprocess.run(
|
|
110
|
+
[sys.executable, "-B", "-c", child],
|
|
111
|
+
input=json.dumps(request),
|
|
112
|
+
env=environment,
|
|
113
|
+
capture_output=True,
|
|
114
|
+
text=True,
|
|
115
|
+
check=False,
|
|
116
|
+
timeout=timeout,
|
|
117
|
+
)
|
|
118
|
+
except subprocess.TimeoutExpired as error:
|
|
119
|
+
raise ImproperlyConfigured(f"App inspection timed out after {timeout} seconds") from error
|
|
120
|
+
except OSError as error:
|
|
121
|
+
raise ImproperlyConfigured(f"Could not launch app inspection interpreter: {error}") from error
|
|
122
|
+
if result.returncode:
|
|
123
|
+
raise ImproperlyConfigured(result.stderr.strip() or "App selection subprocess failed")
|
|
124
|
+
if result.stderr:
|
|
125
|
+
print(result.stderr, end="", file=sys.stderr)
|
|
126
|
+
try:
|
|
127
|
+
return cast(AppSelection, json.loads(result.stdout))
|
|
128
|
+
except json.JSONDecodeError as error:
|
|
129
|
+
raise ImproperlyConfigured("App selection subprocess returned an invalid JSON response") from error
|
|
130
|
+
|
|
131
|
+
|
|
132
|
+
def _inspect_apps(roots: Iterable[str], *, group: str | None = None) -> AppSelection:
|
|
133
|
+
closure = enabled_apps(roots, group=group)
|
|
134
|
+
return {
|
|
135
|
+
"app_entries": [asdict(entry) for entry in closure.app_entries],
|
|
136
|
+
"roots": list(closure.roots),
|
|
137
|
+
"required": sorted(closure.required),
|
|
138
|
+
"components": dict(closure.components),
|
|
139
|
+
"dependencies": {name: list(dependencies) for name, dependencies in closure.dependencies.items()},
|
|
140
|
+
}
|
|
141
|
+
|
|
142
|
+
|
|
46
143
|
@dataclass(frozen=True)
|
|
47
|
-
class
|
|
144
|
+
class InstalledComponents:
|
|
48
145
|
"""Read-only native metadata, indexed without importing apps or loading points.
|
|
49
146
|
|
|
50
147
|
Distributions and entry_points use canonical distribution names as keys.
|
|
@@ -81,23 +178,29 @@ def active_requirements(requirements: Iterable[str]) -> tuple[Requirement, ...]:
|
|
|
81
178
|
)
|
|
82
179
|
|
|
83
180
|
|
|
84
|
-
def
|
|
85
|
-
"""Index
|
|
181
|
+
def index_components(distributions: Iterable[metadata.Distribution], *, group: str) -> InstalledComponents:
|
|
182
|
+
"""Index supplied native metadata without discovering or importing apps.
|
|
86
183
|
|
|
87
184
|
Each participating distribution must declare exactly one group entry point.
|
|
88
185
|
Its value remains a native app/config string, never a loaded entry point.
|
|
89
|
-
|
|
186
|
+
Canonical distribution names must be unique, including library-only inputs.
|
|
187
|
+
Containers are immutable and sorted by distribution name; values retain
|
|
188
|
+
their supplied native Distribution and EntryPoint APIs. Indexing neither
|
|
189
|
+
validates app paths nor resolves requirements.
|
|
90
190
|
"""
|
|
91
191
|
if not isinstance(group, str) or not group:
|
|
92
|
-
raise ImproperlyConfigured("An explicit non-empty
|
|
93
|
-
|
|
192
|
+
raise ImproperlyConfigured("An explicit non-empty component entry-point group is required")
|
|
193
|
+
indexed: dict[str, metadata.Distribution] = {}
|
|
194
|
+
for distribution in distributions:
|
|
195
|
+
name: str = canonicalize_name(distribution.metadata["Name"])
|
|
196
|
+
if name in indexed:
|
|
197
|
+
raise ImproperlyConfigured(f"Duplicate component distribution name {name!r}")
|
|
198
|
+
indexed[name] = distribution
|
|
199
|
+
indexed = dict(sorted(indexed.items()))
|
|
94
200
|
points: dict[str, metadata.EntryPoint] = {}
|
|
95
201
|
app_providers: dict[str, str] = {}
|
|
96
|
-
|
|
97
|
-
for name in sorted(names):
|
|
98
|
-
distribution = metadata.distribution(name)
|
|
202
|
+
for name, distribution in indexed.items():
|
|
99
203
|
entries = distribution.entry_points.select(group=group)
|
|
100
|
-
distributions[name] = distribution
|
|
101
204
|
if not entries:
|
|
102
205
|
continue
|
|
103
206
|
if len(entries) != 1:
|
|
@@ -109,25 +212,36 @@ def installed_addons(group: str) -> InstalledAddons:
|
|
|
109
212
|
)
|
|
110
213
|
app_providers[point.name] = name
|
|
111
214
|
points[name] = point
|
|
112
|
-
return
|
|
113
|
-
MappingProxyType(
|
|
215
|
+
return InstalledComponents(
|
|
216
|
+
MappingProxyType(indexed), MappingProxyType(points), MappingProxyType(app_providers)
|
|
114
217
|
)
|
|
115
218
|
|
|
116
219
|
|
|
220
|
+
def installed_components(group: str) -> InstalledComponents:
|
|
221
|
+
"""Index installed metadata using native same-name installation precedence."""
|
|
222
|
+
|
|
223
|
+
def distributions() -> Iterator[metadata.Distribution]:
|
|
224
|
+
names = {canonicalize_name(dist.metadata["Name"]) for dist in metadata.distributions()}
|
|
225
|
+
for name in sorted(names):
|
|
226
|
+
yield metadata.distribution(name)
|
|
227
|
+
|
|
228
|
+
return index_components(distributions(), group=group)
|
|
229
|
+
|
|
230
|
+
|
|
117
231
|
def enabled_apps(roots: Iterable[str], *, group: str | None = None) -> Closure:
|
|
118
232
|
"""Expand explicit roots using installed providers and selected requires_apps.
|
|
119
233
|
|
|
120
234
|
Settings are never read. Without a group, only native requires_apps edges
|
|
121
235
|
apply and distribution metadata is not inspected. Its entry-point keys are
|
|
122
236
|
native app names and values are native INSTALLED_APPS strings, never loaded
|
|
123
|
-
entry-point objects.
|
|
237
|
+
entry-point objects. A component's active Requires-Dist edges (extra='') activate
|
|
124
238
|
only distributions in this group. Ordinary roots have no metadata expansion.
|
|
125
|
-
Installation alone never activates
|
|
239
|
+
Installation alone never activates a component or an optional extra.
|
|
126
240
|
|
|
127
241
|
Root configs are preselected and override dependency/default config choices.
|
|
128
242
|
Conflicting dependency configs, duplicate native labels and cycles fail.
|
|
129
243
|
"""
|
|
130
|
-
installed =
|
|
244
|
+
installed = installed_components(group) if group is not None else None
|
|
131
245
|
root_entries = tuple(roots)
|
|
132
246
|
if any(not isinstance(entry, str) for entry in root_entries):
|
|
133
247
|
raise ImproperlyConfigured("Root INSTALLED_APPS entries must be native app strings")
|
|
@@ -139,7 +253,7 @@ def enabled_apps(roots: Iterable[str], *, group: str | None = None) -> Closure:
|
|
|
139
253
|
by_app = installed.providers if installed is not None else {}
|
|
140
254
|
graph: dict[str, tuple[str, ...]] = {}
|
|
141
255
|
|
|
142
|
-
def
|
|
256
|
+
def component_entry(provider: str) -> str:
|
|
143
257
|
assert installed is not None
|
|
144
258
|
point = installed.entry_points[provider]
|
|
145
259
|
config = AppConfig.create(point.value)
|
|
@@ -171,16 +285,16 @@ def enabled_apps(roots: Iterable[str], *, group: str | None = None) -> Closure:
|
|
|
171
285
|
dependencies = list(required_apps)
|
|
172
286
|
provider = by_app.get(name)
|
|
173
287
|
if provider is not None:
|
|
174
|
-
|
|
288
|
+
component_entry(provider)
|
|
175
289
|
assert installed is not None
|
|
176
290
|
for parsed in installed.active_requirements(provider):
|
|
177
291
|
dependency = canonicalize_name(parsed.name)
|
|
178
292
|
if dependency not in installed.distributions:
|
|
179
293
|
raise ImproperlyConfigured(
|
|
180
|
-
f"
|
|
294
|
+
f"Component {name!r} requires missing installed distribution {parsed.name!r}"
|
|
181
295
|
)
|
|
182
296
|
if dependency in installed.entry_points:
|
|
183
|
-
dependencies.append(
|
|
297
|
+
dependencies.append(component_entry(dependency))
|
|
184
298
|
if any(not isinstance(entry, str) for entry in dependencies):
|
|
185
299
|
raise ImproperlyConfigured(f"{name}.requires_apps entries must be native app strings")
|
|
186
300
|
graph[name] = tuple(sorted({choose(entry) for entry in sorted(dependencies)}))
|
|
@@ -199,7 +313,9 @@ def enabled_apps(roots: Iterable[str], *, group: str | None = None) -> Closure:
|
|
|
199
313
|
entries,
|
|
200
314
|
root_names,
|
|
201
315
|
frozenset(ordered) - root_set,
|
|
202
|
-
|
|
316
|
+
MappingProxyType(
|
|
317
|
+
{by_app[name]: name for name in sorted(set(ordered).intersection(by_app), key=by_app.__getitem__)}
|
|
318
|
+
),
|
|
203
319
|
MappingProxyType(graph),
|
|
204
320
|
app_configs=configs,
|
|
205
321
|
)
|
django_compose/conf.py
CHANGED
|
@@ -4,7 +4,8 @@ from __future__ import annotations
|
|
|
4
4
|
|
|
5
5
|
import logging
|
|
6
6
|
import os
|
|
7
|
-
from collections.abc import Mapping, MutableMapping
|
|
7
|
+
from collections.abc import Iterator, Mapping, MutableMapping
|
|
8
|
+
from contextlib import contextmanager
|
|
8
9
|
from importlib import import_module
|
|
9
10
|
from pathlib import Path
|
|
10
11
|
from types import MappingProxyType, ModuleType
|
|
@@ -15,8 +16,8 @@ from django.core.exceptions import ImproperlyConfigured
|
|
|
15
16
|
from django.utils.module_loading import module_has_submodule
|
|
16
17
|
|
|
17
18
|
from django_compose import serving
|
|
18
|
-
from django_compose.addons import Closure, enabled_apps
|
|
19
19
|
from django_compose.autoreload import report_inputs, report_watch_paths
|
|
20
|
+
from django_compose.components import Closure, enabled_apps
|
|
20
21
|
from django_compose.snapshot import Entry, mode, snapshot, structural_settings
|
|
21
22
|
|
|
22
23
|
_DERIVED = frozenset({"COMPOSE_ROOTS", "COMPOSE_SNAPSHOT", "COMPOSE_CLOSURE"})
|
|
@@ -60,8 +61,8 @@ def expand_attribute_refs(attributes: MutableMapping[str, Any]) -> None:
|
|
|
60
61
|
from both value and history, those references cannot be recovered from an
|
|
61
62
|
already-expanded cache. Preserve them here before expansion so configure can
|
|
62
63
|
validate structural inputs against direct and transitive environment sources.
|
|
63
|
-
Upstream logged errors retain their native behavior;
|
|
64
|
-
|
|
64
|
+
Upstream logged errors retain their native behavior; strict loaders wrap
|
|
65
|
+
native operations in fail_on_yamlconf_errors, as contribution application does.
|
|
65
66
|
"""
|
|
66
67
|
expanded = _copy_settings(attributes)
|
|
67
68
|
django_yamlconf.expand_attribute_refs(expanded)
|
|
@@ -74,6 +75,33 @@ class _Errors(logging.Handler):
|
|
|
74
75
|
raise ImproperlyConfigured(record.getMessage())
|
|
75
76
|
|
|
76
77
|
|
|
78
|
+
@contextmanager
|
|
79
|
+
def fail_on_yamlconf_errors() -> Iterator[None]:
|
|
80
|
+
"""Raise ImproperlyConfigured for django-yamlconf ERROR records in this scope.
|
|
81
|
+
|
|
82
|
+
Wrap native loading, expansion and injection operations. Enable this logger
|
|
83
|
+
and admit ERROR records for the scope, restoring its level and disabled
|
|
84
|
+
state on exit. Lower-level records retain their prior admission behavior.
|
|
85
|
+
Refuse process-wide logging.disable settings that suppress ERROR rather
|
|
86
|
+
than change logging for unrelated loggers.
|
|
87
|
+
"""
|
|
88
|
+
handler = _Errors(logging.ERROR)
|
|
89
|
+
logger = logging.getLogger("django_yamlconf")
|
|
90
|
+
if logger.manager.disable >= logging.ERROR:
|
|
91
|
+
raise ImproperlyConfigured("Cannot enforce yamlconf errors while logging.disable suppresses ERROR")
|
|
92
|
+
previous_level, previous_disabled = logger.level, logger.disabled
|
|
93
|
+
level = logging.ERROR if previous_disabled else min(logger.getEffectiveLevel(), logging.ERROR)
|
|
94
|
+
logger.setLevel(level)
|
|
95
|
+
logger.disabled = False
|
|
96
|
+
logger.addHandler(handler)
|
|
97
|
+
try:
|
|
98
|
+
yield
|
|
99
|
+
finally:
|
|
100
|
+
logger.removeHandler(handler)
|
|
101
|
+
logger.setLevel(previous_level)
|
|
102
|
+
logger.disabled = previous_disabled
|
|
103
|
+
|
|
104
|
+
|
|
77
105
|
class _Reference:
|
|
78
106
|
"""Observe native format field use without parsing its grammar."""
|
|
79
107
|
|
|
@@ -155,10 +183,7 @@ class _Contributions:
|
|
|
155
183
|
def apply(self, values: Mapping[str, Any], owner: str) -> None:
|
|
156
184
|
if not values:
|
|
157
185
|
return
|
|
158
|
-
|
|
159
|
-
logger = logging.getLogger("django_yamlconf")
|
|
160
|
-
logger.addHandler(handler)
|
|
161
|
-
try:
|
|
186
|
+
with fail_on_yamlconf_errors():
|
|
162
187
|
attributes = vars(self.module)[_ATTRIBUTES]
|
|
163
188
|
for key, value in values.items():
|
|
164
189
|
name = setting_name(key)
|
|
@@ -168,8 +193,6 @@ class _Contributions:
|
|
|
168
193
|
django_yamlconf.set_attr_value(attributes, self.module, owner, key, _copy_settings(value))
|
|
169
194
|
expand_attribute_refs(attributes)
|
|
170
195
|
django_yamlconf.inject_attr(attributes, self.module)
|
|
171
|
-
finally:
|
|
172
|
-
logger.removeHandler(handler)
|
|
173
196
|
self._namespace.update(
|
|
174
197
|
{
|
|
175
198
|
name: value
|
|
@@ -253,7 +276,7 @@ class _Contributions:
|
|
|
253
276
|
def apply_app_settings(namespace: MutableMapping[str, Any], closure: Closure) -> None:
|
|
254
277
|
"""Apply a resolved app selection's native settings contributions once.
|
|
255
278
|
|
|
256
|
-
Pass authored settings and a Closure selected by
|
|
279
|
+
Pass authored settings and a Closure selected by components.enabled_apps.
|
|
257
280
|
The same closure is exposed as COMPOSE_CLOSURE before callbacks; its app
|
|
258
281
|
order, selected native configs, yamlconf merging, authored precedence and
|
|
259
282
|
environment rules are retained. This phase requires no composition output
|
|
@@ -280,6 +303,10 @@ def configure(namespace: MutableMapping[str, Any]) -> None:
|
|
|
280
303
|
results can refine their app's defaults but cannot replace authored values.
|
|
281
304
|
Structural compiler inputs may never originate in the environment.
|
|
282
305
|
"""
|
|
306
|
+
if "COMPOSE_ADDON_GROUP" in namespace:
|
|
307
|
+
raise ImproperlyConfigured(
|
|
308
|
+
"COMPOSE_ADDON_GROUP was renamed to COMPOSE_COMPONENT_GROUP; migrate the authored setting"
|
|
309
|
+
)
|
|
283
310
|
selected_mode = mode()
|
|
284
311
|
for name in _DERIVED:
|
|
285
312
|
if name in namespace:
|
|
@@ -289,7 +316,7 @@ def configure(namespace: MutableMapping[str, Any]) -> None:
|
|
|
289
316
|
report_inputs(files=(Path(namespace["COMPOSE_OUTPUT_DIR"]) / "__init__.py",))
|
|
290
317
|
report_watch_paths(namespace.get("COMPOSE_WATCH_PATHS", ()))
|
|
291
318
|
roots = tuple(namespace.get("INSTALLED_APPS", ()))
|
|
292
|
-
closure = enabled_apps(roots, group=namespace.get("
|
|
319
|
+
closure = enabled_apps(roots, group=namespace.get("COMPOSE_COMPONENT_GROUP"))
|
|
293
320
|
apply_app_settings(namespace, closure)
|
|
294
321
|
report_watch_paths(namespace.get("COMPOSE_WATCH_PATHS", ()))
|
|
295
322
|
namespace["COMPOSE_ROOTS"] = roots
|
|
@@ -23,7 +23,14 @@ from django.utils.module_loading import import_string
|
|
|
23
23
|
from django_compose.autoreload import inputs, report_inputs, write_report
|
|
24
24
|
|
|
25
25
|
MIGRATION_COMMANDS = frozenset(
|
|
26
|
-
{
|
|
26
|
+
{
|
|
27
|
+
"makemigrations",
|
|
28
|
+
"migrate",
|
|
29
|
+
"check_migrations",
|
|
30
|
+
"retire_history",
|
|
31
|
+
"reset_migration_history",
|
|
32
|
+
"provision",
|
|
33
|
+
}
|
|
27
34
|
)
|
|
28
35
|
|
|
29
36
|
|
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
"""Prepare database state for a verified composition."""
|
|
2
|
+
|
|
3
|
+
from typing import Any
|
|
4
|
+
|
|
5
|
+
from django.core.management.base import BaseCommand, CommandParser
|
|
6
|
+
from django.db import DEFAULT_DB_ALIAS
|
|
7
|
+
|
|
8
|
+
from django_compose.management import require_serving_mode
|
|
9
|
+
from django_compose.provision import LEGACY_TABLE, run
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
class Command(BaseCommand):
|
|
13
|
+
help = "Apply migrations and idempotent app hooks for the verified composition."
|
|
14
|
+
requires_system_checks: list[str] = []
|
|
15
|
+
|
|
16
|
+
def add_arguments(self, parser: CommandParser) -> None:
|
|
17
|
+
parser.add_argument("--database", default=DEFAULT_DB_ALIAS)
|
|
18
|
+
parser.add_argument("--wait-db", type=int, default=60, metavar="SECONDS")
|
|
19
|
+
parser.add_argument("--check", action="store_true", help="Read readiness without database mutations.")
|
|
20
|
+
parser.add_argument(
|
|
21
|
+
"--upgrade-from", choices=[LEGACY_TABLE], help="Rename the legacy provision table."
|
|
22
|
+
)
|
|
23
|
+
|
|
24
|
+
def handle(self, *args: Any, **options: Any) -> None:
|
|
25
|
+
require_serving_mode()
|
|
26
|
+
run(self, options)
|
|
@@ -5,7 +5,6 @@ from __future__ import annotations
|
|
|
5
5
|
import ast
|
|
6
6
|
import importlib.util
|
|
7
7
|
import pkgutil
|
|
8
|
-
import re
|
|
9
8
|
import symtable
|
|
10
9
|
from collections.abc import Iterable
|
|
11
10
|
from dataclasses import dataclass
|
|
@@ -14,6 +13,7 @@ from pathlib import Path
|
|
|
14
13
|
|
|
15
14
|
from django.apps import apps
|
|
16
15
|
from django.conf import settings
|
|
16
|
+
from packaging.utils import canonicalize_name
|
|
17
17
|
|
|
18
18
|
from django_compose.sources import ModuleSource, SourceResolver
|
|
19
19
|
|
|
@@ -29,10 +29,6 @@ class HistoricalImport:
|
|
|
29
29
|
detail: str = ""
|
|
30
30
|
|
|
31
31
|
|
|
32
|
-
def _distribution_key(name: str) -> str:
|
|
33
|
-
return re.sub(r"[-_.]+", "-", name).lower()
|
|
34
|
-
|
|
35
|
-
|
|
36
32
|
class _ImportCalls(ast.NodeVisitor):
|
|
37
33
|
"""Let Python's symbol tables own import bindings across lexical scopes.
|
|
38
34
|
|
|
@@ -441,7 +437,7 @@ class MigrationImportReport:
|
|
|
441
437
|
|
|
442
438
|
def removal_refusals(self, removing: Iterable[str]) -> tuple[str, ...]:
|
|
443
439
|
"""Refuse enabled providers, retained imports and unprovable dependencies."""
|
|
444
|
-
selected = {
|
|
440
|
+
selected = {canonicalize_name(name) for name in removing}
|
|
445
441
|
refusals = []
|
|
446
442
|
for config in apps.get_app_configs():
|
|
447
443
|
source = self.resolver.resolve(config.name)
|
|
@@ -449,14 +445,14 @@ class MigrationImportReport:
|
|
|
449
445
|
config_source = self.resolver.resolve(type(config).__module__)
|
|
450
446
|
providers.update(config_source.distributions)
|
|
451
447
|
for name in sorted(providers):
|
|
452
|
-
if
|
|
448
|
+
if canonicalize_name(name) in selected:
|
|
453
449
|
refusals.append(f"{name} provides enabled app {config.name}")
|
|
454
450
|
for item in self.items:
|
|
455
451
|
if item.kind in {"unsupported", "unresolved"}:
|
|
456
452
|
refusals.append(f"{item.path}: {item.kind} {item.module}: {item.detail}")
|
|
457
453
|
if item.kind == "namespace":
|
|
458
454
|
if item.distributions and all(
|
|
459
|
-
|
|
455
|
+
canonicalize_name(name) in selected for name in item.distributions
|
|
460
456
|
):
|
|
461
457
|
refusals.append(
|
|
462
458
|
f"{item.path}: retained namespace import {item.module} needs at least one of "
|
|
@@ -464,7 +460,7 @@ class MigrationImportReport:
|
|
|
464
460
|
)
|
|
465
461
|
continue
|
|
466
462
|
for name in item.distributions:
|
|
467
|
-
if
|
|
463
|
+
if canonicalize_name(name) in selected:
|
|
468
464
|
refusals.append(f"{item.path}: retained import {item.module} requires {name}")
|
|
469
465
|
return tuple(sorted(set(refusals)))
|
|
470
466
|
|