django-compose 0.1.0.dev7__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
 
@@ -54,13 +53,11 @@ class BuildComposeConfig(AppConfig):
54
53
  if selected_mode == "check":
55
54
  verify(snap, output_module)
56
55
  integrations = resolve_integrations(snap.integration_paths)
57
- transitions = snap.transition_records
58
56
  self.plan = emit(
59
57
  snap,
60
58
  self.apps.get_app_configs(),
61
59
  mode=selected_mode,
62
60
  integrations=integrations,
63
- transitions=transitions,
64
61
  output_dir=output_dir,
65
62
  output_module=output_module,
66
63
  )
@@ -92,11 +89,9 @@ class BuildComposeConfig(AppConfig):
92
89
  )
93
90
  self.receipt = self.plan.finalize()
94
91
  if self.compose_mode == "check":
95
- from django_compose.migrations import TransitionBinding
92
+ from django_compose.migrations import check_native_history
96
93
 
97
- binding = TransitionBinding(labels=self.plan.labels, declarations=self.plan.transitions)
98
- assert self.apps is not None
99
- binding.check_native_history(self.apps)
94
+ check_native_history(self.apps, labels=self.plan.labels)
100
95
  _finish_startup_verification()
101
96
  finally:
102
97
  self.plan.close()
django_compose/build.py CHANGED
@@ -41,7 +41,6 @@ class BuildPlan:
41
41
  *,
42
42
  mode: Literal["write", "check"],
43
43
  integrations: tuple[object, ...],
44
- transitions: Iterable[Any],
45
44
  output_dir: Path,
46
45
  output_module: str,
47
46
  ) -> None:
@@ -57,7 +56,6 @@ class BuildPlan:
57
56
  self.configs = tuple(c for c in configs if c.name in selected)
58
57
  self.mode = mode
59
58
  self.integrations = integrations
60
- self.transitions = tuple(transitions)
61
59
  self.output_dir = output_dir
62
60
  self.output_module = output_module
63
61
  self.previous = read_receipt(output_dir)
@@ -79,7 +77,6 @@ class BuildPlan:
79
77
  history = set(previous.HISTORY_LABELS if previous else ())
80
78
  history.update(getattr(self, "labels", ()))
81
79
  history.update(path.parent.name for path in self.output_dir.glob("*/migrations") if path.is_dir())
