django-compose 0.1.0.dev2__py3-none-any.whl → 0.1.0.dev3__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.
@@ -22,6 +22,7 @@ def atomic_write(path: Path, content: bytes, *, exclusive: bool = False, mode: i
22
22
 
23
23
  Exclusive publication fails atomically if the destination already exists.
24
24
  An explicit mode also restores permissions when recreating a deleted file.
25
+ New files use ordinary creation permissions filtered by the process umask.
25
26
  """
26
27
  # Native loaders may otherwise accept same-second, same-size stale bytecode.
27
28
  caches: tuple[Path, ...] = ()
@@ -38,9 +39,11 @@ def atomic_write(path: Path, content: bytes, *, exclusive: bool = False, mode: i
38
39
  except FileNotFoundError:
39
40
  pass
40
41
  path.parent.mkdir(parents=True, exist_ok=True)
41
- descriptor, temporary = tempfile.mkstemp(prefix=".compose-", dir=path.parent)
42
- try:
43
- with os.fdopen(descriptor, "wb") as stream:
42
+ # The private directory protects incomplete bytes while native exclusive
43
+ # creation applies the umask, without changing process-wide permissions.
44
+ with tempfile.TemporaryDirectory(prefix=".compose-", dir=path.parent) as directory:
45
+ temporary = Path(directory) / path.name
46
+ with temporary.open("xb") as stream:
44
47
  stream.write(content)
45
48
  stream.flush()
46
49
  if mode is not None:
@@ -52,9 +55,6 @@ def atomic_write(path: Path, content: bytes, *, exclusive: bool = False, mode: i
52
55
  os.replace(temporary, path)
53
56
  for cache in caches:
54
57
  cache.unlink(missing_ok=True)
55
- finally:
56
- if os.path.exists(temporary):
57
- os.unlink(temporary)
58
58
 
59
59
 
60
60
  @dataclass
django_compose/build.py CHANGED
@@ -162,7 +162,7 @@ class BuildPlan:
162
162
  importlib.invalidate_caches()
163
163
  for label in self.labels:
164
164
  importlib.import_module(f"{self.output_module}.{label}.models")
165
- self.composition.validate_generated(apps)
165
+ self.composition.validate_generated(apps, declarations)
166
166
  return self
167
167
  except BaseException:
168
168
  self.close()
@@ -1,4 +1,4 @@
1
- """Resolve installed component metadata into an ordered selection of native Django apps."""
1
+ """Index native component metadata and resolve ordered selections of Django apps."""
2
2
 
3
3
  from __future__ import annotations
4
4
 
@@ -7,7 +7,7 @@ import math
7
7
  import os
8
8
  import subprocess
9
9
  import sys
10
- from collections.abc import Iterable, Mapping
10
+ from collections.abc import Iterable, Iterator, Mapping
11
11
  from dataclasses import asdict, dataclass, field
12
12
  from graphlib import CycleError, TopologicalSorter
13
13
  from importlib import metadata
@@ -178,23 +178,29 @@ def active_requirements(requirements: Iterable[str]) -> tuple[Requirement, ...]:
178
178
  )
179
179
 
180
180
 
181
- def installed_components(group: str) -> InstalledComponents:
182
- """Index group declarations and declared app-key collisions without imports.
181
+ def index_components(distributions: Iterable[metadata.Distribution], *, group: str) -> InstalledComponents:
182
+ """Index supplied native metadata without discovering or importing apps.
183
183
 
184
184
  Each participating distribution must declare exactly one group entry point.
185
185
  Its value remains a native app/config string, never a loaded entry point.
186
- Native metadata.distribution selects the winner for same-name installations.
186
+ Canonical distribution names must be unique, including library-only inputs.
187
+ Containers are immutable and sorted by distribution name; values retain
188
+ their supplied native Distribution and EntryPoint APIs. Indexing neither
189
+ validates app paths nor resolves requirements.
187
190
  """
188
191
  if not isinstance(group, str) or not group:
189
192
  raise ImproperlyConfigured("An explicit non-empty component entry-point group is required")
190
- distributions: dict[str, metadata.Distribution] = {}
193
+ indexed: dict[str, metadata.Distribution] = {}
194
+ for distribution in distributions:
195
+ name: str = canonicalize_name(distribution.metadata["Name"])
196
+ if name in indexed:
197
+ raise ImproperlyConfigured(f"Duplicate component distribution name {name!r}")
198
+ indexed[name] = distribution
199
+ indexed = dict(sorted(indexed.items()))
191
200
  points: dict[str, metadata.EntryPoint] = {}
192
201
  app_providers: dict[str, str] = {}
193
- names = {canonicalize_name(dist.metadata["Name"]) for dist in metadata.distributions()}
194
- for name in sorted(names):
195
- distribution = metadata.distribution(name)
202
+ for name, distribution in indexed.items():
196
203
  entries = distribution.entry_points.select(group=group)
197
- distributions[name] = distribution
198
204
  if not entries:
199
205
  continue
200
206
  if len(entries) != 1:
@@ -207,10 +213,21 @@ def installed_components(group: str) -> InstalledComponents:
207
213
  app_providers[point.name] = name
208
214
  points[name] = point
209
215
  return InstalledComponents(
210
- MappingProxyType(distributions), MappingProxyType(points), MappingProxyType(app_providers)
216
+ MappingProxyType(indexed), MappingProxyType(points), MappingProxyType(app_providers)
211
217
  )
212
218
 
213
219
 
220
+ def installed_components(group: str) -> InstalledComponents:
221
+ """Index installed metadata using native same-name installation precedence."""
222
+
223
+ def distributions() -> Iterator[metadata.Distribution]:
224
+ names = {canonicalize_name(dist.metadata["Name"]) for dist in metadata.distributions()}
225
+ for name in sorted(names):
226
+ yield metadata.distribution(name)
227
+
228
+ return index_components(distributions(), group=group)
229
+
230
+
214
231
  def enabled_apps(roots: Iterable[str], *, group: str | None = None) -> Closure:
215
232
  """Expand explicit roots using installed providers and selected requires_apps.
216
233
 
@@ -5,7 +5,6 @@ from __future__ import annotations
5
5
  import ast
6
6
  import importlib.util
7
7
  import pkgutil
8
- import re
9
8
  import symtable
10
9
  from collections.abc import Iterable
11
10
  from dataclasses import dataclass
@@ -14,6 +13,7 @@ from pathlib import Path
14
13
 
15
14
  from django.apps import apps
16
15
  from django.conf import settings
16
+ from packaging.utils import canonicalize_name
17
17
 
18
18
  from django_compose.sources import ModuleSource, SourceResolver
19
19
 
@@ -29,10 +29,6 @@ class HistoricalImport:
29
29
  detail: str = ""
30
30
 
31
31
 
32
- def _distribution_key(name: str) -> str:
33
- return re.sub(r"[-_.]+", "-", name).lower()
34
-
35
-
36
32
  class _ImportCalls(ast.NodeVisitor):
37
33
  """Let Python's symbol tables own import bindings across lexical scopes.
38
34
 
@@ -441,7 +437,7 @@ class MigrationImportReport:
441
437
 
442
438
  def removal_refusals(self, removing: Iterable[str]) -> tuple[str, ...]:
443
439
  """Refuse enabled providers, retained imports and unprovable dependencies."""
444
- selected = {_distribution_key(name) for name in removing}
440
+ selected = {canonicalize_name(name) for name in removing}
445
441
  refusals = []
446
442
  for config in apps.get_app_configs():
447
443
  source = self.resolver.resolve(config.name)
@@ -449,14 +445,14 @@ class MigrationImportReport:
449
445
  config_source = self.resolver.resolve(type(config).__module__)
450
446
  providers.update(config_source.distributions)
451
447
  for name in sorted(providers):
452
- if _distribution_key(name) in selected:
448
+ if canonicalize_name(name) in selected:
453
449
  refusals.append(f"{name} provides enabled app {config.name}")
454
450
  for item in self.items:
455
451
  if item.kind in {"unsupported", "unresolved"}:
456
452
  refusals.append(f"{item.path}: {item.kind} {item.module}: {item.detail}")
457
453
  if item.kind == "namespace":
458
454
  if item.distributions and all(
459
- _distribution_key(name) in selected for name in item.distributions
455
+ canonicalize_name(name) in selected for name in item.distributions
460
456
  ):
461
457
  refusals.append(
462
458
  f"{item.path}: retained namespace import {item.module} needs at least one of "
@@ -464,7 +460,7 @@ class MigrationImportReport:
464
460
  )
465
461
  continue
466
462
  for name in item.distributions:
467
- if _distribution_key(name) in selected:
463
+ if canonicalize_name(name) in selected:
468
464
  refusals.append(f"{item.path}: retained import {item.module} requires {name}")
469
465
  return tuple(sorted(set(refusals)))
470
466
 
@@ -23,6 +23,8 @@ from django.conf import settings
23
23
  from django.core.exceptions import ImproperlyConfigured
24
24
  from django.core.management.base import CommandError
25
25
  from django.db import DEFAULT_DB_ALIAS, DatabaseError, connections, router, transaction
26
+ from django.db.backends.base.base import BaseDatabaseWrapper
27
+ from django.db.backends.utils import split_identifier
26
28
  from django.db.migrations import Migration
27
29
  from django.db.migrations.autodetector import MigrationAutodetector
28
30
  from django.db.migrations.executor import MigrationExecutor
@@ -488,26 +490,159 @@ class TransitionBinding:
488
490
  return tuple(written)
489
491
 
490
492
 
493
+ def _storage_identifier(connection: BaseDatabaseWrapper, identifier: str) -> tuple[str, str]:
494
+ """Interpret only native Django's simple or double-quoted identifiers.
495
+
496
+ split_identifier() is not a SQL parser. Reject spellings it cannot represent
497
+ faithfully rather than silently turn quoted storage into an absent object.
498
+ """
499
+ namespace, name = split_identifier(identifier)
500
+ convert = connection.introspection.identifier_converter
501
+ limit = connection.ops.max_name_length()
502
+ if (
503
+ not name
504
+ or (limit is not None and max(len(namespace.encode()), len(name.encode())) > limit)
505
+ or '"' in namespace + name
506
+ or identifier.startswith(("`", "["))
507
+ or (namespace and connection.vendor != "postgresql")
508
+ or (
509
+ identifier != name
510
+ and convert(connection.ops.quote_name(identifier)) != convert(connection.ops.quote_name(name))
511
+ and not (namespace and identifier == f'"{namespace}"."{name}"')
512
+ )
513
+ ):
514
+ raise ImproperlyConfigured(
515
+ f"cannot resolve storage identifier {identifier!r} on {connection.alias!r}; "
516
+ "use a reviewed explicit migration for unsupported identifier syntax, length or namespace"
517
+ )
518
+ return convert(namespace), convert(name)
519
+
520
+
521
+ def _storage_identity(connection: BaseDatabaseWrapper, table: str, cursor: Any) -> tuple[str, str] | None:
522
+ """Resolve physical storage through the backend's native catalog semantics."""
523
+ namespace, name = _storage_identifier(connection, table)
524
+ if connection.vendor == "postgresql":
525
+ cursor.execute(
526
+ "SELECT n.nspname, c.relname FROM pg_catalog.pg_class c "
527
+ "JOIN pg_catalog.pg_namespace n ON n.oid = c.relnamespace "
528
+ "WHERE c.oid = pg_catalog.to_regclass(%s)",
529
+ [connection.ops.quote_name(table)],
530
+ )
531
+ row = cursor.fetchone()
532
+ return (row[0], row[1]) if row else None
533
+ if connection.vendor == "sqlite":
534
+ # SQLite resolves temp before main, and identifiers with native NOCASE.
535
+ # Do not substitute Python's broader Unicode case folding for that rule.
536
+ cursor.execute("PRAGMA database_list")
537
+ if any(row[1] not in {"main", "temp"} for row in cursor.fetchall()):
538
+ raise ImproperlyConfigured("cannot resolve storage across attached SQLite database namespaces")
539
+ cursor.execute(
540
+ "SELECT 'temp', name, 0 FROM sqlite_temp_master WHERE name = %s COLLATE NOCASE "
541
+ "UNION ALL SELECT 'main', name, 1 FROM sqlite_master WHERE name = %s COLLATE NOCASE "
542
+ "ORDER BY 3 LIMIT 1",
543
+ [name, name],
544
+ )
545
+ row = cursor.fetchone()
546
+ return (row[0], row[1]) if row else None
547
+ convert = connection.introspection.identifier_converter
548
+ tables = {convert(item) for item in connection.introspection.table_names(cursor)}
549
+ if name in tables:
550
+ return namespace, name
551
+ if connection.features.ignores_table_name_case:
552
+ raise ImproperlyConfigured(f"cannot prove case-sensitive storage identity for {table!r}")
553
+ return None
554
+
555
+
556
+ def _allows_migrate_model(operation: Operation, alias: str, model: Any, *, offline: bool) -> bool:
557
+ # Feature properties can connect (e.g. MySQL server metadata). Offline
558
+ # planning must conservatively retain an alias instead of probing it.
559
+ if offline and model._meta.required_db_features and not model._meta.required_db_vendor:
560
+ return router.allow_migrate_model(alias, model)
561
+ return operation.allow_migrate_model(alias, model)
562
+
563
+
564
+ def _model_storage(model: Any, *, removed_field: str | None = None) -> Iterator[Any]:
565
+ """Tables deleted by native model deletion or implicit M2M field removal."""
566
+ if removed_field is None:
567
+ yield model
568
+ fields = model._meta.local_many_to_many
569
+ else:
570
+ field = model._meta.get_field(removed_field)
571
+ fields = (field,) if field.many_to_many else ()
572
+ for field in fields:
573
+ through = field.remote_field.through
574
+ if through._meta.auto_created:
575
+ yield through
576
+
577
+
491
578
  def _shared_table_drops(
492
579
  before: ProjectState,
493
580
  after: ProjectState,
494
581
  changes: dict[str, list[Migration]],
582
+ *,
583
+ database: bool = False,
495
584
  ) -> None:
496
- owners: dict[str, set[str]] = {}
497
- for model in after.apps.get_models(include_swapped=True):
498
- if model._meta.managed and not model._meta.proxy:
499
- owners.setdefault(model._meta.db_table, set()).add(model._meta.label_lower)
585
+ owners = tuple(
586
+ (owner, storage)
587
+ for owner in after.apps.get_models(include_swapped=True)
588
+ for storage in _model_storage(owner)
589
+ )
500
590
  for label, migrations in sorted(changes.items()):
501
591
  for migration in migrations:
502
592
  for operation in migration.operations:
503
593
  if isinstance(operation, DeleteModel):
504
594
  model = before.apps.get_model(label, operation.name)
505
- remaining = owners.get(model._meta.db_table, set()) - {model._meta.label_lower}
506
- if model._meta.managed and not model._meta.proxy and remaining:
595
+ dropped = tuple(_model_storage(model))
596
+ elif isinstance(operation, RemoveField):
597
+ model = before.apps.get_model(label, operation.model_name)
598
+ dropped = tuple(_model_storage(model, removed_field=operation.name))
599
+ else:
600
+ continue
601
+ if not dropped:
602
+ continue
603
+ for alias in sorted(connections):
604
+ connection = connections[alias]
605
+ try:
606
+ if not _allows_migrate_model(operation, alias, model, offline=not database):
607
+ continue
608
+ for storage in dropped:
609
+ table = storage._meta.db_table
610
+ identity = _storage_identifier(connection, table)
611
+ remaining = set()
612
+ for owner, active_storage in owners:
613
+ if (
614
+ isinstance(operation, DeleteModel)
615
+ and owner._meta.label_lower == model._meta.label_lower
616
+ ) or not _allows_migrate_model(operation, alias, owner, offline=not database):
617
+ continue
618
+ active_table = active_storage._meta.db_table
619
+ other = _storage_identifier(connection, active_table)
620
+ if identity == other:
621
+ remaining.add(active_storage._meta.label_lower)
622
+ elif identity[1] == other[1] or (
623
+ connection.vendor in {"sqlite", "mysql"}
624
+ and identity[1].casefold() == other[1].casefold()
625
+ ):
626
+ if not database:
627
+ raise ImproperlyConfigured(
628
+ f"cannot resolve shared storage {table!r} and "
629
+ f"{active_table!r} offline; use a reviewed explicit migration"
630
+ )
631
+ with connection.cursor() as cursor:
632
+ physical = _storage_identity(connection, table, cursor)
633
+ if physical is not None and physical == _storage_identity(
634
+ connection, active_table, cursor
635
+ ):
636
+ remaining.add(active_storage._meta.label_lower)
637
+ if remaining:
638
+ raise CommandError(
639
+ f"unsafe autodetected table deletion: table {table!r} "
640
+ f"is still owned by {', '.join(sorted(remaining))} on {alias!r}"
641
+ )
642
+ except (DatabaseError, ImproperlyConfigured) as error:
507
643
  raise CommandError(
508
- f"unsafe autodetected model deletion: table {model._meta.db_table!r} "
509
- f"is still owned by {', '.join(sorted(remaining))}"
510
- )
644
+ f"cannot prove shared storage safe on {alias!r}: {error}"
645
+ ) from error
511
646
 
