django-compose 0.1.0.dev8__py3-none-any.whl → 0.1.0.dev9__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/apps.py CHANGED
@@ -6,7 +6,6 @@ from django.apps import AppConfig
6
6
  from django.conf import settings
7
7
  from django.core.exceptions import ImproperlyConfigured
8
8
 
9
- from django_compose import checks # noqa: F401 -- register deferred native system checks
10
9
  from django_compose.serving import _close_startup_verification, _finish_startup_verification, mode, verify
11
10
  from django_compose.snapshot import Snapshot
12
11
 
@@ -1,4 +1,4 @@
1
- """Native Django dispatch with composition and post-setup execution contexts."""
1
+ """Native Django dispatch with composition-mode selection and the reloader parent."""
2
2
 
3
3
  from __future__ import annotations
4
4
 
@@ -8,17 +8,13 @@ import signal
8
8
  import subprocess
9
9
  import sys
10
10
  import tempfile
11
- from contextlib import ExitStack
12
- from types import MappingProxyType
13
11
  from typing import Any
14
12
 
15
- from django.apps import apps
16
13
  from django.conf import settings
17
14
  from django.core.exceptions import ImproperlyConfigured
18
15
  from django.core.management import ManagementUtility
19
16
  from django.core.management.base import CommandError, handle_default_options
20
17
  from django.utils import autoreload
21
- from django.utils.module_loading import import_string
22
18
 
23
19
  from django_compose.autoreload import inputs, report_inputs, write_report
24
20
 
@@ -40,51 +36,6 @@ def require_serving_mode() -> None:
40
36
  raise CommandError("Migration commands require serving mode; unset DJANGO_COMPOSE_MODE")
41
37
 
42
38
 
43
- class _Dispatch:
44
- def __init__(self, command: Any) -> None:
45
- self.command = command
46
-
47
- def __getattr__(self, name: str) -> Any:
48
- return getattr(self.command, name)
49
-
50
- def run_from_argv(self, argv: list[str]) -> Any:
51
- """Adapt native execute after parsing, retaining the winning argv dispatcher.
52
-
53
- Custom run_from_argv implementations must call self.execute to participate.
54
- Factories receive command, original argv and read-only shallow-copied options.
55
- The native dispatcher continues to own parsing, errors and connection cleanup.
56
- """
57
- original_execute = self.command.execute
58
- missing = object()
59
- previous = vars(self.command).get("execute", missing)
60
- original_argv = tuple(argv)
61
-
62
- def execute(*args: Any, **options: Any) -> Any:
63
- with ExitStack() as stack:
64
- # runserver recovery fabricates ready flags, but not ready_event.
65
- if apps.ready_event.is_set():
66
- parsed_options = MappingProxyType(options.copy())
67
- for dotted in getattr(settings, "COMPOSE_COMMAND_CONTEXT", ()):
68
- stack.enter_context(
69
- import_string(dotted)(original_argv[1], original_argv, parsed_options)
70
- )
71
- return original_execute(*args, **options)
72
-
73
- self.command.execute = execute
74
- try:
75
- return self.command.run_from_argv(argv)
76
- finally:
77
- if previous is missing:
78
- del self.command.execute
79
- else:
80
- self.command.execute = previous
81
-
82
-
83
- class _Utility(ManagementUtility):
84
- def fetch_command(self, subcommand: str) -> Any:
85
- return _Dispatch(super().fetch_command(subcommand))
86
-
87
-
88
39
  def _default_options(arguments: list[str]) -> Any:
89
40
  from django_compose.management.commands.compose import Command
90
41
 
@@ -161,8 +112,16 @@ def _parent(arguments: list[str]) -> None:
161
112
  raise SystemExit(code)
162
113
 
163
114
 
