django-compose 0.1.0.dev6__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]}")
@@ -154,6 +154,8 @@ class TransitionPlan:
154
154
  run_before: tuple[Node, ...]
155
155
  source_package: str
156
156
  initial_baseline: bool = False
157
+ adopted_baseline: Node | None = None
158
+ adopted_baseline_sha256: str | None = None
157
159
 
158
160
 
159
161
  @dataclass(frozen=True)
@@ -167,13 +169,58 @@ class _Source:
167
169
  package: str
168
170
  initial_baseline: bool
169
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
+ )
213
+
170
214
 
171
215
  class _BindingLoader(MigrationLoader):
172
216
  """Supply pending native Migration objects at Django's disk-loading hook."""
173
217
 
174
218
  def __init__(self, pending: Mapping[Node, _Source]) -> None:
175
219
  self.pending = pending
176
- 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
177
224
 
178
225
  def load_disk(self) -> None:
179
226
  super().load_disk()
@@ -211,8 +258,9 @@ class TransitionBinding:
211
258
 
212
259
  Origins and snapshots are immutable, including after declaration removal.
213
260
  A false guard never establishes that a data operation has run. Only an
214
- explicit declaration can assert satisfaction by a newly authored initial
215
- baseline. Completed transitions remain in native history and squash chains.
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.
216
264
  """
217
265
 
218
266
  def __init__(
@@ -336,10 +384,7 @@ class TransitionBinding:
336
384
  """Validate the complete graph and selected prerequisite closure, without writes."""
337
385
  existing = MigrationLoader(None, ignore_no_migrations=True)
338
386
  pending = self._pending(existing)
339
- try:
340
- loader = _BindingLoader(pending)
341
- except Exception as error:
342
- raise RuntimeError(f"authored migration graph is invalid: {error}") from error
387
+ loader = _BindingLoader(pending)
343
388
  selected = None if app_labels is None else set(app_labels)
344
389
  ordered = dict.fromkeys(
345
390
  key
@@ -361,22 +406,14 @@ class TransitionBinding:
361
406
  continue
362
407
  source = pending[key]
363
408
  state = loader.project_state(nodes=[key], at_end=False)
364
- try:
365
- applies = source.guard(state.clone())
366
- except Exception as error:
367
- raise RuntimeError(f"{source.origin}: applies(project_state) failed") from error
368
- if not isinstance(applies, bool):
369
- raise RuntimeError(f"{source.origin}: applies must return bool")
409
+ applies = source.applies_to(state)
370
410
  baseline = not applies and source.initial_baseline and key[0] in initial_baselines
371
411
  if baseline:
372
412
  # A native empty migration also omits source-class lifecycle
373
413
  # overrides. Replace the graph owner before downstream state.
374
- migration = Migration(key[1], key[0])
375
- cast(list[Node], migration.dependencies).extend(source.migration.dependencies)
376
- cast(list[Node], migration.run_before).extend(source.migration.run_before)
377
- pending[key] = source = replace(source, migration=migration)
378
- loader.disk_migrations[key] = migration
379
- loader.graph.nodes[key] = migration
414
+ pending[key] = source = source.satisfied()
415
+ loader.disk_migrations[key] = source.migration
416
+ loader.graph.nodes[key] = source.migration
380
417
  elif not applies:
381
418
  raise RuntimeError(
382
419
  f"{source.origin}: false guard cannot prove a data transition completed; "
@@ -387,24 +424,10 @@ class TransitionBinding:
387
424
  except Exception as error:
388
425
  raise RuntimeError(f"{source.origin}: invalid migration state transition") from error
389
426
  path = _directory(key[0], missing=allow_missing_packages) / f"{key[1]}.py"
390
- if path.exists() or path.resolve() in destinations:
427
+ if path.resolve() in destinations:
391
428
  raise RuntimeError(f"{source.origin}: migration destination already exists: {path}")
392
429
  destinations.add(path.resolve())
393
- result.append(
394
- TransitionPlan(
395
- source.origin,
396
- key[0],
397
- key[1],
398
- source.path,
399
- source.text,
400
- path,
401
- source.digest,
402
- tuple(source.migration.dependencies),
403
- tuple(source.migration.run_before),
404
- source.package,
405
- baseline,
406
- )
407
- )
430
+ result.append(source.plan(path, initial_baseline=baseline))
408
431
  if apps is not None and not defer_drop_check:
409
432
  # This check compares state only. DropGuardAutodetector's row proofs
410
433
  # belong exclusively to explicit native authoring and migrate.
@@ -417,6 +440,110 @@ class TransitionBinding:
417
440
  _shared_table_drops(before, after, changes)
418
441
  return tuple(result)
419
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
+
420
547
  def check(self, app_labels: Iterable[str] | None = None) -> None:
421
548
  """Refuse unmaterialized declarations without creating packages or history."""
422
549
  pending = self.plan(app_labels=app_labels)
@@ -493,6 +620,12 @@ class TransitionBinding:
493
620
  + f"Migration.compose_source_sha256 = {plan.source_sha256!r}\n"
494
621
  + f"Migration.compose_body_sha256 = {body_digest!r}\n"
495
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
+ )
496
629
  ).encode()
497
630
  return payload + _SEAL_PREFIX + repr(hashlib.sha256(payload).hexdigest()).encode() + b"\n"
498
631
 
@@ -517,6 +650,18 @@ class TransitionBinding:
517
650
  allow_missing_packages=True,
518
651
  initial_baselines=initial_baselines,
519
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."""
520
665
  rendered = [(plan, self._render(plan)) for plan in plans]
