django-compose 0.1.0.dev1__py3-none-any.whl → 0.1.0.dev2__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 +15 -6
- django_compose/build.py +12 -27
- django_compose/cli.py +23 -2
- django_compose/{addons.py → components.py} +115 -16
- django_compose/conf.py +39 -12
- django_compose/management/__init__.py +8 -1
- django_compose/management/commands/provision.py +26 -0
- django_compose/migrations.py +52 -33
- django_compose/model_composition.py +40 -17
- django_compose/provision.py +349 -0
- django_compose/snapshot.py +1 -1
- django_compose/typing.py +5 -6
- {django_compose-0.1.0.dev1.dist-info → django_compose-0.1.0.dev2.dist-info}/METADATA +16 -6
- {django_compose-0.1.0.dev1.dist-info → django_compose-0.1.0.dev2.dist-info}/RECORD +19 -17
- {django_compose-0.1.0.dev1.dist-info → django_compose-0.1.0.dev2.dist-info}/WHEEL +0 -0
- {django_compose-0.1.0.dev1.dist-info → django_compose-0.1.0.dev2.dist-info}/entry_points.txt +0 -0
- {django_compose-0.1.0.dev1.dist-info → django_compose-0.1.0.dev2.dist-info}/licenses/COPYING +0 -0
- {django_compose-0.1.0.dev1.dist-info → django_compose-0.1.0.dev2.dist-info}/licenses/LICENSE +0 -0
- {django_compose-0.1.0.dev1.dist-info → django_compose-0.1.0.dev2.dist-info}/licenses/NOTICE +0 -0
django_compose/artifacts.py
CHANGED
|
@@ -17,7 +17,12 @@ 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
|
+
"""
|
|
21
26
|
# Native loaders may otherwise accept same-second, same-size stale bytecode.
|
|
22
27
|
caches: tuple[Path, ...] = ()
|
|
23
28
|
if path.suffix == ".py" and "migrations" not in path.parts:
|
|
@@ -27,10 +32,11 @@ def atomic_write(path: Path, content: bytes) -> None:
|
|
|
27
32
|
caches = tuple(sorted(cache_dir.glob(f"{path.stem}.*.pyc")))
|
|
28
33
|
if any(cache.is_symlink() or not cache.is_file() for cache in caches):
|
|
29
34
|
raise ValueError(f"Unsafe generated bytecode cache for {path}")
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
35
|
+
if mode is None:
|
|
36
|
+
try:
|
|
37
|
+
mode = stat.S_IMODE(path.stat().st_mode)
|
|
38
|
+
except FileNotFoundError:
|
|
39
|
+
pass
|
|
34
40
|
path.parent.mkdir(parents=True, exist_ok=True)
|
|
35
41
|
descriptor, temporary = tempfile.mkstemp(prefix=".compose-", dir=path.parent)
|
|
36
42
|
try:
|
|
@@ -40,7 +46,10 @@ def atomic_write(path: Path, content: bytes) -> None:
|
|
|
40
46
|
if mode is not None:
|
|
41
47
|
os.fchmod(stream.fileno(), mode)
|
|
42
48
|
os.fsync(stream.fileno())
|
|
43
|
-
|
|
49
|
+
if exclusive:
|
|
50
|
+
os.link(temporary, path)
|
|
51
|
+
else:
|
|
52
|
+
os.replace(temporary, path)
|
|
44
53
|
for cache in caches:
|
|
45
54
|
cache.unlink(missing_ok=True)
|
|
46
55
|
finally:
|
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)
|
|
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
|
-
"""Resolve installed
|
|
1
|
+
"""Resolve installed component metadata into an ordered selection of native Django apps."""
|
|
2
2
|
|
|
3
3
|
from __future__ import annotations
|
|
4
4
|
|
|
5
|
+
import json
|
|
6
|
+
import math
|
|
7
|
+
import os
|
|
8
|
+
import subprocess
|
|
9
|
+
import sys
|
|
5
10
|
from collections.abc import Iterable, Mapping
|
|
6
|
-
from dataclasses import dataclass, field
|
|
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,7 +178,7 @@ def active_requirements(requirements: Iterable[str]) -> tuple[Requirement, ...]:
|
|
|
81
178
|
)
|
|
82
179
|
|
|
83
180
|
|
|
84
|
-
def
|
|
181
|
+
def installed_components(group: str) -> InstalledComponents:
|
|
85
182
|
"""Index group declarations and declared app-key collisions without imports.
|
|
86
183
|
|
|
87
184
|
Each participating distribution must declare exactly one group entry point.
|
|
@@ -89,7 +186,7 @@ def installed_addons(group: str) -> InstalledAddons:
|
|
|
89
186
|
Native metadata.distribution selects the winner for same-name installations.
|
|
90
187
|
"""
|
|
91
188
|
if not isinstance(group, str) or not group:
|
|
92
|
-
raise ImproperlyConfigured("An explicit non-empty
|
|
189
|
+
raise ImproperlyConfigured("An explicit non-empty component entry-point group is required")
|
|
93
190
|
distributions: dict[str, metadata.Distribution] = {}
|
|
94
191
|
points: dict[str, metadata.EntryPoint] = {}
|
|
95
192
|
app_providers: dict[str, str] = {}
|
|
@@ -109,7 +206,7 @@ def installed_addons(group: str) -> InstalledAddons:
|
|
|
109
206
|
)
|
|
110
207
|
app_providers[point.name] = name
|
|
111
208
|
points[name] = point
|
|
112
|
-
return
|
|
209
|
+
return InstalledComponents(
|
|
113
210
|
MappingProxyType(distributions), MappingProxyType(points), MappingProxyType(app_providers)
|
|
114
211
|
)
|
|
115
212
|
|
|
@@ -120,14 +217,14 @@ def enabled_apps(roots: Iterable[str], *, group: str | None = None) -> Closure:
|
|
|
120
217
|
Settings are never read. Without a group, only native requires_apps edges
|
|
121
218
|
apply and distribution metadata is not inspected. Its entry-point keys are
|
|
122
219
|
native app names and values are native INSTALLED_APPS strings, never loaded
|
|
123
|
-
entry-point objects.
|
|
220
|
+
entry-point objects. A component's active Requires-Dist edges (extra='') activate
|
|
124
221
|
only distributions in this group. Ordinary roots have no metadata expansion.
|
|
125
|
-
Installation alone never activates
|
|
222
|
+
Installation alone never activates a component or an optional extra.
|
|
126
223
|
|
|
127
224
|
Root configs are preselected and override dependency/default config choices.
|
|
128
225
|
Conflicting dependency configs, duplicate native labels and cycles fail.
|
|
129
226
|
"""
|
|
130
|
-
installed =
|
|
227
|
+
installed = installed_components(group) if group is not None else None
|
|
131
228
|
root_entries = tuple(roots)
|
|
132
229
|
if any(not isinstance(entry, str) for entry in root_entries):
|
|
133
230
|
raise ImproperlyConfigured("Root INSTALLED_APPS entries must be native app strings")
|
|
@@ -139,7 +236,7 @@ def enabled_apps(roots: Iterable[str], *, group: str | None = None) -> Closure:
|
|
|
139
236
|
by_app = installed.providers if installed is not None else {}
|
|
140
237
|
graph: dict[str, tuple[str, ...]] = {}
|
|
141
238
|
|
|
142
|
-
def
|
|
239
|
+
def component_entry(provider: str) -> str:
|
|
143
240
|
assert installed is not None
|
|
144
241
|
point = installed.entry_points[provider]
|
|
145
242
|
config = AppConfig.create(point.value)
|
|
@@ -171,16 +268,16 @@ def enabled_apps(roots: Iterable[str], *, group: str | None = None) -> Closure:
|
|
|
171
268
|
dependencies = list(required_apps)
|
|
172
269
|
provider = by_app.get(name)
|
|
173
270
|
if provider is not None:
|
|
174
|
-
|
|
271
|
+
component_entry(provider)
|
|
175
272
|
assert installed is not None
|
|
176
273
|
for parsed in installed.active_requirements(provider):
|
|
177
274
|
dependency = canonicalize_name(parsed.name)
|
|
178
275
|
if dependency not in installed.distributions:
|
|
179
276
|
raise ImproperlyConfigured(
|
|
180
|
-
f"
|
|
277
|
+
f"Component {name!r} requires missing installed distribution {parsed.name!r}"
|
|
181
278
|
)
|
|
182
279
|
if dependency in installed.entry_points:
|
|
183
|
-
dependencies.append(
|
|
280
|
+
dependencies.append(component_entry(dependency))
|
|
184
281
|
if any(not isinstance(entry, str) for entry in dependencies):
|
|
185
282
|
raise ImproperlyConfigured(f"{name}.requires_apps entries must be native app strings")
|
|
186
283
|
graph[name] = tuple(sorted({choose(entry) for entry in sorted(dependencies)}))
|
|
@@ -199,7 +296,9 @@ def enabled_apps(roots: Iterable[str], *, group: str | None = None) -> Closure:
|
|
|
199
296
|
entries,
|
|
200
297
|
root_names,
|
|
201
298
|
frozenset(ordered) - root_set,
|
|
202
|
-
|
|
299
|
+
MappingProxyType(
|
|
300
|
+
{by_app[name]: name for name in sorted(set(ordered).intersection(by_app), key=by_app.__getitem__)}
|
|
301
|
+
),
|
|
203
302
|
MappingProxyType(graph),
|
|
204
303
|
app_configs=configs,
|
|
205
304
|
)
|
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)
|