512
647
 
513
648
  class DropGuardAutodetector(MigrationAutodetector):
@@ -531,7 +666,7 @@ class DropGuardAutodetector(MigrationAutodetector):
531
666
  migration_name: str | None = None,
532
667
  ) -> dict[str, list[Migration]]:
533
668
  changes = super().changes(graph, trim_to_apps, convert_apps, migration_name)
534
- _shared_table_drops(self.from_state, self.to_state, changes)
669
+ _shared_table_drops(self.from_state, self.to_state, changes, database=True)
535
670
  refusals: list[str] = []
536
671
  rows: Callable[[str], Any]
537
672
  for label, migrations in sorted(changes.items()):
@@ -541,8 +676,8 @@ class DropGuardAutodetector(MigrationAutodetector):
541
676
  model = self.from_state.apps.get_model(label, operation.model_name)
542
677
  field = model._meta.get_field(operation.name)
543
678
  if field.many_to_many:
544
- through = field.remote_field.through
545
- if not through._meta.auto_created:
679
+ through = next(_model_storage(model, removed_field=operation.name), None)
680
+ if through is None:
546
681
  continue
547
682
  table, column = through._meta.db_table, None
548
683
 
@@ -565,11 +700,9 @@ class DropGuardAutodetector(MigrationAutodetector):
565
700
  rows = column_rows