521
666
  packages = [
522
667
  directory / "__init__.py"
@@ -544,7 +689,7 @@ class TransitionBinding:
544
689
  written_files.pop()
545
690
  raise
546
691
  importlib.invalidate_caches()
547
- self.plan(apps=apps, app_labels=app_labels)
692
+ validate()
548
693
  except BaseException:
549
694
  for path in written:
550
695
  path.unlink(missing_ok=True)
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.5
2
2
  Name: django-compose
3
- Version: 0.1.0.dev6
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,7 +12,7 @@ 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=N41itYT4TyJ3kFHoJmlK5l_gJDk9vuh7QeyAmfj6pvY,52548
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
@@ -23,8 +23,9 @@ django_compose/snapshot.py,sha256=J4a3eKa2V6cIIKXfvLiiqe6lWENbDCAKIV5CJC5Fjnc,18
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
31
  django_compose/management/commands/makemigrations.py,sha256=GIoz23DbHDArWQqR9BDp_dOAQf3YLdus5MUp6HDvGxs,10809
@@ -32,10 +33,10 @@ django_compose/management/commands/migrate.py,sha256=_MkiQRjQRwIr9dEUnKk4WEjLgz5
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.dev6.dist-info/METADATA,sha256=N-vk1j2nOuJXQ-8dQh-NPBiToUw0cbHA2DQ7Z3NMSZs,3939
36
- django_compose-0.1.0.dev6.dist-info/WHEEL,sha256=2iZrJkDIkeDh0k9SikKMqFuRP-ua6mb4Ir1AsER4BEw,87
37
- django_compose-0.1.0.dev6.dist-info/entry_points.txt,sha256=-Iw1c8YAegCC53YCKgPXjIZn4aPS3MmEKbcMrCpUMFU,59
38
- django_compose-0.1.0.dev6.dist-info/licenses/COPYING,sha256=jOtLnuWt7d5Hsx6XXB2QxzrSe2sWWh3NgMfFRetluQM,35147
39
- django_compose-0.1.0.dev6.dist-info/licenses/LICENSE,sha256=46mU2C5kSwOnkqkw9XQAJlhBL2JAf1_uCD8lVcXyMRg,7652
40
- django_compose-0.1.0.dev6.dist-info/licenses/NOTICE,sha256=C4fEGI9_-a1GCPfAH9bC0ZvmZFS71b9Z4v6rjrT5dxA,450
41
- django_compose-0.1.0.dev6.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,,