django-compose 0.1.0.dev3__py3-none-any.whl → 0.1.0.dev6__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.
@@ -240,12 +240,20 @@ def enabled_apps(roots: Iterable[str], *, group: str | None = None) -> Closure:
240
240
 
241
241
  Root configs are preselected and override dependency/default config choices.
242
242
  Conflicting dependency configs, duplicate native labels and cycles fail.
243
+ Each exact app/config string resolves to one native instance per call.
243
244
  """
244
245
  installed = installed_components(group) if group is not None else None
245
246
  root_entries = tuple(roots)
246
247
  if any(not isinstance(entry, str) for entry in root_entries):
247
248
  raise ImproperlyConfigured("Root INSTALLED_APPS entries must be native app strings")
248
- root_configs = tuple((entry, AppConfig.create(entry)) for entry in root_entries)
249
+ resolved: dict[str, AppConfig] = {}
250
+
251
+ def resolve(entry: str) -> AppConfig:
252
+ if entry not in resolved:
253
+ resolved[entry] = AppConfig.create(entry)
254
+ return resolved[entry]
255
+
256
+ root_configs = tuple((entry, resolve(entry)) for entry in root_entries)
249
257
  normalized_roots = app_entries(Entry.from_config(config, entry) for entry, config in root_configs)
250
258
  root_names = tuple(entry.name for entry in normalized_roots)
251
259
  root_set = frozenset(root_names)
@@ -256,7 +264,7 @@ def enabled_apps(roots: Iterable[str], *, group: str | None = None) -> Closure:
256
264
  def component_entry(provider: str) -> str:
257
265
  assert installed is not None
258
266
  point = installed.entry_points[provider]
259
- config = AppConfig.create(point.value)
267
+ config = resolve(point.value)
260
268
  if config.name != point.name:
261
269
  raise ImproperlyConfigured(
262
270
  f"Entry point {point.name!r} from {provider!r} selects app {config.name!r}"
@@ -264,7 +272,7 @@ def enabled_apps(roots: Iterable[str], *, group: str | None = None) -> Closure:
264
272
  return point.value
265
273
 
266
274
  def choose(entry: str) -> str:
267
- config = AppConfig.create(entry)
275
+ config = resolve(entry)
268
276
  previous = selected.get(config.name)
269
277
  if previous is None:
270
278
  selected[config.name] = (entry, config)
@@ -100,7 +100,7 @@ def _fallback_inputs() -> None:
100
100
  from django_compose.sources import SourceResolver
101
101
 
102
102
  try:
103
- location = SourceResolver(()).resolve(module)
103
+ location = SourceResolver().locate(module)
104
104
  if location.path is not None:
105
105
  report_inputs(files=[location.path])
106
106
  except ImportError, ImproperlyConfigured, ValueError:
@@ -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,7 @@ class TransitionPlan:
153
153
  dependencies: tuple[Node, ...]
154
154
  run_before: tuple[Node, ...]
155
155
  source_package: str
156
+ initial_baseline: bool = False
156
157
 
157
158
 
158
159
  @dataclass(frozen=True)
@@ -164,6 +165,7 @@ class _Source:
164
165
  text: str
165
166
  digest: str
166
167
  package: str
168
+ initial_baseline: bool
167
169
 
168
170
 
169
171
  class _BindingLoader(MigrationLoader):
@@ -208,8 +210,9 @@ class TransitionBinding:
208
210
  """Bind declared migrations to host leaves without connecting to a database.
209
211
 
210
212
  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.