566
701
  else:
567
702
  continue
568
- refusals.extend(self._holding(model, rows, table, column))
703
+ refusals.extend(self._holding(operation, model, rows, table, column))
569
704
  elif isinstance(operation, DeleteModel):
570
705
  model = self.from_state.apps.get_model(label, operation.name)
571
- if model._meta.proxy or not model._meta.managed or model._meta.swapped:
572
- continue
573
706
  integrations = tuple(
574
707
  integration
575
708
  for integration in resolve_integrations(
@@ -590,7 +723,9 @@ class DropGuardAutodetector(MigrationAutodetector):
590
723
  }
591
724
  return model._base_manager.exclude(pk__in=retired)
592
725
 
593
- refusals.extend(self._holding(model, remaining_rows, model._meta.db_table, None))
726
+ refusals.extend(
727
+ self._holding(operation, model, remaining_rows, model._meta.db_table, None)
728
+ )
594
729
  if refusals:
595
730
  raise CommandError(
596
731
  "unsafe autodetected drop: "
@@ -601,22 +736,47 @@ class DropGuardAutodetector(MigrationAutodetector):
601
736
 
602
737
  @staticmethod
603
738
  def _holding(
739
+ operation: Operation,
604
740
  model: type[Any],
605
741
  rows: Callable[[str], Any],
606
742
  table: str,
607
743
  column: str | None,
608
744
  ) -> Iterator[str]:
609
745
  for alias in sorted(connections):
610
- if not router.allow_migrate_model(alias, model):
611
- continue
612
746
  connection = connections[alias]
613
747
  try:
748
+ if not operation.allow_migrate_model(alias, model):
749
+ continue
614
750
  with connection.cursor() as cursor:
615
- present = table in connection.introspection.table_names(cursor)
751
+ present = _storage_identity(connection, table, cursor) is not None
616
752
  if present and column is not None:
617
- present = column in {
618
- f.name for f in connection.introspection.get_table_description(cursor, table)
619
- }
753
+ namespace, name = _storage_identifier(connection, column)
754
+ if namespace:
755
+ raise ImproperlyConfigured(f"column {column!r} cannot have a namespace")
756
+ if connection.vendor == "sqlite":
757
+ cursor.execute(
758
+ "SELECT name FROM pragma_table_xinfo(%s) WHERE name = %s COLLATE NOCASE",
759
+ [split_identifier(table)[1], name],
760
+ )
761
+ present = cursor.fetchone() is not None
762
+ else:
763
+ convert = connection.introspection.identifier_converter
764
+ if connection.vendor == "postgresql":
765
+ # Native PostgreSQL introspection only describes
766
+ # visible unqualified tables; the cursor owns the
767
+ # actual columns of this fully quoted relation.
768
+ cursor.execute(f"SELECT * FROM {connection.ops.quote_name(table)} LIMIT 0")
769
+ columns = {convert(field[0]) for field in cursor.description}
770
+ else:
771
+ columns = {
772
+ convert(field.name)
773
+ for field in connection.introspection.get_table_description(
774
+ cursor, split_identifier(table)[1]
775
+ )
776
+ }
777
+ present = name in columns
778
+ if not present and connection.vendor == "mysql":
779
+ raise ImproperlyConfigured(f"cannot prove column identity for {column!r}")
620
780
  count = rows(alias).using(alias).count() if present else 0
621
781
  except (DatabaseError, ImproperlyConfigured) as error:
622
782
  yield (
@@ -745,7 +905,9 @@ def _history_aliases(loader: MigrationLoader, labels: set[str]) -> tuple[str, ..
745
905
  for model in state.apps.get_models():
746
906
  if model._meta.app_label in labels:
747
907
  model_labels.add(model._meta.app_label)
748
- aliases.update(alias for alias in connections if router.allow_migrate_model(alias, model))
908
+ aliases.update(
909
+ alias for alias in connections if Operation().allow_migrate_model(alias, model)
910
+ )
749
911
 
750
912
  def include_operations(operations: Iterable[Operation], label: str, state: ProjectState) -> None:
751
913
  include(state)
@@ -841,7 +1003,7 @@ def retire_history(label: str, *, purge: bool = False) -> None:
841
1003
  changes = MigrationAutodetector(before, after).changes(
842
1004
  graph=loader.graph, trim_to_apps={label}, migration_name="compose_purge"
843
1005
  )
844
- _shared_table_drops(before, after, changes)
1006
+ _shared_table_drops(before, after, changes, database=True)
845
1007
  for migration in changes.get(label, ()):
846
1008
  writer = MigrationWriter(migration, include_header=False)
847
1009
  path = Path(writer.path)
@@ -7,7 +7,7 @@ import keyword
7
7
  import sys
8
8
  from collections.abc import Iterable, Mapping
9
9
  from graphlib import CycleError, TopologicalSorter
10
- from typing import Any
10
+ from typing import TYPE_CHECKING, Any
11
11
 
12
12
  from django.apps import AppConfig
13
13
  from django.apps.registry import Apps
@@ -16,6 +16,9 @@ from django.db import models
16
16
 
17
17
  from django_compose.models import Composable
18
18
 
19
+ if TYPE_CHECKING:
20
+ from django_compose.declarations import ModelDeclaration
21
+
19
22
 
20
23
  def _ordered(graph: Mapping[str, Iterable[str]], description: str) -> tuple[str, ...]:
21
24
  try:
@@ -170,21 +173,27 @@ class ModelComposition:
170
173
  """Return one native declaration per constraint, preserving shared ancestry."""
171
174
  return self._constraints[source]
172
175
 
173
- def validate_generated(self, registry: Apps) -> None:
174
- """Check constructed native namespaces, including automatically created managers."""
176
+ def validate_generated(
177
+ self,
178
+ registry: Apps,
179
+ declarations: Mapping[type[models.Model], ModelDeclaration] | None = None,
180
+ ) -> None:
181
+ """Check native structural namespaces, including implicit fields and managers."""
175
182
  for source in self.ordered_models:
176
183
  model = registry.get_model(source._meta.app_label, source.__name__, require_ready=False)
184
+ fields = (
185
+ *model._meta.fields,
186
+ *model._meta.many_to_many,
187
+ *model._meta.private_fields,
188
+ *(field for field in model._meta.parents.values() if field is not None),
189
+ )
190
+ field_names = {name for native in fields for name in (native.name, native.get_attname())}
191
+ if declaration := (declarations or {}).get(source):
192
+ for name in sorted(field_names & declaration.attributes.keys()):
193
+ raise ImproperlyConfigured(f"{model._meta.label}: cannot declare {name!r}")
177
194
  self._validate_field_managers(
178
195
  model,
179
- (
180
- name
181
- for native in (
182
- *model._meta.fields,
183
- *model._meta.many_to_many,
184
- *model._meta.private_fields,
185
- )
186
- for name in (native.name, native.attname)
187
- ),
196
+ field_names,
188
197
  (manager.name for manager in model._meta.managers),
189
198
  )
190
199
 
django_compose/typing.py CHANGED
@@ -16,9 +16,13 @@ from typing import TYPE_CHECKING, Literal
16
16
 
17
17
  from django.core.exceptions import FieldDoesNotExist
18
18
  from django.db import models
19
+ from mypy.checkmember import analyze_member_access
20
+ from mypy.expandtype import expand_type, expand_type_by_instance
21
+ from mypy.maptype import map_instance_to_supertype
19
22
  from mypy.mro import calculate_mro
20
23
  from mypy.nodes import (
21
24
  MDEF,
25
+ CallExpr,
22
26
  ClassDef,
23
27
  Decorator,
24
28
  FuncDef,
@@ -26,6 +30,7 @@ from mypy.nodes import (
26
30
  MypyFile,
27
31
  OverloadedFuncDef,
28
32
  PlaceholderNode,
33
+ SymbolTable,
29
34
  SymbolTableNode,
30
35
  TypeInfo,
31
36
  Var,
@@ -34,7 +39,8 @@ from mypy.options import Options
34
39
  from mypy.plugin import AttributeContext, ClassDefContext, DynamicClassDefContext, ReportConfigContext
35
40
  from mypy.semanal_shared import PRIORITY_FALLBACKS, has_placeholder
36
41
  from mypy.server.trigger import make_trigger
37
- from mypy.types import CallableType, Instance, Overloaded, TypeType, get_proper_type
42
+ from mypy.typeops import erase_to_bound, make_simplified_union
43
+ from mypy.types import CallableType, Instance, Overloaded, TypeType, UnionType, get_proper_type
38
44
  from mypy.types import Type as MypyType
39
45
  from mypy.typevars import fill_typevars, fill_typevars_with_any
40
46
  from mypy_django_plugin.django.context import DjangoContext
@@ -119,7 +125,10 @@ class CompositionContext(DjangoContext):
119
125
  selected: dict[str, _Member] = {}
120
126
  self.members[name] = selected
121
127
  donor_ancestors = {base for donor in donors for base in donor.__mro__}
122
- for owner in concrete.__mro__:
128
+ seen = set(vars(concrete))
129
+ for owner in concrete.__mro__[1:]:
130
+ attributes = set(vars(owner)) - seen
131
+ seen.update(vars(owner))
123
132
  if owner in source.__mro__ or owner not in donor_ancestors:
124
133
  continue
125
134
  receiver = next(
@@ -127,7 +136,7 @@ class CompositionContext(DjangoContext):
127
136
  )
128
137
  member = _Member(helpers.get_class_fullname(owner), helpers.get_class_fullname(receiver))
129
138
  self.dependencies.setdefault(source.__module__, set()).add(owner.__module__)
130
- for attribute in vars(owner):
139
+ for attribute in sorted(attributes):
131
140
  selected.setdefault(attribute, member)
132
141
  for source, parent in self.required_ancestors.items():
133
142
  self.parents.setdefault(helpers.get_class_fullname(source), helpers.get_class_fullname(parent))
@@ -175,6 +184,7 @@ class CompositionPlugin(NewSemanalDjangoPlugin):
175
184
 
176
185
  django_context: CompositionContext
177
186
  context_class: type[CompositionContext] = CompositionContext
187
+ _projecting_access = False
178
188
 
179
189
  def __init__(self, options: Options) -> None:
180
190
  with _compose_mode():
@@ -191,13 +201,105 @@ class CompositionPlugin(NewSemanalDjangoPlugin):
191
201
  }
192
202
 
193
203
  def get_attribute_hook(self, fullname: str) -> Callable[[AttributeContext], MypyType] | None:
194
- """Expose configure's derived facts through native Django settings lookup."""
204
+ """Project effective member access and configure's native settings facts."""
195
205
 
196
206
  native = super().get_attribute_hook(fullname)
207
+ if projection := self._member_access_hook(fullname):
208
+ return projection
197
209
  if fullname.rpartition(".")[0] == fullnames.DUMMY_SETTINGS_BASE_CLASS and native is not None:
198
210
  return partial(self._derived_setting, native=native)
199
211
  return native
200
212
 
213
+ def get_class_attribute_hook(self, fullname: str) -> Callable[[AttributeContext], MypyType] | None:
214
+ return self._member_access_hook(fullname) or super().get_class_attribute_hook(fullname)
215
+
216
+ def _member_access_hook(self, fullname: str) -> Callable[[AttributeContext], MypyType] | None:
217
+ if self._projecting_access:
218
+ return None
219
+ owner, _, name = fullname.rpartition(".")
220
+ if name not in self.django_context.members.get(owner, {}):
221
+ symbol = self.lookup_fully_qualified(owner)
222
+ if symbol and isinstance(symbol.node, TypeInfo):
223
+ inherited = symbol.node.get_containing_type_info(name)
224
+ if inherited is not None:
225
+ owner = inherited.fullname
226
+ if name in self.django_context.members.get(owner, {}):
227
+ return partial(self._member_access, target_name=owner, name=name)
228
+ return None
229
+
230
+ def _member_access(self, ctx: AttributeContext, *, target_name: str, name: str) -> MypyType:
231
+ # Native override checks also use member access with a declaration as
232
+ # context; those must continue to compare the authored signatures. The
233
+ # native union call checker rechecks member access with the CallExpr.
234
+ if not isinstance(ctx.context, MemberExpr) and not (
235
+ isinstance(ctx.context, CallExpr) and isinstance(ctx.context.callee, MemberExpr)
236
+ ):
237
+ return ctx.default_attr_type
238
+ target_symbol = self.lookup_fully_qualified(target_name)
239
+ assert target_symbol and isinstance(target_symbol.node, TypeInfo)
240
+ target = target_symbol.node
241
+ if name not in target.metadata.get("compose_overrides", {}):
242
+ return ctx.default_attr_type
243
+ member = self.django_context.members[target.fullname][name]
244
+ origin = self.lookup_fully_qualified(member.owner)
245
+ receiver = self.lookup_fully_qualified(member.receiver)
246
+ assert origin and isinstance(origin.node, TypeInfo)
247
+ assert receiver and isinstance(receiver.node, TypeInfo)
248
+ symbol = origin.node.names.get(name)
249
+ declaration = _member_variable(symbol.node) if symbol is not None else None
250
+ if declaration is None or declaration.type is None:
251
+ return ctx.default_attr_type
252
+ checker = helpers.get_typechecker_api(ctx)
253
+ projected = self._specialize_member(
254
+ name, declaration, target, origin.node, receiver.node, checker.named_type("builtins.function")
255
+ )
256
+ # A native lookup view keeps authored signatures available to override
257
+ # and method-body analysis. Only expression access sees the donor.
258
+ view = TypeInfo(
259
+ SymbolTable({name: SymbolTableNode(MDEF, projected)}), target.defn, target.module_name
260
+ )
261
+ view._fullname = target.fullname
262
+ view.mro = [view, *target.mro[1:]]
263
+ receivers: list[MypyType] = [ctx.type]
264
+ bounded = get_proper_type(erase_to_bound(ctx.type))
265
+ if isinstance(bounded, UnionType):
266
+ # Native union lookup invokes this hook for each owning member but
267
+ # exposes the original union. Keep only that owner's receivers;
268
+ # the outer native lookup handles the other arms independently.
269
+ receivers = []
270
+ for item in bounded.relevant_items():
271
+ instance = get_proper_type(item)
272
+ if isinstance(instance, TypeType):
273
+ instance = get_proper_type(instance.item)
274
+ elif isinstance(instance, CallableType | Overloaded) and instance.is_type_obj():
275
+ instance = get_proper_type(instance.items[0].ret_type)
276
+ if isinstance(instance, Instance) and instance.type.get_containing_type_info(name) is target:
277
+ receivers.append(item)
278
+ if not receivers:
279
+ return ctx.default_attr_type
280
+ self._projecting_access = True
281
+ try:
282
+ return make_simplified_union(
283
+ [
284
+ analyze_member_access(
285
+ name,
286
+ TypeType.make_normalized(receiver.items[0].ret_type)
287
+ if isinstance(receiver, CallableType | Overloaded) and receiver.is_type_obj()
288
+ else receiver,
289
+ ctx.context,
290
+ is_lvalue=ctx.is_lvalue,
291
+ is_super=False,
292
+ is_operator=False,
293
+ original_type=receiver,
294
+ chk=checker,
295
+ override_info=view,
296
+ )
297
+ for receiver in receivers
298
+ ]
299
+ )
300
+ finally:
301
+ self._projecting_access = False
302
+
201
303
  def _derived_setting(
202
304
  self, ctx: AttributeContext, *, native: Callable[[AttributeContext], MypyType]
203
305
  ) -> MypyType:
@@ -476,8 +578,10 @@ class CompositionPlugin(NewSemanalDjangoPlugin):
476
578
  if symbol and symbol.plugin_generated and isinstance(symbol.node, Var):
477
579
  del target.names[name]
478
580
  emitted = target.metadata.setdefault("compose_members", {})
581
+ overrides = target.metadata.setdefault("compose_overrides", {})
479
582
  for name, member in self.django_context.members.get(target.fullname, {}).items():
480
- if target.get(name) is not None:
583
+ existing = target.get(name)
584
+ if existing is not None and existing.plugin_generated:
481
585
  continue
482
586
  origin = self.lookup_fully_qualified(member.owner)
483
587
  receiver = self.lookup_fully_qualified(member.receiver)
@@ -495,6 +599,17 @@ class CompositionPlugin(NewSemanalDjangoPlugin):
495
599
  projected = self._specialize_member(
496
600
  name, declaration, target, origin.node, receiver.node, function_type
497
601
  )
602
+ if existing is not None:
603
+ original = _member_variable(existing.node)
604
+ if original is not None and original.type is not None:
605
+ owner = target.get_containing_type_info(name)
606
+ assert owner is not None
607
+ target.names[name] = SymbolTableNode(
608
+ MDEF,
609
+ self._specialize_member(name, original, target, owner, target, function_type),
610
+ )
611
+ overrides[name] = True
612
+ continue
498
613
  target.names[name] = SymbolTableNode(MDEF, projected, plugin_generated=True)
499
614
  emitted[name] = member.owner
500
615
 
@@ -507,11 +622,6 @@ class CompositionPlugin(NewSemanalDjangoPlugin):
507
622
  receiver: TypeInfo,
508
623
  function_type: Instance,
509
624
  ) -> Var:
510
- # Load this native owner after mypy.types: its standalone import cycle
511
- # otherwise prevents importing CompositionContext outside mypy's CLI.
512
- from mypy.expandtype import expand_type, expand_type_by_instance
513
- from mypy.maptype import map_instance_to_supertype
514
-
515
625
  assert declaration.type is not None
516
626
  instance = fill_typevars(receiver)
517
627
  assert isinstance(instance, Instance)
django_compose/urls.py CHANGED
@@ -2,12 +2,14 @@
2
2
 
3
3
  from __future__ import annotations
4
4
 
5
- import re
6
5
  from collections.abc import Iterator
7
6
 
8
7
  from django.apps import apps
9
8
  from django.core.checks import Error
10
9
  from django.urls import URLPattern, URLResolver, include, path
10
+ from django.urls.resolvers import RegexPattern, RoutePattern
11
+
12
+ type _Route = tuple[tuple[object, ...], ...]
11
13
 
12
14
 
13
15
  def _patterns() -> Iterator[tuple[str, URLResolver]]:
@@ -26,29 +28,48 @@ def _patterns() -> Iterator[tuple[str, URLResolver]]:
26
28
  )
27
29
 
28
30
 
29
- def _routes(pattern: URLPattern | URLResolver, prefix: str = "") -> Iterator[str]:
30
- # Compare native effective regular expressions, including nested includes.
31
- expression = pattern.pattern.regex.pattern.removeprefix("^")
32
- route = prefix + expression
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
+ )
33
46
  if isinstance(pattern, URLResolver):
34
47
  for child in pattern.url_patterns:
35
48
  yield from _routes(child, route)
36
49
  else:
37
- yield re.sub(r"\(\?P<[^>]+>", "(?:", route)
50
+ yield route
38
51
 
39
52
 
40
53
  def check_url_collisions(**kwargs: object) -> list[Error]:
41
- """Report competing effective routes, regardless of reverse namespace."""
42
- owners: dict[str, str] = {}
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] = {}
43
62
  errors = []
44
- for owner, resolver in _patterns():
63
+ # Retain native resolvers throughout the proof so converter IDs stay live.
64
+ for owner, resolver in tuple(_patterns()):
45
65
  for route in _routes(resolver):
46
66
  previous = owners.get(route)
47
67
  owners[route] = owner
48
68
  if previous is not None:
49
69
  errors.append(
50
70
  Error(
51
- f"URL route {route!r} is claimed by {previous} and {owner}",
71
+ f"URL pattern chain {tuple(part[1] for part in route)!r} "
72
+ f"is claimed by {previous} and {owner}",
52
73
  id="django_compose.E001",
53
74
  )
54
75
  )
@@ -0,0 +1,98 @@
1
+ Metadata-Version: 2.5
2
+ Name: django-compose
3
+ Version: 0.1.0.dev3
4
+ Summary: Compose reusable Django apps into a runnable project.
5
+ Project-URL: Source, https://github.com/ang-ee/django-compose
6
+ Project-URL: Documentation, https://github.com/ang-ee/django-compose/tree/main/docs
7
+ Project-URL: Issues, https://github.com/ang-ee/django-compose/issues
8
+ Author-email: "Angee, Inc." <hi@angee.ai>
9
+ License-Expression: LGPL-3.0-or-later
10
+ License-File: COPYING
11
+ License-File: LICENSE
12
+ License-File: NOTICE
13
+ Requires-Python: >=3.14
14
+ Requires-Dist: django-yamlconf>=1.5
15
+ Requires-Dist: django<6.2,>=6.1.2
16
+ Requires-Dist: packaging>=26
17
+ Provides-Extra: typing
18
+ Requires-Dist: angee-django-stubs-ext==6.1.2; extra == 'typing'
19
+ Requires-Dist: angee-django-stubs[compatible-mypy]==6.1.2.post3; extra == 'typing'
20
+ Requires-Dist: angee-mypy==2.1.0; extra == 'typing'
21
+ Description-Content-Type: text/markdown
22
+
23
+ # django-compose
24
+
25
+ Compose reusable Django apps into a runnable project.
26
+
27
+ django-compose resolves the apps selected by your project's `INSTALLED_APPS`,
28
+ combines their model declarations and settings contributions, and generates
29
+ ordinary Django models and app configurations before startup.
30
+
31
+ Use it when several projects share reusable apps but need different combinations
32
+ of fields and behavior. You author the project settings and launcher; Django
33
+ continues to own the app registry, ORM, managers, querysets and migrations.
34
+
35
+ ```text
36
+ installed apps + project settings → compose → generated Django package
37
+ ```
38
+
39
+ ## What it provides
40
+
41
+ - **App selection:** expand explicit roots through declared app dependencies and
42
+ optional installed-package metadata.
43
+ - **Model composition:** add fields and methods to another app's model, create
44
+ concrete models, or declare native multi-table inheritance.
45
+ - **Project configuration:** combine app settings and optionally collect URL,
46
+ ASGI and database-preparation contributions.
47
+ - **Build output:** generate model/configuration modules and declared artifacts;
48
+ verify that they match the selected inputs before serving.
49
+
50
+ Packages remain installed at runtime because generated classes import their
51
+ source declarations. `compose` writes files; Django's migration commands change
52
+ the database.
53
+
54
+ ## One model, two apps
55
+
56
+ ```python
57
+ # catalog/models.py
58
+ from django.db import models
59
+ from django_compose.models import Composable
60
+
61
+ class Item(Composable, concrete=True):
62
+ title = models.CharField(max_length=100)
63
+
64
+ class Meta:
65
+ abstract = True
66
+ ```
67
+
68
+ ```python
69
+ # reviews/models.py
70
+ from django.db import models
71
+ from django_compose.models import Composable
72
+
73
+ class Rating(Composable, extends="catalog.Item"):
74
+ rating = models.PositiveSmallIntegerField(default=0)
75
+
76
+ class Meta:
77
+ abstract = True
78
+ ```
79
+
80
+ With both apps selected, the generated `catalog.Item` has `title` and `rating` in
81
+ one table. `Rating` adds no table of its own. After composition, migrations and
82
+ Django setup, use `apps.get_model("catalog", "Item")` to obtain the concrete model.
83
+ The [model guide](https://github.com/ang-ee/django-compose/blob/main/docs/models.md)
84
+ explains all four declaration keywords and lazy relations.
85
+
86
+ ## Get started
87
+
88
+ This is a development preview. See [compatibility and platform requirements](https://github.com/ang-ee/django-compose/blob/main/docs/dependencies.md)
89
+ and [installation](https://github.com/ang-ee/django-compose/blob/main/docs/packaging.md).
90
+
91
+ 1. [Run the quick start](https://github.com/ang-ee/django-compose/blob/main/docs/quickstart.md)
92
+ to compose the checked-in SQLite project and query the result.
93
+ 2. [Configure your project](https://github.com/ang-ee/django-compose/blob/main/docs/configuration.md)
94
+ with `configure(globals())` and the command launcher.
95
+ 3. [Browse the APIs](https://github.com/ang-ee/django-compose/blob/main/docs/README.md)
96
+ for commands, Python entry points and app extension hooks.
97
+
98
+ Licensed under [LGPL-3.0-or-later](https://github.com/ang-ee/django-compose/blob/main/LICENSE).
@@ -1,19 +1,19 @@
1
1
  django_compose/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
2
2
  django_compose/__main__.py,sha256=3UMaUz10MyIX8O46BUiU269LnvxdKfjImI2j2Jnl3us,135
3
3
  django_compose/apps.py,sha256=thorhTqeNu2fw6Kx4oguoPqsyYwvkiKnvQbAGeLKB6c,4157
4
- django_compose/artifacts.py,sha256=GHLrzCMU00scL9712TLaQPbTY8cdk3l5gv3QQ1DWZb8,9859
4
+ django_compose/artifacts.py,sha256=JIwTpHDB6dahVpOOrS9M8bHWV1356nGCjCo45Sds5vg,10046
5
5
  django_compose/asgi.py,sha256=EllgrrF3fMEQXNd3YR5JvijKaKFHqPI2Lv2PtmQ4ZKA,5151
6
6
  django_compose/autoreload.py,sha256=Obguzio30T42nIjSX9HVmrU-CqtTrm7moU0Wd271Egg,4128
7
- django_compose/build.py,sha256=QexC6r-yPcWrQ-WBfT2iI1xW1b1iMiYwDCXR-YzLmyw,11752
7
+ django_compose/build.py,sha256=hxLad46ZIU5QdD0f6e6TUtk3W9XQEXXgHyZQXeMhfFU,11766
8
8
  django_compose/checks.py,sha256=68mO4E6_UPYhya9wjO-SsQ2YFnDSl0q_fI8r-DnSTZ0,366
9
9
  django_compose/cli.py,sha256=9YlvZY7-qPVtuTXpMA5KxtAZd-TzTVCrg-2F4cNodUM,1209
10
- django_compose/components.py,sha256=jtjaK2gDBWDMV0H05bT0aG3ruIYkjKyallDHLfnhscA,13450
10
+ django_compose/components.py,sha256=k42JmMTnH-Xl_26qqk8dUiwjsnf35oMZnCecObvzTLU,14267
11
11
  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
- django_compose/migration_imports.py,sha256=AuK2HdfesyuN55_-eQ_lROnxLqh6z_BZ36vRJP-KFoE,22066
15
- django_compose/migrations.py,sha256=q-oOLgDX2lEjK9qDzSUMwnCWpawusvhhzBn75-O-BDU,40613
16
- django_compose/model_composition.py,sha256=6LxdVnpDxkmbfYKG99fqPX-D-QK4PiH7Eg96ggK5x9o,16057
14
+ django_compose/migration_imports.py,sha256=vyg8NdUCl977HrdfBkz642x0ra_btaRdCqZEfQs4V2o,22011
15
+ django_compose/migrations.py,sha256=P_Tz7WdlgoXzxHwzJIjAM31F7HgHlaQdn7LHZHH4q50,49343
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
@@ -21,8 +21,8 @@ django_compose/rendering.py,sha256=1OFZU7lLMO2rD4S9K1-g8wvdn8RKBnUuQTFPHnDWsHY,3
21
21
  django_compose/serving.py,sha256=kOEKik7Oe0CLDmGviHjtP3z3ZUn8xnjdG0z53WMM0KY,15499
22
22
  django_compose/snapshot.py,sha256=V7oxltGssttISZ7zPtIjuPA5fBOvzWbD2e4UdkEnPus,17732
23
23
  django_compose/sources.py,sha256=zusV-sFM9KnW6zyb05Dvag1APU_ABZlqL47W1xwvssI,6094
24
- django_compose/typing.py,sha256=J929_NrnmRWEpANDAhT3pivNE_Cas5sHEDCSENf9O_c,30405
25
- django_compose/urls.py,sha256=pIWRJ2stsL7Cf29S0ET9yBs161hGWdUy7LeYIXB1f_o,1987
24
+ django_compose/typing.py,sha256=13pd3JfIoBV8v4AHK-QgAg9J8C4Miz_D0dmHFEwUG4I,36089
25
+ django_compose/urls.py,sha256=PZLa-pGe5JgzpUgu9sOEUbO2FgLGPkZZSOhRD1ZLgUk,2969
26
26
  django_compose/management/__init__.py,sha256=p9ZFdX92SHN9RHeSN4dTgt6Oe3DhKq0LbiTaPRz7tSY,8727
27
27
  django_compose/management/commands/__init__.py,sha256=_mgOwmIp5-GhgJd6tY4Wc89G0EJDiHF9tYo8F63ytm8,40
28
28
  django_compose/management/commands/check_migrations.py,sha256=CIGGQCq-01Cm0_ZR7Exl4EtM_-qnFfhzfMsLxhl8P5A,2918
@@ -32,10 +32,10 @@ django_compose/management/commands/migrate.py,sha256=_MkiQRjQRwIr9dEUnKk4WEjLgz5
32
32
  django_compose/management/commands/provision.py,sha256=4GTPwH1Pp1V_YkztDZxeHuyAjDUHjZxhkdvFlrgDBfU,1035
33
33
  django_compose/management/commands/reset_migration_history.py,sha256=PD3baeH1jQHIXXLaEYyxZXfhVYfJLzTXnv-XF1ySULQ,1489
34
34
  django_compose/management/commands/retire_history.py,sha256=3RV1-w5Niij0svr0gB_gAjBgskxCYtdg5pPfsGN287s,886
35
- django_compose-0.1.0.dev2.dist-info/METADATA,sha256=n-5jP3W_nMDISvjGOxNZK9J0fgN8DrtBie9tCebUniA,4897
36
- django_compose-0.1.0.dev2.dist-info/WHEEL,sha256=2iZrJkDIkeDh0k9SikKMqFuRP-ua6mb4Ir1AsER4BEw,87
37
- django_compose-0.1.0.dev2.dist-info/entry_points.txt,sha256=-Iw1c8YAegCC53YCKgPXjIZn4aPS3MmEKbcMrCpUMFU,59
38
- django_compose-0.1.0.dev2.dist-info/licenses/COPYING,sha256=jOtLnuWt7d5Hsx6XXB2QxzrSe2sWWh3NgMfFRetluQM,35147
39
- django_compose-0.1.0.dev2.dist-info/licenses/LICENSE,sha256=46mU2C5kSwOnkqkw9XQAJlhBL2JAf1_uCD8lVcXyMRg,7652
40
- django_compose-0.1.0.dev2.dist-info/licenses/NOTICE,sha256=C4fEGI9_-a1GCPfAH9bC0ZvmZFS71b9Z4v6rjrT5dxA,450
41
- django_compose-0.1.0.dev2.dist-info/RECORD,,
35
+ django_compose-0.1.0.dev3.dist-info/METADATA,sha256=tFYz0eLOCkKTqUrBmDbeWUeWmfPbHOriqcqpPHihu20,3939
36
+ django_compose-0.1.0.dev3.dist-info/WHEEL,sha256=2iZrJkDIkeDh0k9SikKMqFuRP-ua6mb4Ir1AsER4BEw,87
37
+ django_compose-0.1.0.dev3.dist-info/entry_points.txt,sha256=-Iw1c8YAegCC53YCKgPXjIZn4aPS3MmEKbcMrCpUMFU,59
38
+ django_compose-0.1.0.dev3.dist-info/licenses/COPYING,sha256=jOtLnuWt7d5Hsx6XXB2QxzrSe2sWWh3NgMfFRetluQM,35147
39
+ django_compose-0.1.0.dev3.dist-info/licenses/LICENSE,sha256=46mU2C5kSwOnkqkw9XQAJlhBL2JAf1_uCD8lVcXyMRg,7652
40
+ django_compose-0.1.0.dev3.dist-info/licenses/NOTICE,sha256=C4fEGI9_-a1GCPfAH9bC0ZvmZFS71b9Z4v6rjrT5dxA,450
41
+ django_compose-0.1.0.dev3.dist-info/RECORD,,
@@ -1,111 +0,0 @@
1
- Metadata-Version: 2.5
2
- Name: django-compose
3
- Version: 0.1.0.dev2
4
- Summary: Compose reusable Django apps into a runnable project.
5
- Project-URL: Source, https://github.com/ang-ee/django-compose
6
- Project-URL: Documentation, https://github.com/ang-ee/django-compose/tree/main/docs
7
- Project-URL: Issues, https://github.com/ang-ee/django-compose/issues
8
- Author-email: "Angee, Inc." <hi@angee.ai>
9
- License-Expression: LGPL-3.0-or-later
10
- License-File: COPYING
11
- License-File: LICENSE
12
- License-File: NOTICE
13
- Requires-Python: >=3.14
14
- Requires-Dist: django-yamlconf>=1.5
15
- Requires-Dist: django<6.2,>=6.1.2
16
- Requires-Dist: packaging>=26
17
- Provides-Extra: typing
18
- Requires-Dist: angee-django-stubs-ext==6.1.2; extra == 'typing'
19
- Requires-Dist: angee-django-stubs[compatible-mypy]==6.1.2.post3; extra == 'typing'
20
- Requires-Dist: angee-mypy==2.1.0; extra == 'typing'
21
- Description-Content-Type: text/markdown
22
-
23
- # django-compose
24
-
25
- Compose reusable Django apps into a runnable project.
26
-
27
- Installed Python distributions participate as **components**, each providing one
28
- Django app. Native package metadata supplies dependencies; `INSTALLED_APPS`
29
- selects the project's roots. Components can provide models, settings or resources.
30
-
31
- One app can define a model and another can add fields and behavior to it. The
32
- result is an ordinary concrete Django model, with Django's ORM and migrations.
33
-
34
- For example, `catalog` defines an item and `reviews` adds a rating:
35
-
36
- ```text
37
- catalog.Item (title) + reviews.Rating (rating, is_recommended)
38
- → concrete catalog.Item → one catalog_item table
39
- ```
40
-
41
- The reusable declarations are abstract models. An explicit `compose` command
42
- writes the concrete classes into a Python package before the project runs.
43
- Select the apps you need; the generated models reflect that selection. You
44
- write ordinary project settings and a command launcher; django-compose supplies
45
- the generated models and app configuration.
46
-
47
- This is useful when several projects share a model but need different optional
48
- capabilities. For a single project with a fixed model structure, ordinary Django
49
- models and abstract bases may already be sufficient.
50
-
51
- **Status:** development preview `0.1.0.dev2`; Python 3.14 and Django 6.1 are supported.
52
- The base dependencies are Django, packaging and django-yamlconf.
53
-
54
- ```sh
55
- python -m pip install django-compose==0.1.0.dev2
56
- ```
57
-
58
- For advanced composed-model analysis, install `django-compose[typing]==0.1.0.dev2`;
59
- see [typing dependencies](https://github.com/ang-ee/django-compose/blob/main/docs/dependencies.md#advanced-typing). The example below
60
- uses this checkout and does not require another framework.
61
-
62
- ## Try the example
63
-
64
- Install [uv](https://docs.astral.sh/uv/) and run these commands from the checkout
65
- root. The example uses a local SQLite database.
66
-
67
- ```sh
68
- uv sync --frozen --no-dev
69
- uv pip install --no-deps ./examples/shop/catalog ./examples/shop/reviews
70
- cd examples/shop
71
- uv run --project ../.. --no-sync python manage.py compose
72
- uv run --project ../.. --no-sync python manage.py makemigrations catalog auth contenttypes
73
- uv run --project ../.. --no-sync python manage.py migrate
74
- uv run --project ../.. --no-sync python manage.py compose --check
75
- uv run --project ../.. --no-sync python verify.py
76
- uv run --project ../.. --no-sync python manage.py shell
77
- ```
78
-
79
- In the Django shell:
80
-
81
- ```python
82
- from django.apps import apps
83
-
84
- Item = apps.get_model("catalog", "Item")
85
- item = Item.objects.create(title="A book", rating=5)
86
- assert item.is_recommended()
87
- assert Item.objects.get(pk=item.pk).rating == 5
88
- ```
89
-
90
- The two apps now contribute to the same model and table. `compose` generated the
91
- classes; `makemigrations` and `migrate` created and applied ordinary Django
92
- history. Source apps remain installed when the generated project runs.
93
-
94
- Projects with database preparation hooks can use
95
- [`provision`](https://github.com/ang-ee/django-compose/blob/main/docs/provisioning.md)
96
- after composing and authoring migrations. It applies migrations, runs optional
97
- app hooks and records readiness for the verified composition. `compose` itself
98
- performs no database preparation.
99
-
100
- ## Where to go next
101
-
102
- - [Quick start](https://github.com/ang-ee/django-compose/blob/main/docs/quickstart.md): walk through the source, generated files,
103
- commands and ORM result.
104
- - [Model declarations](https://github.com/ang-ee/django-compose/blob/main/docs/models.md): add fields to one model or declare
105
- native multi-table inheritance.
106
- - [Project configuration](https://github.com/ang-ee/django-compose/blob/main/docs/configuration.md): use django-compose in your own
107
- project with the current settings and `manage.py` integration.
108
- - [Documentation](https://github.com/ang-ee/django-compose/blob/main/docs/README.md): optional component selection, integrations,
109
- migrations, packaging, API reference and current limitations.
110
-
111
- The source is licensed under [LGPL-3.0-or-later](https://github.com/ang-ee/django-compose/blob/main/LICENSE).