django-compose 0.1.0.dev5__py3-none-any.whl → 0.1.0.dev7__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.
@@ -25,6 +25,7 @@ from django_compose.autoreload import inputs, report_inputs, write_report
25
25
  MIGRATION_COMMANDS = frozenset(
26
26
  {
27
27
  "makemigrations",
28
+ "adopt_transition",
28
29
  "migrate",
29
30
  "check_migrations",
30
31
  "retire_history",
@@ -0,0 +1,41 @@
1
+ """Append a declared transition origin satisfied by retained native baseline history."""
2
+
3
+ from typing import Any
4
+
5
+ from django.core.exceptions import ImproperlyConfigured
6
+ from django.core.management.base import BaseCommand, CommandError, CommandParser
7
+
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 TransitionBinding
11
+
12
+
13
+ class Command(BaseCommand):
14
+ help = (
15
+ "Attest that the named retained initial is covered by the transition owner's "
16
+ "baseline-satisfaction assertion, and append a sealed native no-op origin."
17
+ )
18
+ requires_system_checks: list[str] = []
19
+
20
+ def add_arguments(self, parser: CommandParser) -> None:
21
+ parser.add_argument("origin", metavar="DECLARING_APP:NAME")
22
+ parser.add_argument("--baseline", required=True, metavar="APP_LABEL.MIGRATION_NAME")
23
+ parser.add_argument("--dry-run", action="store_true")
24
+
25
+ def handle(self, *args: Any, **options: Any) -> None:
26
+ require_serving_mode()
27
+ label, separator, name = options["baseline"].partition(".")
28
+ if not separator or not label or not name:
29
+ raise CommandError("--baseline must name APP_LABEL.MIGRATION_NAME")
30
+ origin = options["origin"]
31
+ try:
32
+ paths = TransitionBinding(labels=history_labels()).adopt(
33
+ origin, (label, name), dry_run=options["dry_run"]
34
+ )
35
+ except (RuntimeError, ImproperlyConfigured) as error:
36
+ raise CommandError(str(error)) from error
37
+ if not paths:
38
+ self.stdout.write(f"Already adopted {origin} against {options['baseline']}")
39
+ else:
40
+ action = "Would author" if options["dry_run"] else "Authored"
41
+ self.stdout.write(f"{action} {paths[0]}")
@@ -3,6 +3,7 @@
3
3
  from __future__ import annotations
4
4
 
5
5
  import importlib
6
+ import stat
6
7
  from pathlib import Path
7
8
  from typing import Any
8
9
 
@@ -16,15 +17,21 @@ from django.db.migrations.loader import MigrationLoader
16
17
  from django.db.migrations.writer import MigrationWriter
17
18
  from django.utils.module_loading import module_dir
18
19
 
20
+ from django_compose.artifacts import atomic_write
19
21
  from django_compose.management import require_serving_mode
20
22
  from django_compose.migrations import (
21
23
  DropGuardAutodetector,
22
24
  TransitionBinding,
25
+ _forget_history,
23
26
  _metadata,
24
27
  )
25
28
  from django_compose.serving import read_receipt
26
29
 
27
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
+
28
35
  def history_labels() -> tuple[str, ...]:
29
36
  """Read the compiler receipt without invoking composition."""
30
37
  receipt = read_receipt(Path(settings.COMPOSE_OUTPUT_DIR))
@@ -39,7 +46,77 @@ class Command(NativeCommand):
39
46
  autodetector = DropGuardAutodetector
40
47
  _initial_history: frozenset[str] | None = None
41
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
+
42
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:
43
120
  require_serving_mode()
44
121
  name = options.get("name")
45
122
  if name and not name.isidentifier():
@@ -61,6 +138,7 @@ class Command(NativeCommand):
61
138
  and any(apps.get_app_config(label).get_models())
62
139
  }
63
140
  selected = set(app_labels) if app_labels else None
141
+ new_labels = frozenset[str]()
64
142
  if initial:
65
143
  for flag in ("merge", "empty", "update"):
66
144
  if options.get(flag):
@@ -72,10 +150,15 @@ class Command(NativeCommand):
72
150
  self._initial_history = None
73
151
  if options.get("dry_run") or options.get("check_changes"):
74
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)
75
160
  if selected is not None:
76
- # Native dependency expansion can initialize other fresh apps.
77
- current = MigrationLoader(None, ignore_no_migrations=True)
78
- selected.update(label for label, _ in current.disk_migrations if label not in initialized)
161
+ selected.update(new_labels)
79
162
  if options.get("merge"):
80
163
  return super().handle(*app_labels, **options)
81
164
  authored = TransitionBinding(labels=labels)