213
+ 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.
213
216
  """
214
217
 
215
218
  def __init__(
@@ -309,7 +312,16 @@ class TransitionBinding:
309
312
  if len(leaves) == 1 and leaves[0] not in migration.dependencies:
310
313
  cast(list[Node], migration.dependencies).append(leaves[0])
311
314
  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)
315
+ pending[key] = _Source(
316
+ origin,
317
+ migration,
318
+ guard,
319
+ path,
320
+ data.decode("utf-8"),
321
+ digest,
322
+ package,
323
+ declaration.get("initial_baseline") == "satisfied",
324
+ )
313
325
  return pending
314
326
 
315
327
  def plan(
@@ -319,6 +331,7 @@ class TransitionBinding:
319
331
  defer_drop_check: bool = False,
320
332
  app_labels: Iterable[str] | None = None,
321
333
  allow_missing_packages: bool = False,
334
+ initial_baselines: frozenset[str] = frozenset(),
322
335
  ) -> tuple[TransitionPlan, ...]:
323
336
  """Validate the complete graph and selected prerequisite closure, without writes."""
324
337
  existing = MigrationLoader(None, ignore_no_migrations=True)
@@ -354,7 +367,17 @@ class TransitionBinding:
354
367
  raise RuntimeError(f"{source.origin}: applies(project_state) failed") from error
355
368
  if not isinstance(applies, bool):
356
369
  raise RuntimeError(f"{source.origin}: applies must return bool")
357
- if not applies:
370
+ baseline = not applies and source.initial_baseline and key[0] in initial_baselines
371
+ if baseline:
372
+ # A native empty migration also omits source-class lifecycle
373
+ # 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
380
+ elif not applies:
358
381
  raise RuntimeError(
359
382
  f"{source.origin}: false guard cannot prove a data transition completed; "
360
383
  "retain native history or a complete replacement baseline"
@@ -379,6 +402,7 @@ class TransitionBinding:
379
402
  tuple(source.migration.dependencies),
380
403
  tuple(source.migration.run_before),
381
404
  source.package,
405
+ baseline,
382
406
  )
383
407
  )
384
408
  if apps is not None and not defer_drop_check:
@@ -456,30 +480,69 @@ class TransitionBinding:
456
480
  body.decode()
457
481
  + MATERIALIZED_FOOTER
458
482
  + "\n"
483
+ + (
484
+ "from django.db.migrations import Migration as _ComposeInitialBaselineMigration\n"
485
+ "class Migration(_ComposeInitialBaselineMigration):\n"
486
+ " operations = []\n"
487
+ if plan.initial_baseline
488
+ else ""
489
+ )
459
490
  + f"Migration.dependencies = {list(plan.dependencies)!r}\n"
460
491
  + f"Migration.run_before = {list(plan.run_before)!r}\n"
461
492
  + f"Migration.compose_origin = {plan.origin!r}\n"
462
493
  + f"Migration.compose_source_sha256 = {plan.source_sha256!r}\n"
463
494
  + f"Migration.compose_body_sha256 = {body_digest!r}\n"
495
+ + ("Migration.compose_initial_baseline = 'satisfied'\n" if plan.initial_baseline else "")
464
496
  ).encode()
465
497
  return payload + _SEAL_PREFIX + repr(hashlib.sha256(payload).hexdigest()).encode() + b"\n"
466
498
 
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)
499
+ def materialize(
500
+ self,
501
+ apps: Apps,
502
+ app_labels: Iterable[str] | None = None,
503
+ *,
504
+ initial_baselines: frozenset[str] = frozenset(),
505
+ written_files: list[Path] | None = None,
506
+ ) -> tuple[Path, ...]:
507
+ """Snapshot sources, optionally satisfying declared first-authoring baselines.
508
+
509
+ initial_baselines is the command's exact newly initialized disk-label
510
+ delta, never inferred from initial-looking files or database contents.
511
+ written_files tracks exclusive destinations for an enclosing native
512
+ authoring rollback, including a write that raises after publication.
513
+ """
514
+ plans = self.plan(
515
+ apps=apps,
516
+ app_labels=app_labels,
517
+ allow_missing_packages=True,
518
+ initial_baselines=initial_baselines,
519
+ )
470
520
  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 = []
521
+ packages = [
522
+ directory / "__init__.py"
523
+ for label in dict.fromkeys(plan.app_label for plan in plans)
524
+ for directory in (_directory(label, missing=True),)
525
+ if not (directory / "__init__.py").exists()
526
+ ]
527
+ written: list[Path] = []
477
528
  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)
529
+ for path, content in [
530
+ *((path, b"") for path in packages),
531
+ *((plan.output_path, content) for plan, content in rendered),
532
+ ]:
533
+ if path.exists():
534
+ raise RuntimeError(f"Migration destination appeared during authoring: {path}")
535
+ written.append(path)
536
+ if written_files is not None:
537
+ written_files.append(path)
538
+ try:
539
+ atomic_write(path, content, exclusive=True)
540
+ except FileExistsError:
541
+ # Exclusive publication lost a race; that file is not ours.
542
+ written.pop()
543
+ if written_files is not None:
544
+ written_files.pop()
545
+ raise
483
546
  importlib.invalidate_caches()
484
547
  self.plan(apps=apps, app_labels=app_labels)
485
548
  except BaseException:
@@ -487,7 +550,7 @@ class TransitionBinding:
487
550
  path.unlink(missing_ok=True)
488
551
  _forget_history({plan.app_label for plan in plans})
489
552
  raise
490
- return tuple(written)
553
+ return tuple(plan.output_path for plan in plans)
491
554
 
492
555
 
493
556
  def _storage_identifier(connection: BaseDatabaseWrapper, identifier: str) -> tuple[str, str]:
@@ -563,6 +626,9 @@ def _allows_migrate_model(operation: Operation, alias: str, model: Any, *, offli
563
626
 
564
627
  def _model_storage(model: Any, *, removed_field: str | None = None) -> Iterator[Any]:
565
628
  """Tables deleted by native model deletion or implicit M2M field removal."""
629
+ # Django intentionally creates no implicit through classes for swapped models.
630
+ if model._meta.swapped:
631
+ return
566
632
  if removed_field is None:
567
633
  yield model
568
634
  fields = model._meta.local_many_to_many
@@ -791,13 +857,21 @@ class DropGuardAutodetector(MigrationAutodetector):
791
857
  )
792
858
 
793
859
 
794
- def _forget_history(labels: Iterable[str]) -> None:
795
- prefixes = [MigrationLoader.migrations_module(label)[0] for label in labels]
860
+ def _forget_history(labels: Iterable[str], *, packages: Mapping[str, Path] | None = None) -> None:
861
+ # Native writer observation can retain paths even when restored package
862
+ # initializers no longer import successfully. Do not execute them to clean
863
+ # their import caches, or leave newly authored ancestor packages cached.
864
+ directories = dict(packages or {})
865
+ for label in labels:
866
+ package = MigrationLoader.migrations_module(label)[0]
867
+ if package is not None and package not in directories:
868
+ directories[package] = _directory(label, missing=True)
869
+ prefixes = tuple(directories)
796
870
  for name in tuple(sys.modules):
797
871
  if any(prefix and (name == prefix or name.startswith(prefix + ".")) for prefix in prefixes):
798
872
  sys.modules.pop(name, None)
799
- for label in labels:
800
- for bytecode in (_directory(label) / "__pycache__").glob("*.pyc"):
873
+ for directory in set(directories.values()):
874
+ for bytecode in (directory / "__pycache__").glob("*.pyc"):
801
875
  bytecode.unlink()
802
876
  importlib.invalidate_caches()
803
877
 
django_compose/serving.py CHANGED
@@ -186,7 +186,7 @@ def read_receipt(output_module: Path | str) -> Receipt | None:
186
186
 
187
187
 
188
188
  def output_directory(output_module: str) -> Path:
189
- source = SourceResolver().resolve(output_module)
189
+ source = SourceResolver().locate(output_module)
190
190
  if len(source.search_locations) != 1:
191
191
  raise ImproperlyConfigured(f"Missing generated package {output_module!r}; run compose")
192
192
  root = source.search_locations[0]
@@ -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"
@@ -235,7 +242,7 @@ def _fingerprints(
235
242
  ) -> tuple[tuple[str, str], ...]:
236
243
  result = []
237
244
  for declaration in records:
238
- location = resolver.resolve(declaration["module"])
245
+ location = resolver.locate(declaration["module"])
239
246
  if location.path is not None:
240
247
  report_inputs(files=[location.path])
241
248
  if location.path is None or not location.path.is_file():
@@ -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
@@ -388,7 +395,7 @@ def snapshot(
388
395
  if owner is not object:
389
396
  modules[f"config:{owner.__module__}"] = owner.__module__
390
397
  for key, module in sorted(modules.items()):
391
- location = resolver.resolve(module)
398
+ location = resolver.locate(module)
392
399
  if location.path is not None:
393
400
  report_inputs(files=[location.path])
394
401
  if location.kind in {"builtin", "frozen"}:
django_compose/sources.py CHANGED
@@ -6,7 +6,7 @@ import json
6
6
  import sys
7
7
  import sysconfig
8
8
  from collections.abc import Iterable
9
- from dataclasses import dataclass
9
+ from dataclasses import dataclass, replace
10
10
  from importlib import metadata
11
11
  from importlib.machinery import BuiltinImporter, FrozenImporter, ModuleSpec, PathFinder
12
12
  from pathlib import Path
@@ -93,12 +93,12 @@ class SourceResolver:
93
93
  search = list(spec.submodule_search_locations)
94
94
  return None
95
95
 
96
- def resolve(self, module: str) -> ModuleSource:
96
+ def _locate(self, module: str) -> tuple[ModuleSource, tuple[Path, ...]]:
97
97
  if not module or not all(part and ("_" + part).isidentifier() for part in module.split(".")):
98
- return ModuleSource(module, None, "unresolved")
98
+ return ModuleSource(module, None, "unresolved"), ()
99
99
  for finder, kind in ((BuiltinImporter, "builtin"), (FrozenImporter, "frozen")):
100
100
  if finder.find_spec(module) is not None:
101
- return ModuleSource(module, None, kind)
101
+ return ModuleSource(module, None, kind), ()
102
102
  spec = None
103
103
  for entry in self.entries:
104
104
  if module == entry.name:
@@ -114,11 +114,11 @@ class SourceResolver:
114
114
  if spec is None:
115
115
  spec = self._find(module.split("."))
116
116
  if spec is None:
117
- return ModuleSource(module, None, "unresolved")
117
+ return ModuleSource(module, None, "unresolved"), ()
118
118
  locations = tuple(Path(path).resolve() for path in spec.submodule_search_locations or ())
119
119
  path = Path(spec.origin).resolve() if spec.origin else next(iter(locations), None)
120
120
  if path is None:
121
- return ModuleSource(module, None, "unresolved")
121
+ return ModuleSource(module, None, "unresolved"), ()
122
122
  paths = sysconfig.get_paths()
123
123
  site_roots = {Path(paths[key]).resolve() for key in ("purelib", "platlib")}
124
124
  if (
@@ -126,18 +126,26 @@ class SourceResolver:
126
126
  and path.is_relative_to(Path(paths["stdlib"]).resolve())
127
127
  and not any(path.is_relative_to(root) for root in site_roots)
128
128
  ):
129
- return ModuleSource(module, path, "stdlib")
129
+ return ModuleSource(module, path, "stdlib"), ()
130
130
  ownership_paths = (path,) if spec.origin else locations
131
- names = tuple(
132
- sorted({name for source in ownership_paths for name in self.distribution_names(source)})
133
- )
134
131
  app = next(
135
132
  (entry.name for entry in self.entries if path.is_relative_to(Path(entry.path).resolve())), None
136
133
  )
137
- return ModuleSource(
138
- module, path, "distribution" if names else "app" if app else "project", names, app, locations
134
+ return (
135
+ ModuleSource(module, path, "app" if app else "project", app=app, search_locations=locations),
136
+ ownership_paths,
139
137
  )
140
138
 
139
+ def locate(self, module: str) -> ModuleSource:
140
+ """Locate without imports or distribution metadata; kind excludes installed ownership."""
141
+ return self._locate(module)[0]
142
+
143
+ def resolve(self, module: str) -> ModuleSource:
144
+ """Locate and attribute exact installed ownership, indexing metadata once per resolver."""
145
+ source, ownership_paths = self._locate(module)
146
+ names = tuple(sorted({name for path in ownership_paths for name in self.distribution_names(path)}))
147
+ return replace(source, kind="distribution", distributions=names) if names else source
148
+
141
149
 
142
150
  def resolve_module(module: str, entries: Iterable[AppSource] = ()) -> ModuleSource:
143
151
  return SourceResolver(entries).resolve(module)
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.5
2
2
  Name: django-compose
3
- Version: 0.1.0.dev3
3
+ Version: 0.1.0.dev6
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
@@ -7,35 +7,35 @@ django_compose/autoreload.py,sha256=Obguzio30T42nIjSX9HVmrU-CqtTrm7moU0Wd271Egg,
7
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=k42JmMTnH-Xl_26qqk8dUiwjsnf35oMZnCecObvzTLU,14267
10
+ django_compose/components.py,sha256=jNMkWm0Q15dbmVkK3jBdM_ldgqilFitvrfGaRHxmXx0,14518
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
14
  django_compose/migration_imports.py,sha256=vyg8NdUCl977HrdfBkz642x0ra_btaRdCqZEfQs4V2o,22011
15
- django_compose/migrations.py,sha256=P_Tz7WdlgoXzxHwzJIjAM31F7HgHlaQdn7LHZHH4q50,49343
15
+ django_compose/migrations.py,sha256=N41itYT4TyJ3kFHoJmlK5l_gJDk9vuh7QeyAmfj6pvY,52548
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
- django_compose/serving.py,sha256=kOEKik7Oe0CLDmGviHjtP3z3ZUn8xnjdG0z53WMM0KY,15499
22
- django_compose/snapshot.py,sha256=V7oxltGssttISZ7zPtIjuPA5fBOvzWbD2e4UdkEnPus,17732
23
- django_compose/sources.py,sha256=zusV-sFM9KnW6zyb05Dvag1APU_ABZlqL47W1xwvssI,6094
21
+ django_compose/serving.py,sha256=FoS3TNNpgPGLpfCHtGrW0JVJVT9DyI7sxJ5U4x0oVLU,15498
22
+ django_compose/snapshot.py,sha256=J4a3eKa2V6cIIKXfvLiiqe6lWENbDCAKIV5CJC5Fjnc,18344
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=p9ZFdX92SHN9RHeSN4dTgt6Oe3DhKq0LbiTaPRz7tSY,8727
26
+ django_compose/management/__init__.py,sha256=wBX58M8MHUEvl9M57wVNNDAq4lsCSLjPtM3Copabs2w,8724
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
29
29
  django_compose/management/commands/compose.py,sha256=UuNjIgNwYOYE_1aKIcEvh3C1fMjP9tdN_-SDDwVQjIc,1860
30
- django_compose/management/commands/makemigrations.py,sha256=CliPK4u1SRK-_Ww0zuG8M_FWCl_ku4Aje7czW1Y8hjg,6087
30
+ django_compose/management/commands/makemigrations.py,sha256=GIoz23DbHDArWQqR9BDp_dOAQf3YLdus5MUp6HDvGxs,10809
31
31
  django_compose/management/commands/migrate.py,sha256=_MkiQRjQRwIr9dEUnKk4WEjLgz5FTH_Tmn6ZkKHgOMA,589
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.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,,
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,,