164
- def execute(argv: list[str] | None = None) -> None:
165
- """Drop-in management entrypoint retaining Django's native setup policy."""
115
+ def execute(
116
+ argv: list[str] | None = None, *, utility_class: type[ManagementUtility] = ManagementUtility
117
+ ) -> None:
118
+ """Drop-in management entrypoint retaining Django's native setup policy.
119
+
120
+ Dispatch goes through ``utility_class``, Django's native ManagementUtility
121
+ by default. A project wraps command execution by supplying its own subclass;
122
+ django-compose adds no command middleware. The reloader parent's compose
123
+ subprocess always uses the default dispatcher.
124
+ """
166
125
  arguments = list(sys.argv if argv is None else argv)
167
126
  command = arguments[1] if len(arguments) > 1 else "help"
168
127
  if command in MIGRATION_COMMANDS:
@@ -213,7 +172,7 @@ def execute(argv: list[str] | None = None) -> None:
213
172
  print(f"Composition lock: {settings.COMPOSE_OUTPUT_DIR}/.compose.lock")
214
173
  print("Composition is current.")
215
174
  return
216
- _Utility(arguments).execute()
175
+ utility_class(arguments).execute()
217
176
  finally:
218
177
  try:
219
178
  _fallback_inputs()
@@ -23,9 +23,7 @@ from django_compose.sources import SourceResolver
23
23
  COMPILER = "django-compose:2"
24
24
  DEFAULT_EXCLUDES = ("**/__pycache__/**", "**/migrations/**", "**/tests/**")
25
25
 