82
- history.update(transition["app_label"] for transition in self.transitions)
83
80
  return Receipt(
84
81
  tuple(sorted(history - set(retired))),
85
82
  retired,
@@ -248,7 +245,6 @@ def emit(
248
245
  *,
249
246
  mode: Literal["write", "check"],
250
247
  integrations: tuple[object, ...],
251
- transitions: Iterable[Any],
252
248
  output_dir: Path | str,
253
249
  output_module: str,
254
250
  ) -> BuildPlan:
@@ -257,7 +253,6 @@ def emit(
257
253
  configs,
258
254
  mode=mode,
259
255
  integrations=integrations,
260
- transitions=transitions,
261
256
  output_dir=Path(output_dir),
262
257
  output_module=output_module,
263
258
  ).emit()
@@ -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,24 +8,19 @@ 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
 
25
21
  MIGRATION_COMMANDS = frozenset(
26
22
  {
27
23
  "makemigrations",
28
- "adopt_transition",
29
24
  "migrate",
30
25
  "check_migrations",
31
26
  "retire_history",
@@ -41,51 +36,6 @@ def require_serving_mode() -> None:
41
36
  raise CommandError("Migration commands require serving mode; unset DJANGO_COMPOSE_MODE")
42
37
 
43
38
 
44
- class _Dispatch:
45
- def __init__(self, command: Any) -> None:
46
- self.command = command
47
-
48
- def __getattr__(self, name: str) -> Any:
49
- return getattr(self.command, name)
50
-
51
- def run_from_argv(self, argv: list[str]) -> Any:
52
- """Adapt native execute after parsing, retaining the winning argv dispatcher.
53
-
54
- Custom run_from_argv implementations must call self.execute to participate.
55
- Factories receive command, original argv and read-only shallow-copied options.
56
- The native dispatcher continues to own parsing, errors and connection cleanup.
57
- """
58
- original_execute = self.command.execute
59
- missing = object()
60
- previous = vars(self.command).get("execute", missing)
61
- original_argv = tuple(argv)
62
-
63
- def execute(*args: Any, **options: Any) -> Any:
64
- with ExitStack() as stack:
65
- # runserver recovery fabricates ready flags, but not ready_event.
66
- if apps.ready_event.is_set():
67
- parsed_options = MappingProxyType(options.copy())
68
- for dotted in getattr(settings, "COMPOSE_COMMAND_CONTEXT", ()):
69
- stack.enter_context(
70
- import_string(dotted)(original_argv[1], original_argv, parsed_options)
71
- )
72
- return original_execute(*args, **options)
73
-
74
- self.command.execute = execute
75
- try:
76
- return self.command.run_from_argv(argv)
77
- finally:
78
- if previous is missing:
79
- del self.command.execute
80
- else:
81
- self.command.execute = previous
82
-
83
-
84
- class _Utility(ManagementUtility):
85
- def fetch_command(self, subcommand: str) -> Any:
86
- return _Dispatch(super().fetch_command(subcommand))
87
-
88
-
89
39
  def _default_options(arguments: list[str]) -> Any:
90
40
  from django_compose.management.commands.compose import Command
91
41
 
@@ -162,8 +112,16 @@ def _parent(arguments: list[str]) -> None:
162
112
  raise SystemExit(code)
163
113
 
164
114
 
165
- def execute(argv: list[str] | None = None) -> None:
166
- """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
+ """
167
125
  arguments = list(sys.argv if argv is None else argv)
168
126
  command = arguments[1] if len(arguments) > 1 else "help"
169
127
  if command in MIGRATION_COMMANDS:
@@ -214,7 +172,7 @@ def execute(argv: list[str] | None = None) -> None:
214
172
  print(f"Composition lock: {settings.COMPOSE_OUTPUT_DIR}/.compose.lock")
215
173
  print("Composition is current.")
216
174
  return
217
- _Utility(arguments).execute()
175
+ utility_class(arguments).execute()
218
176
  finally:
219
177
  try:
220
178
  _fallback_inputs()
@@ -7,13 +7,12 @@ from django.core.management.base import BaseCommand, CommandError, CommandParser
7
7
  from django.db.migrations.loader import MigrationLoader
8
8
 
9
9
  from django_compose.management import require_serving_mode
10
- from django_compose.management.commands.makemigrations import history_labels
11
10
  from django_compose.migration_imports import MigrationImportReport
12
- from django_compose.migrations import TransitionBinding
11
+ from django_compose.migrations import check_native_history, history_labels
13
12
 
14
13
 
15
14
  class Command(BaseCommand):
16
- help = "Check native history and pending transitions, or audit retained Python imports."
15
+ help = "Check native history, or audit retained Python imports."
17
16
  requires_system_checks: list[str] = []
18
17
 
19
18
  def add_arguments(self, parser: CommandParser) -> None:
@@ -52,6 +51,6 @@ class Command(BaseCommand):
52
51
  self.stdout.write("No retained history or enabled app requires the named distributions.")
53
52
  return
54
53
  try:
55
- TransitionBinding(labels=history_labels()).check_native_history(apps)
54
+ check_native_history(apps, labels=history_labels())
56
55
  except RuntimeError as error:
57
56
  raise CommandError(str(error)) from error
@@ -1,236 +1,18 @@
1
- """Author initial schema, bind transitions, then reconcile native model changes."""
1
+ """Author native migrations with the shared destructive-operation safeguards."""
2
2
 
3
- from __future__ import annotations
4
-
5
- import importlib
6
- import stat
7
- from pathlib import Path
8
3
  from typing import Any
9
4
 
10
- from django.apps import apps
11
- from django.conf import settings
12
- from django.core.exceptions import ImproperlyConfigured
13
- from django.core.management.base import CommandError
14
5
  from django.core.management.commands.makemigrations import Command as NativeCommand
15
- from django.db.migrations import Migration
16
- from django.db.migrations.loader import MigrationLoader
17
- from django.db.migrations.writer import MigrationWriter
18
- from django.utils.module_loading import module_dir
19
6
 
20
- from django_compose.artifacts import atomic_write
21
7
  from django_compose.management import require_serving_mode
22
- from django_compose.migrations import (
23
- DropGuardAutodetector,
24
- TransitionBinding,
25
- _forget_history,
26
- _metadata,
27
- )
28
- from django_compose.serving import read_receipt
29
-
30
-
31
- def _file_state(path: Path) -> tuple[bytes, int] | None:
32
- return (path.read_bytes(), stat.S_IMODE(path.stat().st_mode)) if path.exists() else None
33
-
34
-
35
- def history_labels() -> tuple[str, ...]:
36
- """Read the compiler receipt without invoking composition."""
37
- receipt = read_receipt(Path(settings.COMPOSE_OUTPUT_DIR))
38
- if receipt is None:
39
- raise CommandError("Migration authoring requires a receipt; run compose first")
40
- return tuple(receipt.HISTORY_LABELS)
8
+ from django_compose.migrations import DropGuardAutodetector
41
9
 
42
10
 
43
11
  class Command(NativeCommand):
44
- """Keep native authoring and add immutable reusable origin binding."""
12
+ """Delegate migration authoring and serialization to Django."""
45
13
 
46
14
  autodetector = DropGuardAutodetector
47
- _initial_history: frozenset[str] | None = None
48
-
49
- def __init__(self, *args: Any, **kwargs: Any) -> None:
50
- super().__init__(*args, **kwargs)
51
- self._originals: dict[Path, tuple[bytes, int] | None] = {}
52
- self._bound_files: list[Path] = []
53
- self._changed_labels: set[str] = set()
54
- self._migration_packages: dict[str, Path] = {}
55
15
 
56
- def handle(self, *app_labels: str, **options: Any) -> str | None:
57
- self._originals.clear()
58
- self._bound_files.clear()
59
- self._changed_labels.clear()
60
- self._migration_packages.clear()
61
- try:
62
- return self._author(*app_labels, **options)
63
- except BaseException:
64
- for path in self._bound_files:
65
- path.unlink(missing_ok=True)
66
- for path, original in self._originals.items():
67
- if original is None:
68
- path.unlink(missing_ok=True)
69
- else:
70
- content, mode = original
71
- atomic_write(path, content, mode=mode)
72
- _forget_history(self._changed_labels, packages=self._migration_packages)
73
- raise
74
-
75
- def _remember(self, path: Path) -> None:
76
- path = path.resolve()
77
- if path not in self._originals:
78
- self._originals[path] = _file_state(path)
79
-
80
- def _record_native_directory(self, writer: MigrationWriter, package: str) -> Path:
81
- """Observe package writes; Django alone chooses and creates the directory.
82
-
83
- basedir has no write hook. Snapshot initializer candidates below every
84
- native imported ancestor, including AppConfig.path's direct-submodule
85
- case, then journal only files changed by the native call. Do not select
86
- a destination from these candidates or substitute a source pathfinder.
87
- """
88
- parts = package.split(".")
89
- candidates: list[tuple[str, Path, list[str]]] = []
90
- config = apps.get_app_config(writer.migration.app_label)
91
- if package.rpartition(".")[0] == config.name:
92
- candidates.append((config.name, Path(config.path), parts[-1:]))
93
- for length in range(1, len(parts) + 1):
94
- prefix = ".".join(parts[:length])
95
- try:
96
- directory = Path(module_dir(importlib.import_module(prefix)))
97
- except ImportError, ValueError:
98
- continue
99
- candidates.append((prefix, directory, parts[length:]))
100
- initializers: dict[Path, tuple[str, tuple[bytes, int] | None]] = {}
101
- for prefix, directory, suffix in candidates:
102
- for part in ("", *suffix):
103
- if part:
104
- prefix += "." + part
105
- directory /= part
106
- path = (directory / "__init__.py").resolve()
107
- initializers.setdefault(path, (prefix, _file_state(path)))
108
- try:
109
- directory = Path(writer.basedir).resolve()
110
- finally:
111
- for path, (prefix, original) in initializers.items():
112
- if _file_state(path) != original:
113
- self._originals.setdefault(path, original)
114
- self._migration_packages[prefix] = path.parent
115
- importlib.invalidate_caches()
116
- self._migration_packages[package] = directory
117
- return directory
118
-
119
- def _author(self, *app_labels: str, **options: Any) -> str | None:
16
+ def handle(self, *app_labels: str, **options: Any) -> Any:
120
17
  require_serving_mode()
121
- name = options.get("name")
122
- if name and not name.isidentifier():
123
- return super().handle(*app_labels, **options)
124
- for label in app_labels:
125
- try:
126
- apps.get_app_config(label)
127
- except LookupError:
128
- return super().handle(*app_labels, **options)
129
- labels = history_labels()
130
- loader = MigrationLoader(None, ignore_no_migrations=True)
131
- initialized = frozenset(label for label, _ in loader.disk_migrations)
132
- initial = {
133
- label
134
- for label in labels
135
- if label not in initialized
136
- and (not app_labels or label in app_labels)
137
- and MigrationLoader.migrations_module(label)[0] is not None
138
- and any(apps.get_app_config(label).get_models())
139
- }
140
- selected = set(app_labels) if app_labels else None
141
- new_labels = frozenset[str]()
142
- if initial:
143
- for flag in ("merge", "empty", "update"):
144
- if options.get(flag):
145
- raise CommandError(f"--{flag} is not applicable before initial schema authoring")
146
- self._initial_history = initialized
147
- try:
148
- super().handle(*sorted(initial), **options)
149
- finally:
150
- self._initial_history = None
151
- if options.get("dry_run") or options.get("check_changes"):
152
- return None
153
- # Native writer may have imported a missing initializer as a
154
- # namespace before writing it (including a same-process retry).
155
- _forget_history(self._changed_labels, packages=self._migration_packages)
156
- # Only actual disk nodes created by this native initial phase prove
157
- # first authoring, including native prerequisite expansion.
158
- current = MigrationLoader(None, ignore_no_migrations=True)
159
- new_labels = frozenset(label for label, _ in current.disk_migrations if label not in initialized)
160
- if selected is not None:
161
- selected.update(new_labels)
162
- if options.get("merge"):
163
- return super().handle(*app_labels, **options)
164
- authored = TransitionBinding(labels=labels)
165
- try:
166
- if options.get("dry_run") or options.get("check_changes"):
167
- authored.check(app_labels=selected)
168
- else:
169
- authored.materialize(
170
- apps,
171
- app_labels=selected,
172
- initial_baselines=new_labels,
173
- written_files=self._bound_files,
174
- )
175
- self._changed_labels.update(
176
- declaration["app_label"]
177
- for declaration in authored.declarations
178
- if MigrationLoader.migrations_module(declaration["app_label"])[0] is not None
179
- )
180
- except (RuntimeError, ImproperlyConfigured) as error:
181
- raise CommandError(str(error)) from error
182
18
  return super().handle(*app_labels, **options)
183
-
184
- def write_migration_files(
185
- self,
186
- changes: dict[str, list[Migration]],
187
- update_previous_migration_paths: dict[str, str] | None = None,
188
- ) -> None:
189
- """Preflight every destination before handing serialization to Django."""
190
- if self._initial_history is not None:
191
- existing = sorted(set(changes) & self._initial_history)
192
- if existing:
193
- raise CommandError(
194
- "Initial schema depends on changes to existing apps; "
195
- "author their transitions first: " + ", ".join(existing)
196
- )
197
- destinations = set()
198
- paths = set()
199
- for label, migrations in changes.items():
200
- for migration in migrations:
201
- if update_previous_migration_paths and _metadata(migration, "origin") is not None:
202
- raise CommandError(
203
- "Cannot update immutable authored migration; create a follow-up migration"
204
- )
205
- package, _ = MigrationLoader.migrations_module(label)
206
- if package is None:
207
- raise CommandError(f"Migrations are disabled for app {label!r}")
208
- writer = MigrationWriter(migration, self.include_header)
209
- if not self.dry_run:
210
- directory = self._record_native_directory(writer, package)
211
- self._changed_labels.add(label)
212
- self._remember(directory / writer.filename)
213
- self._remember(directory / "__init__.py")
214
- if update_previous_migration_paths:
215
- self._remember(Path(update_previous_migration_paths[label]))
216
- key = package, writer.filename
217
- if key in destinations:
218
- raise CommandError(f"Multiple migrations target {key!r}")
219
- destinations.add(key)
220
- try:
221
- directory = Path(module_dir(importlib.import_module(package)))
222
- except ModuleNotFoundError as error:
223
- if error.name is None or not (
224
- package == error.name or package.startswith(error.name + ".")
225
- ):
226
- raise
227
- if self.dry_run:
228
- raise CommandError(
229
- f"Read-only authoring cannot create missing migration package {package!r}"
230
- ) from error
231
- continue
232
- path = (directory / writer.filename).resolve()
233
- if path in paths or path.exists():
234
- raise CommandError(f"Refusing to overwrite existing migration {path}")
235
- paths.add(path)
236
- return super().write_migration_files(changes, update_previous_migration_paths)
@@ -6,8 +6,7 @@ from django.core.management.base import BaseCommand, CommandError, CommandParser
6
6
  from django.db import DEFAULT_DB_ALIAS, connections
7
7
 
8
8
  from django_compose.management import require_serving_mode
9
- from django_compose.management.commands.makemigrations import history_labels
10
- from django_compose.migrations import reset_migration_history
9
+ from django_compose.migrations import history_labels, reset_migration_history
11
10
 
12
11
 
13
12
  class Command(BaseCommand):
@@ -193,19 +193,16 @@ class _ImportCalls(ast.NodeVisitor):
193
193
  class MigrationImportReport:
194
194
  """Audit selected native migration sources and local helper bodies offline.
195
195
 
196
- Distribution source files are leaves: installed distributions own their
197
- dependencies. Project and enabled-app helpers are recursively inspected,
198
- including imports inside functions which a RunPython operation may call.
196
+ Installed dependencies outside native migration packages and literal historical
197
+ package anchors are leaves. Project, enabled-app and anchored helpers are
198
+ recursively inspected, including imports inside RunPython callables.
199
199
  """
200
200
 
201
201
  def __init__(self) -> None:
202
202
  self.resolver = SourceResolver(apps.get_app_configs())
203
203
  self.items: list[HistoricalImport] = []
204
204
  self._visited: set[Path] = set()
205
- snapshot = getattr(settings, "COMPOSE_SNAPSHOT", None)
206
- self._transition_packages = {
207
- record["module"].rpartition(".")[0] for record in getattr(snapshot, "transition_records", ())
208
- }
205
+ self._history_helper_packages: set[str] = set()
209
206
 
210
207
  def _edge(self, path: Path, source: ModuleSource) -> HistoricalImport:
211
208
  if source.path is not None and source.path.is_dir() and source.search_locations:
@@ -219,19 +216,18 @@ class MigrationImportReport:
219
216
  return HistoricalImport(path, source.module, providers, "namespace")
220
217
  return HistoricalImport(path, source.module, source.distributions, source.kind)
221
218
 
219
+ def _in_history_package(self, module: str) -> bool:
220
+ return any(
221
+ module == package or module.startswith(package + ".") for package in self._history_helper_packages
222
+ )
223
+
222
224
  def _record(self, path: Path, module: str) -> None:
223
225
  source = self.resolver.resolve(module)
224
226
  self.items.append(self._edge(path, source))
225
227
  if (
226
228
  source.path is not None
227
229
  and source.path.is_file()
228
- and (
229
- source.kind in {"app", "project"}
230
- or any(
231
- module == package or module.startswith(package + ".")
232
- for package in self._transition_packages
233
- )
234
- )
230
+ and (source.kind in {"app", "project"} or self._in_history_package(module))
235
231
  ):
236
232
  self._scan(source.path, module)
237
233
  # Importing a child also executes its parent packages. Inspect local
@@ -243,7 +239,7 @@ class MigrationImportReport:
243
239
  if (
244
240
  parent_source.path is not None
245
241
  and parent_source.path.is_file()
246
- and (parent_source.kind in {"app", "project"} or parent in self._transition_packages)
242
+ and (parent_source.kind in {"app", "project"} or self._in_history_package(parent))
247
243
  ):
248
244
  self._scan(parent_source.path, parent)
249
245
 
@@ -272,14 +268,14 @@ class MigrationImportReport:
272
268
  self.items.append(HistoricalImport(path, module, kind="unresolved", detail=str(error)))
273
269
  return
274
270
  package = module if path.name == "__init__.py" else module.rpartition(".")[0]
275
- # Copied transitions deliberately retain their original relative package.
271
+ # Retained history can explicitly preserve its original relative package.
276
272
  for statement in tree.body:
277
273
  if isinstance(statement, ast.Assign) and any(
278
274
  isinstance(target, ast.Name) and target.id == "__package__" for target in statement.targets
279
275
  ):
280
276
  if isinstance(statement.value, ast.Constant) and isinstance(statement.value.value, str):
281
277
  package = statement.value.value
282
- self._transition_packages.add(package)
278
+ self._history_helper_packages.add(package)
283
279
  try:
284
280
  bindings = _ImportCalls(source, path, package)
285
281
  bindings.visit(tree)
@@ -402,7 +398,12 @@ class MigrationImportReport:
402
398
  def collect(self) -> tuple[HistoricalImport, ...]:
403
399
  """Enumerate selected modules from native settings, never loader objects."""
404
400
  mappings = settings.MIGRATION_MODULES
405
- for config in sorted(apps.get_app_configs(), key=lambda config: config.label):
401
+ configs = sorted(apps.get_app_configs(), key=lambda config: config.label)
402
+ for config in configs:
403
+ module = mappings.get(config.label, config.name + ".migrations")
404
+ if module is not None and self.resolver.resolve(module).search_locations:
405
+ self._history_helper_packages.add(module)
406
+ for config in configs:
406
407
  module = mappings.get(config.label, config.name + ".migrations")
407
408
  if module is None:
408
409
  continue