@@ -83,7 +166,17 @@ class Command(NativeCommand):
83
166
  if options.get("dry_run") or options.get("check_changes"):
84
167
  authored.check(app_labels=selected)
85
168
  else:
86
- authored.materialize(apps, app_labels=selected)
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
+ )
87
180
  except (RuntimeError, ImproperlyConfigured) as error:
88
181
  raise CommandError(str(error)) from error
89
182
  return super().handle(*app_labels, **options)
@@ -113,6 +206,13 @@ class Command(NativeCommand):
113
206
  if package is None:
114
207
  raise CommandError(f"Migrations are disabled for app {label!r}")
115
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]))
116
216
  key = package, writer.filename
117
217
  if key in destinations:
118
218
  raise CommandError(f"Multiple migrations target {key!r}")
@@ -13,7 +13,7 @@ import importlib.util
13
13
  import stat
14
14
  import sys
15
15
  from collections.abc import Callable, Iterable, Iterator, Mapping
16
- from dataclasses import dataclass
16
+ from dataclasses import dataclass, replace
17
17
  from pathlib import Path
18
18
  from typing import Any, cast
19
19
 
@@ -103,7 +103,7 @@ def _directory(label: str, *, missing: bool = False) -> Path:
103
103
  module = importlib.import_module(package)
104
104
  if not hasattr(module, "__path__"):
105
105
  raise ValueError("Migrations must be a Python package")
106
- return Path(module_dir(module))
106
+ return Path(module_dir(module)).resolve()
107
107
  except ModuleNotFoundError as error:
108
108
  if (
109
109
  not missing
@@ -114,12 +114,12 @@ def _directory(label: str, *, missing: bool = False) -> Path:
114
114
  parent, _, name = package.rpartition(".")
115
115
  config = global_apps.get_app_config(label)
116
116
  if parent == config.name:
117
- return Path(config.path) / name
117
+ return (Path(config.path) / name).resolve()
118
118
  try:
119
119
  parent_module = importlib.import_module(parent)
120
120
  if not hasattr(parent_module, "__path__"):
121
121
  raise ValueError("Migration parent must be a Python package")
122
- return Path(module_dir(parent_module)) / name
122
+ return (Path(module_dir(parent_module)) / name).resolve()
123
123
  except (ImportError, ValueError) as parent_error:
124
124
  raise ImproperlyConfigured(
125
125
  f"Initialize importable migration parent package {parent!r}"
@@ -153,6 +153,9 @@ class TransitionPlan:
153
153
  dependencies: tuple[Node, ...]
154
154
  run_before: tuple[Node, ...]
155
155
  source_package: str
156
+ initial_baseline: bool = False
157
+ adopted_baseline: Node | None = None
158
+ adopted_baseline_sha256: str | None = None
156
159
 
157
160
 
158
161
  @dataclass(frozen=True)
@@ -164,6 +167,49 @@ class _Source:
164
167
  text: str
165
168
  digest: str
166
169
  package: str
170
+ initial_baseline: bool
171
+
172
+ def applies_to(self, state: ProjectState) -> bool:
173
+ try:
174
+ applies = self.guard(state.clone())
175
+ except Exception as error:
176
+ raise RuntimeError(f"{self.origin}: applies(project_state) failed") from error
177
+ if not isinstance(applies, bool):
178
+ raise RuntimeError(f"{self.origin}: applies must return bool")
179
+ return applies
180
+
181
+ def satisfied(self) -> _Source:
182
+ """Omit source operations and lifecycle overrides through native Django."""
183
+ migration = Migration(self.migration.name, self.migration.app_label)
184
+ cast(list[Node], migration.dependencies).extend(self.migration.dependencies)
185
+ cast(list[Node], migration.run_before).extend(self.migration.run_before)
186
+ return replace(self, migration=migration)
187
+
188
+ def plan(
189
+ self,
190
+ path: Path,
191
+ *,
192
+ initial_baseline: bool = False,
193
+ adopted_baseline: Node | None = None,
194
+ adopted_baseline_sha256: str | None = None,
195
+ ) -> TransitionPlan:
196
+ if path.exists():
197
+ raise RuntimeError(f"{self.origin}: migration destination already exists: {path}")
198
+ return TransitionPlan(
199
+ self.origin,
200
+ self.migration.app_label,
201
+ self.migration.name,
202
+ self.path,
203
+ self.text,
204
+ path,
205
+ self.digest,
206
+ tuple(self.migration.dependencies),
207
+ tuple(self.migration.run_before),
208
+ self.package,
209
+ initial_baseline,
210
+ adopted_baseline,
211
+ adopted_baseline_sha256,
212
+ )
167
213
 
168
214
 
169
215
  class _BindingLoader(MigrationLoader):
@@ -171,7 +217,10 @@ class _BindingLoader(MigrationLoader):
171
217
 
172
218
  def __init__(self, pending: Mapping[Node, _Source]) -> None:
173
219
  self.pending = pending
174
- super().__init__(None, ignore_no_migrations=True)
220
+ try:
221
+ super().__init__(None, ignore_no_migrations=True)
222
+ except Exception as error:
223
+ raise RuntimeError(f"authored migration graph is invalid: {error}") from error
175
224
 
176
225
  def load_disk(self) -> None:
177
226
  super().load_disk()
@@ -208,8 +257,10 @@ class TransitionBinding:
208
257
  """Bind declared migrations to host leaves without connecting to a database.
209
258
 
210
259
  Origins and snapshots are immutable, including after declaration removal.
211
- A false guard never establishes that a data operation has run. Completed
212
- transitions must remain in native history, including native squash chains.
260
+ A false guard never establishes that a data operation has run. Only an
261
+ explicit declaration can assert baseline satisfaction, through first
262
+ authoring or a named retained-initial adoption. Origins remain in native
263
+ history and squash chains.
213
264
  """
214
265
 
215
266
  def __init__(
@@ -309,7 +360,16 @@ class TransitionBinding:
309
360
  if len(leaves) == 1 and leaves[0] not in migration.dependencies:
310
361
  cast(list[Node], migration.dependencies).append(leaves[0])
311
362
  package = (module.__spec__.parent if module.__spec__ else None) or module_name.rpartition(".")[0]
312
- pending[key] = _Source(origin, migration, guard, path, data.decode("utf-8"), digest, package)
363
+ pending[key] = _Source(
364
+ origin,
365
+ migration,
366
+ guard,
367
+ path,
368
+ data.decode("utf-8"),
369
+ digest,
370
+ package,
371
+ declaration.get("initial_baseline") == "satisfied",
372
+ )
313
373
  return pending
314
374
 
315
375
  def plan(
@@ -319,14 +379,12 @@ class TransitionBinding:
319
379
  defer_drop_check: bool = False,
320
380
  app_labels: Iterable[str] | None = None,
321
381
  allow_missing_packages: bool = False,
382
+ initial_baselines: frozenset[str] = frozenset(),
322
383
  ) -> tuple[TransitionPlan, ...]:
323
384
  """Validate the complete graph and selected prerequisite closure, without writes."""
324
385
  existing = MigrationLoader(None, ignore_no_migrations=True)
325
386
  pending = self._pending(existing)
326
- try:
327
- loader = _BindingLoader(pending)
328
- except Exception as error:
329
- raise RuntimeError(f"authored migration graph is invalid: {error}") from error
387
+ loader = _BindingLoader(pending)
330
388
  selected = None if app_labels is None else set(app_labels)
331
389
  ordered = dict.fromkeys(
332
390
  key
@@ -348,13 +406,15 @@ class TransitionBinding:
348
406
  continue
349
407
  source = pending[key]
350
408
  state = loader.project_state(nodes=[key], at_end=False)
351
- try:
352
- applies = source.guard(state.clone())
353
- except Exception as error:
354
- raise RuntimeError(f"{source.origin}: applies(project_state) failed") from error
355
- if not isinstance(applies, bool):
356
- raise RuntimeError(f"{source.origin}: applies must return bool")
357
- if not applies:
409
+ applies = source.applies_to(state)
410
+ baseline = not applies and source.initial_baseline and key[0] in initial_baselines
411
+ if baseline:
412
+ # A native empty migration also omits source-class lifecycle
413
+ # overrides. Replace the graph owner before downstream state.
414
+ pending[key] = source = source.satisfied()
415
+ loader.disk_migrations[key] = source.migration
416
+ loader.graph.nodes[key] = source.migration
417
+ elif not applies:
358
418
  raise RuntimeError(
359
419
  f"{source.origin}: false guard cannot prove a data transition completed; "
360
420
  "retain native history or a complete replacement baseline"
@@ -364,23 +424,10 @@ class TransitionBinding:
364
424
  except Exception as error:
365
425
  raise RuntimeError(f"{source.origin}: invalid migration state transition") from error
366
426
  path = _directory(key[0], missing=allow_missing_packages) / f"{key[1]}.py"
367
- if path.exists() or path.resolve() in destinations:
427
+ if path.resolve() in destinations:
368
428
  raise RuntimeError(f"{source.origin}: migration destination already exists: {path}")
369
429
  destinations.add(path.resolve())
370
- result.append(
371
- TransitionPlan(
372
- source.origin,
373
- key[0],
374
- key[1],
375
- source.path,
376
- source.text,
377
- path,
378
- source.digest,
379
- tuple(source.migration.dependencies),
380
- tuple(source.migration.run_before),
381
- source.package,
382
- )
383
- )
430
+ result.append(source.plan(path, initial_baseline=baseline))
384
431
  if apps is not None and not defer_drop_check:
385
432
  # This check compares state only. DropGuardAutodetector's row proofs
386
433
  # belong exclusively to explicit native authoring and migrate.
@@ -393,6 +440,110 @@ class TransitionBinding:
393
440
  _shared_table_drops(before, after, changes)
394
441
  return tuple(result)
395
442
 
443
+ def adoption_plan(self, origin: str, baseline: Node) -> TransitionPlan | None:
444
+ """Plan one declared origin satisfied by an explicit retained initial.
445
+
446
+ The caller attests that this retained initial is covered by the owner's
447
+ satisfaction assertion; native structure and guards do not prove prior
448
+ data work. The anchor must remain an active native initial and ancestor of
449
+ the unique target leaf. A matching sealed adoption is an immutable,
450
+ idempotent result even after later native descendants are authored.
451
+ """
452
+ declaration = next(
453
+ (
454
+ record
455
+ for record in self.declarations
456
+ if f"{record['declaring_app']}:{record['name']}" == origin
457
+ ),
458
+ None,
459
+ )
460
+ if declaration is None:
461
+ raise RuntimeError(f"{origin}: unknown selected transition origin")
462
+ snap = getattr(settings, "COMPOSE_SNAPSHOT", None)
463
+ frozen = next(
464
+ (
465
+ record
466
+ for record in getattr(snap, "transition_records", ())
467
+ if f"{record['declaring_app']}:{record['name']}" == origin
468
+ ),
469
+ None,
470
+ )
471
+ frozen_digest = dict(getattr(snap, "transitions", ())).get(origin)
472
+ if declaration != frozen or frozen_digest is None:
473
+ raise RuntimeError(f"{origin}: selected declaration must match the frozen snapshot")
474
+ if declaration.get("initial_baseline") != "satisfied":
475
+ raise RuntimeError(f"{origin}: adoption requires initial_baseline='satisfied'")
476
+ baseline = _node(baseline, origin, "baseline")
477
+ label = declaration["app_label"]
478
+ if baseline[0] != label:
479
+ raise RuntimeError(f"{origin}: baseline must target app {label!r}")
480
+ # Scope before loading source modules. Other pending declarations are
481
+ # neither prerequisites inferred by this action nor implicit adoptions.
482
+ selected = TransitionBinding(labels=self.labels, declarations=(declaration,))
483
+ existing = MigrationLoader(None, ignore_no_migrations=True)
484
+ if baseline not in existing.disk_migrations or baseline not in existing.graph.nodes:
485
+ raise RuntimeError(f"{origin}: baseline must be retained native disk and active graph history")
486
+ native = existing.disk_migrations[baseline]
487
+ if native.initial is not True and not (
488
+ native.initial is None and baseline in existing.graph.root_nodes(label)
489
+ ):
490
+ raise RuntimeError(f"{origin}: baseline must be a native initial migration")
491
+ leaves = existing.graph.leaf_nodes(label)
492
+ if len(leaves) != 1:
493
+ raise RuntimeError(f"{origin}: adoption requires one native target leaf")
494
+ if baseline not in existing.graph.forwards_plan(leaves[0]):
495
+ raise RuntimeError(f"{origin}: baseline is not an ancestor of the native target leaf")
496
+ baseline_digest = hashlib.sha256((_directory(label) / f"{baseline[1]}.py").read_bytes()).hexdigest()
497
+ pending = selected._pending(existing)
498
+ history = selected._history(existing)
499
+ if origin in history:
500
+ key, migration = history[origin]
501
+ if (
502
+ key not in existing.graph.nodes
503
+ or baseline not in existing.graph.forwards_plan(key)
504
+ or _metadata(migration, "source_sha256") != frozen_digest
505
+ or _metadata(migration, "initial_baseline") != "satisfied"
506
+ or _metadata(migration, "adopted_baseline") != baseline
507
+ or _metadata(migration, "adopted_baseline_sha256") != baseline_digest
508
+ or migration.operations
509
+ or type(migration).apply is not Migration.apply
510
+ or type(migration).mutate_state is not Migration.mutate_state
511
+ ):
512
+ raise RuntimeError(f"{origin}: existing origin is not the matching sealed baseline adoption")
513
+ return None
514
+ key = label, declaration["name"]
515
+ source = pending[key]
516
+ if source.digest != frozen_digest:
517
+ raise RuntimeError(f"{origin}: source digest does not match the frozen snapshot")
518
+ if source.applies_to(existing.project_state(nodes=[baseline])):
519
+ raise RuntimeError(f"{origin}: true guard at baseline; author the ordinary transition")
520
+ loader = _BindingLoader(pending)
521
+ relevant = {node[0] for node in loader.graph.forwards_plan(key)}
522
+ conflicts = {app: names for app, names in loader.detect_conflicts().items() if app in relevant}
523
+ if conflicts:
524
+ raise RuntimeError(f"multiple migration leaves: {conflicts}")
525
+ if source.applies_to(loader.project_state(nodes=[key], at_end=False)):
526
+ raise RuntimeError(f"{origin}: true guard at binding state; author the ordinary transition")
527
+ return source.satisfied().plan(
528
+ _directory(label) / f"{key[1]}.py",
529
+ initial_baseline=True,
530
+ adopted_baseline=baseline,
531
+ adopted_baseline_sha256=baseline_digest,
532
+ )
533
+
534
+ def adopt(self, origin: str, baseline: Node, *, dry_run: bool = False) -> tuple[Path, ...]:
535
+ """Append one sealed native empty origin without changing retained history.
536
+
537
+ Dry-run validates the same inputs and returns the prospective path.
538
+ An exact previously sealed adoption returns no paths and writes nothing.
539
+ """
540
+ plan = self.adoption_plan(origin, baseline)
541
+ if plan is None:
542
+ return ()
543
+ if dry_run:
544
+ return (plan.output_path,)
545
+ return self._materialize((plan,), lambda: self.adoption_plan(origin, baseline))
546
+
396
547
  def check(self, app_labels: Iterable[str] | None = None) -> None:
397
548
  """Refuse unmaterialized declarations without creating packages or history."""
398
549
  pending = self.plan(app_labels=app_labels)
@@ -456,38 +607,95 @@ class TransitionBinding:
456
607
  body.decode()
457
608
  + MATERIALIZED_FOOTER
458
609
  + "\n"
610
+ + (
611
+ "from django.db.migrations import Migration as _ComposeInitialBaselineMigration\n"
612
+ "class Migration(_ComposeInitialBaselineMigration):\n"
613
+ " operations = []\n"
614
+ if plan.initial_baseline
615
+ else ""
616
+ )
459
617
  + f"Migration.dependencies = {list(plan.dependencies)!r}\n"
460
618
  + f"Migration.run_before = {list(plan.run_before)!r}\n"
461
619
  + f"Migration.compose_origin = {plan.origin!r}\n"
462
620
  + f"Migration.compose_source_sha256 = {plan.source_sha256!r}\n"
463
621
  + f"Migration.compose_body_sha256 = {body_digest!r}\n"
622
+ + ("Migration.compose_initial_baseline = 'satisfied'\n" if plan.initial_baseline else "")
623
+ + (
624
+ f"Migration.compose_adopted_baseline = {plan.adopted_baseline!r}\n"
625
+ f"Migration.compose_adopted_baseline_sha256 = {plan.adopted_baseline_sha256!r}\n"
626
+ if plan.adopted_baseline is not None
627
+ else ""
628
+ )
464
629
  ).encode()
465
630
  return payload + _SEAL_PREFIX + repr(hashlib.sha256(payload).hexdigest()).encode() + b"\n"
466
631
 
467
- def materialize(self, apps: Apps, app_labels: Iterable[str] | None = None) -> tuple[Path, ...]:
468
- """Snapshot all validated sources at the explicit native authoring boundary."""
469
- plans = self.plan(apps=apps, app_labels=app_labels, allow_missing_packages=True)
632
+ def materialize(
633
+ self,
634
+ apps: Apps,
635
+ app_labels: Iterable[str] | None = None,
636
+ *,
637
+ initial_baselines: frozenset[str] = frozenset(),
638
+ written_files: list[Path] | None = None,
639
+ ) -> tuple[Path, ...]:
640
+ """Snapshot sources, optionally satisfying declared first-authoring baselines.
641
+
642
+ initial_baselines is the command's exact newly initialized disk-label
643
+ delta, never inferred from initial-looking files or database contents.
644
+ written_files tracks exclusive destinations for an enclosing native
645
+ authoring rollback, including a write that raises after publication.
646
+ """
647
+ plans = self.plan(
648
+ apps=apps,
649
+ app_labels=app_labels,
650
+ allow_missing_packages=True,
651
+ initial_baselines=initial_baselines,
652
+ )
653
+ return self._materialize(
654
+ plans, lambda: self.plan(apps=apps, app_labels=app_labels), written_files=written_files
655
+ )
656
+
657
+ def _materialize(
658
+ self,
659
+ plans: tuple[TransitionPlan, ...],
660
+ validate: Callable[[], object],
661
+ *,
662
+ written_files: list[Path] | None = None,
663
+ ) -> tuple[Path, ...]:
664
+ """Publish validated native origins through one exclusive rollback owner."""
470
665
  rendered = [(plan, self._render(plan)) for plan in plans]
471
- for label in dict.fromkeys(plan.app_label for plan in plans):
472
- directory = Path(MigrationWriter(Migration("_package", label)).basedir)
473
- directory.mkdir(parents=True, exist_ok=True)
474
- if not (directory / "__init__.py").exists():
475
- atomic_write(directory / "__init__.py", b"", exclusive=True)
476
- written = []
666
+ packages = [
667
+ directory / "__init__.py"
668
+ for label in dict.fromkeys(plan.app_label for plan in plans)
669
+ for directory in (_directory(label, missing=True),)
670
+ if not (directory / "__init__.py").exists()
671
+ ]
672
+ written: list[Path] = []
477
673
  try:
478
- for plan, content in rendered:
479
- if plan.output_path.exists():
480
- raise RuntimeError(f"Migration destination appeared during authoring: {plan.output_path}")
481
- atomic_write(plan.output_path, content, exclusive=True)
482
- written.append(plan.output_path)
674
+ for path, content in [
675
+ *((path, b"") for path in packages),
676
+ *((plan.output_path, content) for plan, content in rendered),
677
+ ]:
678
+ if path.exists():
679
+ raise RuntimeError(f"Migration destination appeared during authoring: {path}")
680
+ written.append(path)
681
+ if written_files is not None:
682
+ written_files.append(path)
683
+ try:
684
+ atomic_write(path, content, exclusive=True)
685
+ except FileExistsError:
686
+ # Exclusive publication lost a race; that file is not ours.
687
+ written.pop()
688
+ if written_files is not None:
689
+ written_files.pop()
690
+ raise
483
691
  importlib.invalidate_caches()
484
- self.plan(apps=apps, app_labels=app_labels)
692
+ validate()
485
693
  except BaseException:
486
694
  for path in written:
487
695
  path.unlink(missing_ok=True)
488
696
  _forget_history({plan.app_label for plan in plans})
489
697
  raise
490
- return tuple(written)
698
+ return tuple(plan.output_path for plan in plans)
491
699
 
492
700
 
493
701
  def _storage_identifier(connection: BaseDatabaseWrapper, identifier: str) -> tuple[str, str]:
@@ -794,13 +1002,21 @@ class DropGuardAutodetector(MigrationAutodetector):
794
1002
  )
795
1003
 
796
1004
 
797
- def _forget_history(labels: Iterable[str]) -> None:
798
- prefixes = [MigrationLoader.migrations_module(label)[0] for label in labels]
1005
+ def _forget_history(labels: Iterable[str], *, packages: Mapping[str, Path] | None = None) -> None:
1006
+ # Native writer observation can retain paths even when restored package
1007
+ # initializers no longer import successfully. Do not execute them to clean
1008
+ # their import caches, or leave newly authored ancestor packages cached.
1009
+ directories = dict(packages or {})
1010
+ for label in labels:
1011
+ package = MigrationLoader.migrations_module(label)[0]
1012
+ if package is not None and package not in directories:
1013
+ directories[package] = _directory(label, missing=True)
1014
+ prefixes = tuple(directories)
799
1015
  for name in tuple(sys.modules):
800
1016
  if any(prefix and (name == prefix or name.startswith(prefix + ".")) for prefix in prefixes):
801
1017
  sys.modules.pop(name, None)
802
- for label in labels:
803
- for bytecode in (_directory(label) / "__pycache__").glob("*.pyc"):
1018
+ for directory in set(directories.values()):
1019
+ for bytecode in (directory / "__pycache__").glob("*.pyc"):
804
1020
  bytecode.unlink()
805
1021
  importlib.invalidate_caches()
806
1022
 
@@ -185,15 +185,15 @@ def transition_declarations(source: Any) -> tuple[Mapping[str, str], ...]:
185
185
  declarations = []
186
186
  origins: set[str] = set()
187
187
  for declaration in source:
188
- if not isinstance(declaration, Mapping) or set(declaration) != {
189
- "declaring_app",
190
- "name",
191
- "app_label",
192
- "module",
188
+ required = {"declaring_app", "name", "app_label", "module"}
189
+ if not isinstance(declaration, Mapping) or not required <= set(declaration) <= required | {
190
+ "initial_baseline"
193
191
  }:
194
192
  raise ImproperlyConfigured(f"Invalid transition declaration: {declaration!r}")
195
193
  if not all(isinstance(value, str) and value for value in declaration.values()):
196
194
  raise ImproperlyConfigured(f"Invalid transition declaration: {declaration!r}")
195
+ if "initial_baseline" in declaration and declaration["initial_baseline"] != "satisfied":
196
+ raise ImproperlyConfigured("Transition initial_baseline must be 'satisfied' or absent")
197
197
  origin = f"{declaration['declaring_app']}:{declaration['name']}"
198
198
  name = declaration["name"]
199
199
  if not ("_" + name).isidentifier() or name != name.lower() or name.startswith("_"):
@@ -208,7 +208,14 @@ def transition_declarations(source: Any) -> tuple[Mapping[str, str], ...]:
208
208
  return tuple(declarations)
209
209
 
210
210
 
211
- def _default_transitions(entries: tuple[Entry, ...]) -> tuple[Mapping[str, str], ...]:
211
+ def discover_transitions(entries: Iterable[Entry]) -> tuple[Mapping[str, str], ...]:
212
+ """Read immutable default records in selected-app and filename order.
213
+
214
+ Pass resolved identities, normally Closure.app_entries. Discovery reports
215
+ watched paths but imports no apps or migration modules. Settings adapters
216
+ can copy and annotate owner-declared records before supplying an explicit
217
+ COMPOSE_TRANSITION_SOURCE; snapshot's default uses this same owner.
218
+ """
212
219
  records = []
213
220
  for entry in entries:
214
221
  directory = Path(entry.path) / "compose_migrations"
@@ -314,7 +321,7 @@ def snapshot(
314
321
  )
315
322
  resolver = SourceResolver(normalized)
316
323
  if transitions is None and "COMPOSE_TRANSITION_SOURCE" not in values:
317
- records = _default_transitions(normalized)
324
+ records = discover_transitions(normalized)
318
325
  else:
319
326
  records = transition_declarations(
320
327
  values.get("COMPOSE_TRANSITION_SOURCE", ()) if transitions is None else transitions
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.5
2
2
  Name: django-compose
3
- Version: 0.1.0.dev5
3
+ Version: 0.1.0.dev7
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
@@ -12,30 +12,31 @@ django_compose/conf.py,sha256=Y6wEhxZh2gT_XjooEjc_5Ry0MOEIaPH4yCOf6UlZo-U,15838
12
12
  django_compose/declarations.py,sha256=JJ09haPmgua4h2P9T8-fMos3CWHdQMpWkw15gXlL1nM,6900
13
13
  django_compose/history.py,sha256=-D9jT-2EvKH6HDo3EfDeTD6lxUirgQOxeDh4cJKLoAU,1291
14
14
  django_compose/migration_imports.py,sha256=vyg8NdUCl977HrdfBkz642x0ra_btaRdCqZEfQs4V2o,22011
15
- django_compose/migrations.py,sha256=oHkVHiYk-iq64cDio6zDSBNMEFwZax2Cfk8UommYzxw,49469
15
+ django_compose/migrations.py,sha256=pY9E0on69y-JdGoZW4k52ksrXLhvkimkl9gzeG9_0S8,59663
16
16
  django_compose/model_composition.py,sha256=470nEltv-x6JYl_AWaQxK6cUOnOQe7e63y-Ehi_WrnM,16547
17
17
  django_compose/models.py,sha256=hM0ed-sotXh2vdI0zNESYnX_qS_39_IHwAk4jZnpYXU,2512
18
18
  django_compose/provision.py,sha256=ufGuc1jesX6gid-s1a-rNwQbKvKcgnOjvSPwVdUrHF4,15321
19
19
  django_compose/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
20
20
  django_compose/rendering.py,sha256=1OFZU7lLMO2rD4S9K1-g8wvdn8RKBnUuQTFPHnDWsHY,3647
21
21
  django_compose/serving.py,sha256=FoS3TNNpgPGLpfCHtGrW0JVJVT9DyI7sxJ5U4x0oVLU,15498
22
- django_compose/snapshot.py,sha256=115gi4SRkYUu2JFf_GC8kORPUWGy9z0BGlTyhNZxZYg,17730
22
+ django_compose/snapshot.py,sha256=J4a3eKa2V6cIIKXfvLiiqe6lWENbDCAKIV5CJC5Fjnc,18344
23
23
  django_compose/sources.py,sha256=fLBGSHtAInnoTM1Z2Wdt74P_cbLUUP4MWD1l2uS_zAI,6629
24
24
  django_compose/typing.py,sha256=13pd3JfIoBV8v4AHK-QgAg9J8C4Miz_D0dmHFEwUG4I,36089
25
25
  django_compose/urls.py,sha256=PZLa-pGe5JgzpUgu9sOEUbO2FgLGPkZZSOhRD1ZLgUk,2969
26
- django_compose/management/__init__.py,sha256=wBX58M8MHUEvl9M57wVNNDAq4lsCSLjPtM3Copabs2w,8724
26
+ django_compose/management/__init__.py,sha256=n0qu5vjAVdDBTGzUE0oUBYkQ-oaZtOHpIkG9iU5OBA4,8752
27
27
  django_compose/management/commands/__init__.py,sha256=_mgOwmIp5-GhgJd6tY4Wc89G0EJDiHF9tYo8F63ytm8,40
28
+ django_compose/management/commands/adopt_transition.py,sha256=MQYLfKL71vC4hFmVNu34VK99UBTSJS5qioB7lS4m2qc,1847
28
29
  django_compose/management/commands/check_migrations.py,sha256=CIGGQCq-01Cm0_ZR7Exl4EtM_-qnFfhzfMsLxhl8P5A,2918
29
30
  django_compose/management/commands/compose.py,sha256=UuNjIgNwYOYE_1aKIcEvh3C1fMjP9tdN_-SDDwVQjIc,1860
30
- django_compose/management/commands/makemigrations.py,sha256=CliPK4u1SRK-_Ww0zuG8M_FWCl_ku4Aje7czW1Y8hjg,6087
31
+ django_compose/management/commands/makemigrations.py,sha256=GIoz23DbHDArWQqR9BDp_dOAQf3YLdus5MUp6HDvGxs,10809
31
32
  django_compose/management/commands/migrate.py,sha256=_MkiQRjQRwIr9dEUnKk4WEjLgz5FTH_Tmn6ZkKHgOMA,589
32
33
  django_compose/management/commands/provision.py,sha256=4GTPwH1Pp1V_YkztDZxeHuyAjDUHjZxhkdvFlrgDBfU,1035
33
34
  django_compose/management/commands/reset_migration_history.py,sha256=PD3baeH1jQHIXXLaEYyxZXfhVYfJLzTXnv-XF1ySULQ,1489
34
35
  django_compose/management/commands/retire_history.py,sha256=3RV1-w5Niij0svr0gB_gAjBgskxCYtdg5pPfsGN287s,886
35
- django_compose-0.1.0.dev5.dist-info/METADATA,sha256=Pc9V5woPKK6K8UEae8GhJ-jq7rcjA8aGAurtGFfCvzM,3939
36
- django_compose-0.1.0.dev5.dist-info/WHEEL,sha256=2iZrJkDIkeDh0k9SikKMqFuRP-ua6mb4Ir1AsER4BEw,87
37
- django_compose-0.1.0.dev5.dist-info/entry_points.txt,sha256=-Iw1c8YAegCC53YCKgPXjIZn4aPS3MmEKbcMrCpUMFU,59
38
- django_compose-0.1.0.dev5.dist-info/licenses/COPYING,sha256=jOtLnuWt7d5Hsx6XXB2QxzrSe2sWWh3NgMfFRetluQM,35147
39
- django_compose-0.1.0.dev5.dist-info/licenses/LICENSE,sha256=46mU2C5kSwOnkqkw9XQAJlhBL2JAf1_uCD8lVcXyMRg,7652
40
- django_compose-0.1.0.dev5.dist-info/licenses/NOTICE,sha256=C4fEGI9_-a1GCPfAH9bC0ZvmZFS71b9Z4v6rjrT5dxA,450
41
- django_compose-0.1.0.dev5.dist-info/RECORD,,
36
+ django_compose-0.1.0.dev7.dist-info/METADATA,sha256=0ydNLWwjWVc0Loyg79zZTaqSFiwLQVvcD7QpffvGIi8,3939
37
+ django_compose-0.1.0.dev7.dist-info/WHEEL,sha256=2iZrJkDIkeDh0k9SikKMqFuRP-ua6mb4Ir1AsER4BEw,87
38
+ django_compose-0.1.0.dev7.dist-info/entry_points.txt,sha256=-Iw1c8YAegCC53YCKgPXjIZn4aPS3MmEKbcMrCpUMFU,59
39
+ django_compose-0.1.0.dev7.dist-info/licenses/COPYING,sha256=jOtLnuWt7d5Hsx6XXB2QxzrSe2sWWh3NgMfFRetluQM,35147
40
+ django_compose-0.1.0.dev7.dist-info/licenses/LICENSE,sha256=46mU2C5kSwOnkqkw9XQAJlhBL2JAf1_uCD8lVcXyMRg,7652
41
+ django_compose-0.1.0.dev7.dist-info/licenses/NOTICE,sha256=C4fEGI9_-a1GCPfAH9bC0ZvmZFS71b9Z4v6rjrT5dxA,450
42
+ django_compose-0.1.0.dev7.dist-info/RECORD,,