26
- NON_INPUT_SETTINGS = frozenset(
27
- {"COMPOSE_ROOTS", "COMPOSE_SNAPSHOT", "COMPOSE_CLOSURE", "COMPOSE_COMMAND_CONTEXT"}
28
- )
26
+ NON_INPUT_SETTINGS = frozenset({"COMPOSE_ROOTS", "COMPOSE_SNAPSHOT", "COMPOSE_CLOSURE"})
29
27
  STRUCTURAL_SETTINGS = frozenset(
30
28
  {
31
29
  "INSTALLED_APPS",
@@ -206,6 +204,11 @@ def snapshot(
206
204
  "COMPOSE_TRANSITION_SOURCE is no longer supported; review pending schema and data work "
207
205
  "and author native project migrations before upgrading"
208
206
  )
207
+ if "COMPOSE_COMMAND_CONTEXT" in values:
208
+ raise ImproperlyConfigured(
209
+ "COMPOSE_COMMAND_CONTEXT is no longer supported; wrap command execution through "
210
+ "execute(..., utility_class=...) with a native ManagementUtility subclass"
211
+ )
209
212
  normalized = app_entries(entries)
210
213
  positions = {entry.name: index for index, entry in enumerate(normalized)}
211
214
  edges = {} if dependencies is None else dependencies
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.5
2
2
  Name: django-compose
3
- Version: 0.1.0.dev8
3
+ Version: 0.1.0.dev9
4
4
  Summary: Compose reusable Django apps into a runnable project.
5
5
  Project-URL: Source, https://github.com/ang-ee/django-compose
6
6
  Project-URL: Documentation, https://github.com/ang-ee/django-compose/tree/main/docs
@@ -1,11 +1,9 @@
1
1
  django_compose/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
2
2
  django_compose/__main__.py,sha256=3UMaUz10MyIX8O46BUiU269LnvxdKfjImI2j2Jnl3us,135
3
- django_compose/apps.py,sha256=Lzicsfm5riNQxqgWklxoqBTE4dpJO1z-enMdincatm0,3944
3
+ django_compose/apps.py,sha256=GO_bUP_aXEva0vI21G9CKVw_C2FRSxiNuBhy6wtVn6M,3854
4
4
  django_compose/artifacts.py,sha256=JIwTpHDB6dahVpOOrS9M8bHWV1356nGCjCo45Sds5vg,10046
5
- django_compose/asgi.py,sha256=EllgrrF3fMEQXNd3YR5JvijKaKFHqPI2Lv2PtmQ4ZKA,5151
6
5
  django_compose/autoreload.py,sha256=Obguzio30T42nIjSX9HVmrU-CqtTrm7moU0Wd271Egg,4128
7
6
  django_compose/build.py,sha256=DQ3yVb7SZtflMeIhBSFJalVby62sU8vvpu-l93pIL9c,11536
8
- django_compose/checks.py,sha256=68mO4E6_UPYhya9wjO-SsQ2YFnDSl0q_fI8r-DnSTZ0,366
9
7
  django_compose/cli.py,sha256=9YlvZY7-qPVtuTXpMA5KxtAZd-TzTVCrg-2F4cNodUM,1209
10
8
  django_compose/components.py,sha256=jNMkWm0Q15dbmVkK3jBdM_ldgqilFitvrfGaRHxmXx0,14518
11
9
  django_compose/conf.py,sha256=Y6wEhxZh2gT_XjooEjc_5Ry0MOEIaPH4yCOf6UlZo-U,15838
@@ -19,11 +17,10 @@ django_compose/provision.py,sha256=ufGuc1jesX6gid-s1a-rNwQbKvKcgnOjvSPwVdUrHF4,1
19
17
  django_compose/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
20
18
  django_compose/rendering.py,sha256=1OFZU7lLMO2rD4S9K1-g8wvdn8RKBnUuQTFPHnDWsHY,3647
21
19
  django_compose/serving.py,sha256=FoS3TNNpgPGLpfCHtGrW0JVJVT9DyI7sxJ5U4x0oVLU,15498
22
- django_compose/snapshot.py,sha256=HH0lwhQtnUR0xLF4JNs-bAuU5b_97qWhYhjR_gXhX48,13316
20
+ django_compose/snapshot.py,sha256=pHVV9P-gDM_JukVxav3veICgDYc_8xm4RFLdr0mvM00,13554
23
21
  django_compose/sources.py,sha256=fLBGSHtAInnoTM1Z2Wdt74P_cbLUUP4MWD1l2uS_zAI,6629
24
22
  django_compose/typing.py,sha256=13pd3JfIoBV8v4AHK-QgAg9J8C4Miz_D0dmHFEwUG4I,36089
25
- django_compose/urls.py,sha256=PZLa-pGe5JgzpUgu9sOEUbO2FgLGPkZZSOhRD1ZLgUk,2969
26
- django_compose/management/__init__.py,sha256=wBX58M8MHUEvl9M57wVNNDAq4lsCSLjPtM3Copabs2w,8724
23
+ django_compose/management/__init__.py,sha256=z5LGwZCxfGd44kJWDpQZkdwclHwfFlBgCBfJjPmcdI0,7156
27
24
  django_compose/management/commands/__init__.py,sha256=_mgOwmIp5-GhgJd6tY4Wc89G0EJDiHF9tYo8F63ytm8,40
28
25
  django_compose/management/commands/check_migrations.py,sha256=ORx1cV9cMd0hlboWfTHUra8DvJLSw_QqwNCKUn6AtDY,2818
29
26
  django_compose/management/commands/compose.py,sha256=UuNjIgNwYOYE_1aKIcEvh3C1fMjP9tdN_-SDDwVQjIc,1860
@@ -32,10 +29,10 @@ django_compose/management/commands/migrate.py,sha256=_MkiQRjQRwIr9dEUnKk4WEjLgz5
32
29
  django_compose/management/commands/provision.py,sha256=4GTPwH1Pp1V_YkztDZxeHuyAjDUHjZxhkdvFlrgDBfU,1035
33
30
  django_compose/management/commands/reset_migration_history.py,sha256=Q6ShGeiWOAFS-rZOWuP0lncjwYp9vjRRbaIuk7Aoth0,1428
34
31
  django_compose/management/commands/retire_history.py,sha256=3RV1-w5Niij0svr0gB_gAjBgskxCYtdg5pPfsGN287s,886
35
- django_compose-0.1.0.dev8.dist-info/METADATA,sha256=AYmR_yB0ECx2tGrujGGwxJhHvsLY3pibDeyJ3xhu_v4,4151
36
- django_compose-0.1.0.dev8.dist-info/WHEEL,sha256=2iZrJkDIkeDh0k9SikKMqFuRP-ua6mb4Ir1AsER4BEw,87
37
- django_compose-0.1.0.dev8.dist-info/entry_points.txt,sha256=-Iw1c8YAegCC53YCKgPXjIZn4aPS3MmEKbcMrCpUMFU,59
38
- django_compose-0.1.0.dev8.dist-info/licenses/COPYING,sha256=jOtLnuWt7d5Hsx6XXB2QxzrSe2sWWh3NgMfFRetluQM,35147
39
- django_compose-0.1.0.dev8.dist-info/licenses/LICENSE,sha256=46mU2C5kSwOnkqkw9XQAJlhBL2JAf1_uCD8lVcXyMRg,7652
40
- django_compose-0.1.0.dev8.dist-info/licenses/NOTICE,sha256=C4fEGI9_-a1GCPfAH9bC0ZvmZFS71b9Z4v6rjrT5dxA,450
41
- django_compose-0.1.0.dev8.dist-info/RECORD,,
32
+ django_compose-0.1.0.dev9.dist-info/METADATA,sha256=YUQt0oeVSlMZhpLS33zAOrxRksdiftylg9sDq75eWtY,4151
33
+ django_compose-0.1.0.dev9.dist-info/WHEEL,sha256=2iZrJkDIkeDh0k9SikKMqFuRP-ua6mb4Ir1AsER4BEw,87
34
+ django_compose-0.1.0.dev9.dist-info/entry_points.txt,sha256=-Iw1c8YAegCC53YCKgPXjIZn4aPS3MmEKbcMrCpUMFU,59
35
+ django_compose-0.1.0.dev9.dist-info/licenses/COPYING,sha256=jOtLnuWt7d5Hsx6XXB2QxzrSe2sWWh3NgMfFRetluQM,35147
36
+ django_compose-0.1.0.dev9.dist-info/licenses/LICENSE,sha256=46mU2C5kSwOnkqkw9XQAJlhBL2JAf1_uCD8lVcXyMRg,7652
37
+ django_compose-0.1.0.dev9.dist-info/licenses/NOTICE,sha256=C4fEGI9_-a1GCPfAH9bC0ZvmZFS71b9Z4v6rjrT5dxA,450
38
+ django_compose-0.1.0.dev9.dist-info/RECORD,,
django_compose/asgi.py DELETED
@@ -1,110 +0,0 @@
1
- """Post-setup ASGI composition over native Django HTTP and async contexts."""
2
-
3
- from __future__ import annotations
4
-
5
- from collections.abc import Callable, Mapping
6
- from contextlib import AbstractAsyncContextManager, AsyncExitStack
7
- from dataclasses import dataclass, field
8
- from typing import cast
9
-
10
- from asgiref.typing import ASGI3Application, ASGIReceiveCallable, ASGISendCallable, Scope
11
- from django.apps import apps
12
- from django.core.exceptions import ImproperlyConfigured
13
- from django.core.handlers.asgi import ASGIHandler
14
-
15
-
16
- @dataclass(frozen=True)
17
- class AsgiContribution:
18
- """Mount paths and scope handlers; lifespan factories return fresh async contexts.
19
-
20
- Mounts are absolute decoded paths without a trailing slash (except `/`).
21
- The mounted app receives the original path with its mount added to root_path,
22
- following ASGI's path/root_path convention. Query strings are unchanged.
23
- HTTP and lifespan are reserved scope types.
24
- """
25
-
26
- http_mounts: Mapping[str, ASGI3Application] = field(default_factory=dict)
27
- lifespans: tuple[Callable[[], AbstractAsyncContextManager[object]], ...] = ()
28
- protocols: Mapping[str, ASGI3Application] = field(default_factory=dict)
29
-
30
-
31
- class _Application:
32
- def __init__(self) -> None:
33
- apps.check_apps_ready()
34
- if not apps.ready:
35
- raise RuntimeError("ASGI composition requires completed django.setup()")
36
- self.http = cast(ASGI3Application, ASGIHandler())
37
- self.mounts: dict[str, ASGI3Application] = {}
38
- self.protocols: dict[str, ASGI3Application] = {}
39
- self.lifespans: list[Callable[[], AbstractAsyncContextManager[object]]] = []
40
- mount_owners: dict[str, str] = {}
41
- protocol_owners = {"http": "Django HTTP fallback", "lifespan": "django-compose lifespan"}
42
- for config in apps.get_app_configs():
43
- factory = getattr(config, "compose_asgi", None)
44
- if factory is None:
45
- continue
46
- contribution = factory()
47
- if not isinstance(contribution, AsgiContribution):
48
- raise ImproperlyConfigured(f"{config.name}.compose_asgi() must return AsgiContribution")
49
- for prefix, handler in contribution.http_mounts.items():
50
- if (
51
- not isinstance(prefix, str)
52
- or not prefix.startswith("/")
53
- or (prefix != "/" and prefix.endswith("/"))
54
- ):
55
- raise ImproperlyConfigured(f"{config.name}: invalid HTTP mount {prefix!r}")
56
- self._claim(mount_owners, prefix, config.name)
57
- self.mounts[prefix] = handler
58
- for protocol, handler in contribution.protocols.items():
59
- self._claim(protocol_owners, protocol, config.name)
60
- self.protocols[protocol] = handler
61
- self.lifespans.extend(contribution.lifespans)
62
- self.prefixes = sorted(self.mounts, key=lambda prefix: (-len(prefix), prefix))
63
-
64
- @staticmethod
65
- def _claim(owners: dict[str, str], key: str, owner: str) -> None:
66
- if key in owners:
67
- raise ImproperlyConfigured(f"ASGI {key!r} is claimed by {owners[key]} and {owner}")
68
- owners[key] = owner
69
-
70
- async def __call__(self, scope: Scope, receive: ASGIReceiveCallable, send: ASGISendCallable) -> None:
71
- kind = scope["type"]
72
- if scope["type"] == "lifespan":
73
- await self._lifespan(receive, send)
74
- elif scope["type"] == "http":
75
- root = scope.get("root_path", "")
76
- relative = scope["path"].removeprefix(root)
77
- for prefix in self.prefixes:
78
- if prefix == "/" or relative == prefix or relative.startswith(prefix + "/"):
79
- mounted = scope.copy()
80
- mounted["root_path"] = root + ("" if prefix == "/" else prefix)
81
- await self.mounts[prefix](mounted, receive, send)
82
- return
83
- await self.http(scope, receive, send)
84
- elif kind in self.protocols:
85
- await self.protocols[kind](scope, receive, send)
86
- else:
87
- raise ValueError(f"Unsupported ASGI scope type: {kind!r}")
88
-
89
- async def _lifespan(self, receive: ASGIReceiveCallable, send: ASGISendCallable) -> None:
90
- if (await receive())["type"] != "lifespan.startup":
91
- raise ValueError("Expected lifespan.startup")
92
- started = False
93
- try:
94
- async with AsyncExitStack() as stack:
95
- for factory in self.lifespans:
96
- await stack.enter_async_context(factory())
97
- started = True
98
- await send({"type": "lifespan.startup.complete"})
99
- if (await receive())["type"] != "lifespan.shutdown":
100
- raise ValueError("Expected lifespan.shutdown")
101
- except Exception as error:
102
- if started:
103
- await send({"type": "lifespan.shutdown.failed", "message": str(error)})
104
- else:
105
- await send({"type": "lifespan.startup.failed", "message": str(error)})
106
- else:
107
- await send({"type": "lifespan.shutdown.complete"})
108
-
109
-
110
- application = _Application()
django_compose/checks.py DELETED
@@ -1,11 +0,0 @@
1
- """Bootstrap-safe registration of deferred native serving checks."""
2
-
3
- from django.core.checks import Error, Tags, register
4
-
5
-
6
- @register(Tags.urls)
7
- def check_url_collisions(**kwargs: object) -> list[Error]:
8
- """Load URL policy only when native checks run after setup."""
9
- from django_compose.urls import check_url_collisions as check
10
-
11
- return check(**kwargs)
django_compose/urls.py DELETED
@@ -1,79 +0,0 @@
1
- """Post-setup, opt-in native Django URL composition."""
2
-
3
- from __future__ import annotations
4
-
5
- from collections.abc import Iterator
6
-
7
- from django.apps import apps
8
- from django.core.checks import Error
9
- from django.urls import URLPattern, URLResolver, include, path
10
- from django.urls.resolvers import RegexPattern, RoutePattern
11
-
12
- type _Route = tuple[tuple[object, ...], ...]
13
-
14
-
15
- def _patterns() -> Iterator[tuple[str, URLResolver]]:
16
- apps.check_apps_ready()
17
- if not apps.ready:
18
- raise RuntimeError("URL composition requires completed django.setup()")
19
- for config in apps.get_app_configs():
20
- module = getattr(config, "compose_urls", None)
21
- if module is not None:
22
- yield (
23
- config.name,
24
- path(
25
- getattr(config, "compose_url_prefix", ""),
26
- include(module, namespace=getattr(config, "compose_url_namespace", None)),
27
- ),
28
- )
29
-
30
-
31
- def _routes(pattern: URLPattern | URLResolver, prefix: _Route = ()) -> Iterator[_Route]:
32
- native = pattern.pattern
33
- if type(pattern) not in (URLPattern, URLResolver) or type(native) not in (RoutePattern, RegexPattern):
34
- return
35
- # Each include matches independently. Preserve native boundaries, anchors,
36
- # flags and converter identity instead of approximating one combined regex.
37
- route = prefix + (
38
- (
39
- type(native),
40
- native.regex.pattern,
41
- native.regex.flags,
42
- native._is_endpoint, # type: ignore[union-attr] # Native attribute omitted by django-stubs.
43
- tuple((name, id(converter)) for name, converter in native.converters.items()),
44
- ),
45
- )
46
- if isinstance(pattern, URLResolver):
47
- for child in pattern.url_patterns:
48
- yield from _routes(child, route)
49
- else:
50
- yield route
51
-
52
-
53
- def check_url_collisions(**kwargs: object) -> list[Error]:
54
- """Report identical native matching chains, regardless of reverse namespace.
55
-
56
- Pattern type, regex text/flags, endpoint behavior and converter instances
57
- must agree at every include boundary. Differently expressed chains and
58
- custom pattern types retain Django's ordered resolution without a proof.
59
- No converter is executed by this check.
60
- """
61
- owners: dict[_Route, str] = {}
62
- errors = []
63
- # Retain native resolvers throughout the proof so converter IDs stay live.
64
- for owner, resolver in tuple(_patterns()):
65
- for route in _routes(resolver):
66
- previous = owners.get(route)
67
- owners[route] = owner
68
- if previous is not None:
69
- errors.append(
70
- Error(
71
- f"URL pattern chain {tuple(part[1] for part in route)!r} "
72
- f"is claimed by {previous} and {owner}",
73
- id="django_compose.E001",
74
- )
75
- )
76
- return errors
77
-
78
-
79
- urlpatterns = [resolver for _, resolver in _patterns()]