django-compose 0.1.0.dev9__tar.gz → 0.1.0.dev11__tar.gz

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.
Files changed (105) hide show
  1. {django_compose-0.1.0.dev9 → django_compose-0.1.0.dev11}/CHANGELOG.md +20 -0
  2. {django_compose-0.1.0.dev9 → django_compose-0.1.0.dev11}/PKG-INFO +1 -1
  3. {django_compose-0.1.0.dev9 → django_compose-0.1.0.dev11}/docs/SPEC.md +7 -0
  4. {django_compose-0.1.0.dev9 → django_compose-0.1.0.dev11}/docs/components.md +7 -2
  5. {django_compose-0.1.0.dev9 → django_compose-0.1.0.dev11}/pyproject.toml +1 -1
  6. {django_compose-0.1.0.dev9 → django_compose-0.1.0.dev11}/src/django_compose/components.py +34 -1
  7. {django_compose-0.1.0.dev9 → django_compose-0.1.0.dev11}/src/django_compose/sources.py +41 -32
  8. {django_compose-0.1.0.dev9 → django_compose-0.1.0.dev11}/tests/test_components.py +26 -0
  9. django_compose-0.1.0.dev11/tests/test_sources.py +280 -0
  10. {django_compose-0.1.0.dev9 → django_compose-0.1.0.dev11}/uv.lock +1 -1
  11. django_compose-0.1.0.dev9/tests/test_sources.py +0 -138
  12. {django_compose-0.1.0.dev9 → django_compose-0.1.0.dev11}/.gitignore +0 -0
  13. {django_compose-0.1.0.dev9 → django_compose-0.1.0.dev11}/AGENTS.md +0 -0
  14. {django_compose-0.1.0.dev9 → django_compose-0.1.0.dev11}/CONTRIBUTING.md +0 -0
  15. {django_compose-0.1.0.dev9 → django_compose-0.1.0.dev11}/COPYING +0 -0
  16. {django_compose-0.1.0.dev9 → django_compose-0.1.0.dev11}/LICENSE +0 -0
  17. {django_compose-0.1.0.dev9 → django_compose-0.1.0.dev11}/Makefile +0 -0
  18. {django_compose-0.1.0.dev9 → django_compose-0.1.0.dev11}/NOTICE +0 -0
  19. {django_compose-0.1.0.dev9 → django_compose-0.1.0.dev11}/README.md +0 -0
  20. {django_compose-0.1.0.dev9 → django_compose-0.1.0.dev11}/docs/README.md +0 -0
  21. {django_compose-0.1.0.dev9 → django_compose-0.1.0.dev11}/docs/ROADMAP.md +0 -0
  22. {django_compose-0.1.0.dev9 → django_compose-0.1.0.dev11}/docs/api.md +0 -0
  23. {django_compose-0.1.0.dev9 → django_compose-0.1.0.dev11}/docs/configuration.md +0 -0
  24. {django_compose-0.1.0.dev9 → django_compose-0.1.0.dev11}/docs/dependencies.md +0 -0
  25. {django_compose-0.1.0.dev9 → django_compose-0.1.0.dev11}/docs/extensions.md +0 -0
  26. {django_compose-0.1.0.dev9 → django_compose-0.1.0.dev11}/docs/migrations.md +0 -0
  27. {django_compose-0.1.0.dev9 → django_compose-0.1.0.dev11}/docs/models.md +0 -0
  28. {django_compose-0.1.0.dev9 → django_compose-0.1.0.dev11}/docs/packaging.md +0 -0
  29. {django_compose-0.1.0.dev9 → django_compose-0.1.0.dev11}/docs/proposals/0001-native-url-collisions.md +0 -0
  30. {django_compose-0.1.0.dev9 → django_compose-0.1.0.dev11}/docs/proposals/0002-supplied-distribution-metadata.md +0 -0
  31. {django_compose-0.1.0.dev9 → django_compose-0.1.0.dev11}/docs/proposals/0004-serving-boundary.md +0 -0
  32. {django_compose-0.1.0.dev9 → django_compose-0.1.0.dev11}/docs/proposals/README.md +0 -0
  33. {django_compose-0.1.0.dev9 → django_compose-0.1.0.dev11}/docs/provisioning.md +0 -0
  34. {django_compose-0.1.0.dev9 → django_compose-0.1.0.dev11}/docs/quickstart.md +0 -0
  35. {django_compose-0.1.0.dev9 → django_compose-0.1.0.dev11}/examples/shop/.gitignore +0 -0
  36. {django_compose-0.1.0.dev9 → django_compose-0.1.0.dev11}/examples/shop/README.md +0 -0
  37. {django_compose-0.1.0.dev9 → django_compose-0.1.0.dev11}/examples/shop/catalog/__init__.py +0 -0
  38. {django_compose-0.1.0.dev9 → django_compose-0.1.0.dev11}/examples/shop/catalog/apps.py +0 -0
  39. {django_compose-0.1.0.dev9 → django_compose-0.1.0.dev11}/examples/shop/catalog/autoconfig.py +0 -0
  40. {django_compose-0.1.0.dev9 → django_compose-0.1.0.dev11}/examples/shop/catalog/integrations.py +0 -0
  41. {django_compose-0.1.0.dev9 → django_compose-0.1.0.dev11}/examples/shop/catalog/models.py +0 -0
  42. {django_compose-0.1.0.dev9 → django_compose-0.1.0.dev11}/examples/shop/catalog/pyproject.toml +0 -0
  43. {django_compose-0.1.0.dev9 → django_compose-0.1.0.dev11}/examples/shop/catalog/schema.py +0 -0
  44. {django_compose-0.1.0.dev9 → django_compose-0.1.0.dev11}/examples/shop/catalog/urls.py +0 -0
  45. {django_compose-0.1.0.dev9 → django_compose-0.1.0.dev11}/examples/shop/manage.py +0 -0
  46. {django_compose-0.1.0.dev9 → django_compose-0.1.0.dev11}/examples/shop/reviews/__init__.py +0 -0
  47. {django_compose-0.1.0.dev9 → django_compose-0.1.0.dev11}/examples/shop/reviews/apps.py +0 -0
  48. {django_compose-0.1.0.dev9 → django_compose-0.1.0.dev11}/examples/shop/reviews/autoconfig.py +0 -0
  49. {django_compose-0.1.0.dev9 → django_compose-0.1.0.dev11}/examples/shop/reviews/models.py +0 -0
  50. {django_compose-0.1.0.dev9 → django_compose-0.1.0.dev11}/examples/shop/reviews/pyproject.toml +0 -0
  51. {django_compose-0.1.0.dev9 → django_compose-0.1.0.dev11}/examples/shop/settings.py +0 -0
  52. {django_compose-0.1.0.dev9 → django_compose-0.1.0.dev11}/examples/shop/urls.py +0 -0
  53. {django_compose-0.1.0.dev9 → django_compose-0.1.0.dev11}/examples/shop/verify.py +0 -0
  54. {django_compose-0.1.0.dev9 → django_compose-0.1.0.dev11}/scripts/check_distribution.py +0 -0
  55. {django_compose-0.1.0.dev9 → django_compose-0.1.0.dev11}/src/django_compose/__init__.py +0 -0
  56. {django_compose-0.1.0.dev9 → django_compose-0.1.0.dev11}/src/django_compose/__main__.py +0 -0
  57. {django_compose-0.1.0.dev9 → django_compose-0.1.0.dev11}/src/django_compose/apps.py +0 -0
  58. {django_compose-0.1.0.dev9 → django_compose-0.1.0.dev11}/src/django_compose/artifacts.py +0 -0
  59. {django_compose-0.1.0.dev9 → django_compose-0.1.0.dev11}/src/django_compose/autoreload.py +0 -0
  60. {django_compose-0.1.0.dev9 → django_compose-0.1.0.dev11}/src/django_compose/build.py +0 -0
  61. {django_compose-0.1.0.dev9 → django_compose-0.1.0.dev11}/src/django_compose/cli.py +0 -0
  62. {django_compose-0.1.0.dev9 → django_compose-0.1.0.dev11}/src/django_compose/conf.py +0 -0
  63. {django_compose-0.1.0.dev9 → django_compose-0.1.0.dev11}/src/django_compose/declarations.py +0 -0
  64. {django_compose-0.1.0.dev9 → django_compose-0.1.0.dev11}/src/django_compose/history.py +0 -0
  65. {django_compose-0.1.0.dev9 → django_compose-0.1.0.dev11}/src/django_compose/management/__init__.py +0 -0
  66. {django_compose-0.1.0.dev9 → django_compose-0.1.0.dev11}/src/django_compose/management/commands/__init__.py +0 -0
  67. {django_compose-0.1.0.dev9 → django_compose-0.1.0.dev11}/src/django_compose/management/commands/check_migrations.py +0 -0
  68. {django_compose-0.1.0.dev9 → django_compose-0.1.0.dev11}/src/django_compose/management/commands/compose.py +0 -0
  69. {django_compose-0.1.0.dev9 → django_compose-0.1.0.dev11}/src/django_compose/management/commands/makemigrations.py +0 -0
  70. {django_compose-0.1.0.dev9 → django_compose-0.1.0.dev11}/src/django_compose/management/commands/migrate.py +0 -0
  71. {django_compose-0.1.0.dev9 → django_compose-0.1.0.dev11}/src/django_compose/management/commands/provision.py +0 -0
  72. {django_compose-0.1.0.dev9 → django_compose-0.1.0.dev11}/src/django_compose/management/commands/reset_migration_history.py +0 -0
  73. {django_compose-0.1.0.dev9 → django_compose-0.1.0.dev11}/src/django_compose/management/commands/retire_history.py +0 -0
  74. {django_compose-0.1.0.dev9 → django_compose-0.1.0.dev11}/src/django_compose/migration_imports.py +0 -0
  75. {django_compose-0.1.0.dev9 → django_compose-0.1.0.dev11}/src/django_compose/migrations.py +0 -0
  76. {django_compose-0.1.0.dev9 → django_compose-0.1.0.dev11}/src/django_compose/model_composition.py +0 -0
  77. {django_compose-0.1.0.dev9 → django_compose-0.1.0.dev11}/src/django_compose/models.py +0 -0
  78. {django_compose-0.1.0.dev9 → django_compose-0.1.0.dev11}/src/django_compose/provision.py +0 -0
  79. {django_compose-0.1.0.dev9 → django_compose-0.1.0.dev11}/src/django_compose/py.typed +0 -0
  80. {django_compose-0.1.0.dev9 → django_compose-0.1.0.dev11}/src/django_compose/rendering.py +0 -0
  81. {django_compose-0.1.0.dev9 → django_compose-0.1.0.dev11}/src/django_compose/serving.py +0 -0
  82. {django_compose-0.1.0.dev9 → django_compose-0.1.0.dev11}/src/django_compose/snapshot.py +0 -0
  83. {django_compose-0.1.0.dev9 → django_compose-0.1.0.dev11}/src/django_compose/typing.py +0 -0
  84. {django_compose-0.1.0.dev9 → django_compose-0.1.0.dev11}/tests/core_fixtures/__init__.py +0 -0
  85. {django_compose-0.1.0.dev9 → django_compose-0.1.0.dev11}/tests/test_artifacts.py +0 -0
  86. {django_compose-0.1.0.dev9 → django_compose-0.1.0.dev11}/tests/test_autoreload.py +0 -0
  87. {django_compose-0.1.0.dev9 → django_compose-0.1.0.dev11}/tests/test_bootstrap.py +0 -0
  88. {django_compose-0.1.0.dev9 → django_compose-0.1.0.dev11}/tests/test_boundaries.py +0 -0
  89. {django_compose-0.1.0.dev9 → django_compose-0.1.0.dev11}/tests/test_conf.py +0 -0
  90. {django_compose-0.1.0.dev9 → django_compose-0.1.0.dev11}/tests/test_history.py +0 -0
  91. {django_compose-0.1.0.dev9 → django_compose-0.1.0.dev11}/tests/test_initial_history.py +0 -0
  92. {django_compose-0.1.0.dev9 → django_compose-0.1.0.dev11}/tests/test_integrations.py +0 -0
  93. {django_compose-0.1.0.dev9 → django_compose-0.1.0.dev11}/tests/test_launcher.py +0 -0
  94. {django_compose-0.1.0.dev9 → django_compose-0.1.0.dev11}/tests/test_migration_imports.py +0 -0
  95. {django_compose-0.1.0.dev9 → django_compose-0.1.0.dev11}/tests/test_migration_scaffold.py +0 -0
  96. {django_compose-0.1.0.dev9 → django_compose-0.1.0.dev11}/tests/test_migrations.py +0 -0
  97. {django_compose-0.1.0.dev9 → django_compose-0.1.0.dev11}/tests/test_migrations_guards.py +0 -0
  98. {django_compose-0.1.0.dev9 → django_compose-0.1.0.dev11}/tests/test_migrations_postgres.py +0 -0
  99. {django_compose-0.1.0.dev9 → django_compose-0.1.0.dev11}/tests/test_models.py +0 -0
  100. {django_compose-0.1.0.dev9 → django_compose-0.1.0.dev11}/tests/test_provision.py +0 -0
  101. {django_compose-0.1.0.dev9 → django_compose-0.1.0.dev11}/tests/test_provision_postgres.py +0 -0
  102. {django_compose-0.1.0.dev9 → django_compose-0.1.0.dev11}/tests/test_snapshot.py +0 -0
  103. {django_compose-0.1.0.dev9 → django_compose-0.1.0.dev11}/tests/test_startup.py +0 -0
  104. {django_compose-0.1.0.dev9 → django_compose-0.1.0.dev11}/tests/test_typing.py +0 -0
  105. {django_compose-0.1.0.dev9 → django_compose-0.1.0.dev11}/tests/typing_fixtures/__init__.py +0 -0
@@ -1,5 +1,25 @@
1
1
  # Changelog
2
2
 
3
+ ## 0.1.0.dev11
4
+
5
+ - Reuse the `installed_components(group)` index for the same group and `sys.path`
6
+ until `importlib.invalidate_caches()` runs, instead of re-reading every installed
7
+ distribution's metadata on each call: with 280 distributions a call fell from
8
+ about 40 ms to a lookup. A process that installs or writes distribution metadata
9
+ at runtime invalidates the import caches before indexing again, as before
10
+ importing new modules. Code that replaces `importlib.metadata` functions, such
11
+ as a test that monkeypatches `metadata.distributions`, must call
12
+ `importlib.invalidate_caches()` too; `monkeypatch.syspath_prepend` already does.
13
+ - Register the cache's invalidation hook on `sys.meta_path` once per process,
14
+ including across `importlib.reload` of `django_compose.components`.
15
+
16
+ ## 0.1.0.dev10
17
+
18
+ - Answer directory and editable-project distribution ownership by key from the one
19
+ audit index instead of scanning every recorded file per lookup.
20
+ - Attribute zip-imported namespace portions to the distributions recording files
21
+ inside them, so removal audits retain those providers.
22
+
3
23
  ## 0.1.0.dev9
4
24
 
5
25
  - Remove the URL/ASGI serving and command-context seams; consumers own serving
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.5
2
2
  Name: django-compose
3
- Version: 0.1.0.dev9
3
+ Version: 0.1.0.dev11
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
@@ -166,6 +166,13 @@ nor checks importability, actual AppConfig identity or installed dependencies.
166
166
 
167
167
  `components.installed_components(group)` selects each canonical installed name's
168
168
  native `metadata.distribution()` winner, then delegates to that same index owner.
169
+ The index is reused for the same group and `sys.path` until
170
+ `importlib.invalidate_caches()` runs. A process that installs or writes
171
+ distribution metadata at runtime invalidates the import caches before indexing
172
+ again, as it must before importing modules written at runtime. Code that
173
+ replaces `importlib.metadata` functions, such as a test that monkeypatches
174
+ `metadata.distributions`, must call `importlib.invalidate_caches()` too;
175
+ pytest's `monkeypatch.syspath_prepend` already calls it.
169
176
  `active_requirements(iterable_of_strings)` and the index method
170
177
  `active_requirements(provider)` return native Requirement values active with
171
178
  `extra=""`. Metadata inspection does not activate apps.
@@ -145,8 +145,13 @@ an explicitly empty or invalid group fails. `configure` uses this same helper.
145
145
 
146
146
  `installed_components(group)` returns an `InstalledComponents` index of native
147
147
  distribution and entry-point objects without importing apps or loading entry
148
- points. To inspect metadata prepared separately by a package build backend, pass
149
- native `Distribution` objects to the same indexing owner:
148
+ points. The index is reused for the same group and `sys.path`; after installing
149
+ or writing distribution metadata at runtime, call `importlib.invalidate_caches()`
150
+ before indexing again, as before importing new modules. Code that replaces
151
+ `importlib.metadata` functions, such as a test that monkeypatches
152
+ `metadata.distributions`, must call it too; pytest's `monkeypatch.syspath_prepend`
153
+ already does. To inspect metadata prepared separately by a package build
154
+ backend, pass native `Distribution` objects to the same indexing owner:
150
155
 
151
156
  ```python
152
157
  from importlib.metadata import Distribution
@@ -4,7 +4,7 @@ build-backend = "hatchling.build"
4
4
 
5
5
  [project]
6
6
  name = "django-compose"
7
- version = "0.1.0.dev9"
7
+ version = "0.1.0.dev11"
8
8
  description = "Compose reusable Django apps into a runnable project."
9
9
  readme = "README.md"
10
10
  requires-python = ">=3.14"
@@ -2,6 +2,7 @@
2
2
 
3
3
  from __future__ import annotations
4
4
 
5
+ import functools
5
6
  import json
6
7
  import math
7
8
  import os
@@ -218,8 +219,18 @@ def index_components(distributions: Iterable[metadata.Distribution], *, group: s
218
219
 
219
220
 
220
221
  def installed_components(group: str) -> InstalledComponents:
221
- """Index installed metadata using native same-name installation precedence."""
222
+ """Index installed metadata using native same-name installation precedence.
222
223
 
224
+ The index is reused for the same group and import path until
225
+ importlib.invalidate_caches() runs, which a process that installs or writes
226
+ distribution metadata at runtime calls before discovering it, as for imports.
227
+ Code that replaces importlib.metadata functions must call it too.
228
+ """
229
+ return _installed_components(group, tuple(sys.path))
230
+
231
+
232
+ @functools.lru_cache(maxsize=8)
233
+ def _installed_components(group: str, path: tuple[str, ...]) -> InstalledComponents:
223
234
  def distributions() -> Iterator[metadata.Distribution]:
224
235
  names = {canonicalize_name(dist.metadata["Name"]) for dist in metadata.distributions()}
225
236
  for name in sorted(names):
@@ -228,6 +239,28 @@ def installed_components(group: str) -> InstalledComponents:
228
239
  return index_components(distributions(), group=group)
229
240
 
230
241
 
242
+ class _InstalledComponentsFinder:
243
+ """Find nothing; let importlib.invalidate_caches() clear the installed index."""
244
+
245
+ @staticmethod
246
+ def find_spec(*args: object) -> None:
247
+ return None
248
+
249
+ @staticmethod
250
+ def invalidate_caches() -> None:
251
+ _installed_components.cache_clear()
252
+
253
+
254
+ # A reload re-runs this module in the same namespace, where a registered finder
255
+ # already clears the new cache; register once per process.
256
+ if not any(
257
+ getattr(finder, "__module__", None) == __name__
258
+ and getattr(finder, "__qualname__", None) == _InstalledComponentsFinder.__qualname__
259
+ for finder in sys.meta_path
260
+ ):
261
+ sys.meta_path.append(_InstalledComponentsFinder)
262
+
263
+
231
264
  def enabled_apps(roots: Iterable[str], *, group: str | None = None) -> Closure:
232
265
  """Expand explicit roots using installed providers and selected requires_apps.
233
266
 
@@ -9,6 +9,7 @@ from collections.abc import Iterable
9
9
  from dataclasses import dataclass, replace
10
10
  from importlib import metadata
11
11
  from importlib.machinery import BuiltinImporter, FrozenImporter, ModuleSpec, PathFinder
12
+ from itertools import chain
12
13
  from pathlib import Path
13
14
  from typing import Protocol
14
15
  from urllib.parse import unquote, urlsplit
@@ -42,41 +43,49 @@ class SourceResolver:
42
43
  distributions: Iterable[metadata.Distribution] | None = None,
43
44
  ) -> None:
44
45
  self.entries = tuple(sorted(entries, key=lambda entry: -len(entry.name)))
45
- self._distributions = distributions
46
- self._files: dict[Path, set[str]] | None = None
47
- self._projects: list[tuple[Path, str]] = []
46
+ # A one-shot iterable is held whole so a failed index build fails again on retry.
47
+ self._distributions = None if distributions is None else tuple(distributions)
48
+ self._owners: dict[Path, set[str]] | None = None
49
+
50
+ def _index(self) -> tuple[dict[Path, set[str]], dict[Path, set[str]]]:
51
+ """Key each resolved RECORD file and its ancestors, and each PEP 610 project, to owners."""
52
+ owners: dict[Path, set[str]] = {}
53
+ projects: dict[Path, set[str]] = {}
54
+ distributions = self._distributions
55
+ for distribution in metadata.distributions() if distributions is None else distributions:
56
+ name = distribution.metadata["Name"]
57
+ if not name:
58
+ continue
59
+ for file in distribution.files or ():
60
+ location = Path(str(distribution.locate_file(file))).resolve()
61
+ for directory in chain((location,), location.parents):
62
+ names = owners.setdefault(directory, set())
63
+ if name in names:
64
+ break # Every further ancestor already records this distribution.
65
+ names.add(name)
66
+ direct = distribution.read_text("direct_url.json")
67
+ if direct:
68
+ try:
69
+ direct_url = json.loads(direct)
70
+ url = urlsplit(direct_url.get("url", ""))
71
+ if "dir_info" in direct_url and url.scheme == "file" and url.netloc in ("", "localhost"):
72
+ projects.setdefault(Path(unquote(url.path)).resolve(), set()).add(name)
73
+ except ValueError, TypeError, AttributeError:
74
+ continue
75
+ return owners, projects
48
76
 
49
77
  def distribution_names(self, path: Path) -> tuple[str, ...]:
50
- """Match RECORD files or a PEP 610 local project directory, never package names."""
51
- if self._files is None:
52
- self._files = {}
53
- distributions = self._distributions
54
- for distribution in metadata.distributions() if distributions is None else distributions:
55
- name = distribution.metadata["Name"]
56
- if not name:
57
- continue
58
- for file in distribution.files or ():
59
- location = Path(str(distribution.locate_file(file))).resolve()
60
- self._files.setdefault(location, set()).add(name)
61
- direct = distribution.read_text("direct_url.json")
62
- if direct:
63
- try:
64
- record = json.loads(direct)
65
- url = urlsplit(record.get("url", ""))
66
- if "dir_info" in record and url.scheme == "file" and url.netloc in ("", "localhost"):
67
- self._projects.append((Path(unquote(url.path)).resolve(), name))
68
- except ValueError, TypeError, AttributeError:
69
- continue
78
+ """Match RECORD files or a PEP 610 local project directory, never package names.
79
+
80
+ A path is owned by every distribution recording a file at or beneath it. Lookups
81
+ read the once-built index by key, so their cost never grows with recorded files.
82
+ """
83
+ if self._owners is None:
84
+ self._owners, self._projects = self._index()
70
85
  location = path.resolve()
71
- names = self._files.get(location, set()).copy()
72
- if location.is_dir():
73
- names.update(
74
- name
75
- for file, owners in self._files.items()
76
- if file.is_relative_to(location)
77
- for name in owners
78
- )
79
- names.update(name for root, name in self._projects if location.is_relative_to(root))
86
+ names = set(self._owners.get(location, ()))
87
+ for directory in chain((location,), location.parents):
88
+ names.update(self._projects.get(directory, ()))
80
89
  return tuple(sorted(names))
81
90
 
82
91
  @staticmethod
@@ -509,6 +509,32 @@ def test_active_requirements_are_native_platform_filtered_and_extra_empty(instal
509
509
  assert str(requirements[1].specifier) == ">=1"
510
510
 
511
511
 
512
+ def test_installed_index_is_reused_until_import_caches_or_the_path_change(installed, monkeypatch, tmp_path):
513
+ installed.distribution("first-provider", app="first_app")
514
+ index = installed_components(GROUP)
515
+ installed.distribution("second-provider", app="second_app")
516
+ assert installed_components(GROUP) is index
517
+ importlib.invalidate_caches()
518
+ assert set(installed_components(GROUP).providers) == {"first_app", "second_app"}
519
+ installed.distribution("third-provider", app="third_app")
520
+ monkeypatch.setattr(sys, "path", [*sys.path, str(tmp_path / "elsewhere")])
521
+ assert set(installed_components(GROUP).providers) == {"first_app", "second_app", "third_app"}
522
+
523
+
524
+ def test_reloaded_components_keep_one_hook_that_clears_the_new_index():
525
+ script = (
526
+ "import importlib, sys\n"
527
+ "from django_compose import components\n"
528
+ "importlib.reload(components)\n"
529
+ "hooks = [f for f in sys.meta_path if getattr(f, '__module__', None) == components.__name__]\n"
530
+ "components.installed_components('testsite.none')\n"
531
+ "importlib.invalidate_caches()\n"
532
+ "print(len(hooks), components._installed_components.cache_info().currsize)\n"
533
+ )
534
+ result = subprocess.run([sys.executable, "-c", script], capture_output=True, text=True, check=True)
535
+ assert result.stdout.split() == ["1", "0"]
536
+
537
+
512
538
  @pytest.mark.parametrize("kind", ("provider", "entries"))
513
539
  def test_installed_index_rejects_metadata_collisions_without_activation(installed, kind):
514
540
  installed.distribution(
@@ -0,0 +1,280 @@
1
+ """One import-free source and exact file ownership seam for every caller."""
2
+
3
+ import gc
4
+ import json
5
+ import sys
6
+ import zipfile
7
+ from importlib import metadata
8
+ from pathlib import Path
9
+
10
+ import pytest
11
+
12
+ from django_compose.snapshot import Entry
13
+ from django_compose.sources import SourceResolver, distribution_names, resolve_module
14
+
15
+
16
+ def distribution(root: Path, name: str, files=(), project: Path | None = None):
17
+ info = root / f"{name}.dist-info"
18
+ info.mkdir(parents=True)
19
+ (info / "METADATA").write_text(f"Metadata-Version: 2.1\nName: {name}\nVersion: 1\n")
20
+ (info / "RECORD").write_text("".join(f"{file},,\n" for file in files))
21
+ if project:
22
+ (info / "direct_url.json").write_text(
23
+ json.dumps({"url": project.as_uri(), "dir_info": {"editable": True}})
24
+ )
25
+ return metadata.PathDistribution(info)
26
+
27
+
28
+ @pytest.mark.parametrize("method", ["locate", "resolve"])
29
+ def test_enabled_app_source_precedes_sys_path_without_importing_packages(tmp_path, monkeypatch, method):
30
+ wrong = tmp_path / "wrong" / "sourceprobe"
31
+ right = tmp_path / "right" / "sourceprobe"
32
+ for root, value in ((wrong, "wrong"), (right, "right")):
33
+ (root / "integrations").mkdir(parents=True)
34
+ (root / "__init__.py").write_text("raise AssertionError('parent executed')")
35
+ (root / "integrations" / "__init__.py").write_text("raise AssertionError('parent executed')")
36
+ (root / "integrations" / "leaf.py").write_text(value)
37
+ monkeypatch.syspath_prepend(str(wrong.parent))
38
+
39
+ def distributions():
40
+ assert method == "resolve", "location must not query distribution metadata"
41
+ return ()
42
+
43
+ monkeypatch.setattr(metadata, "distributions", distributions)
44
+ entry = Entry("sourceprobe", "probe", "django.apps.AppConfig", str(right), "sourceprobe")
45
+ source = getattr(SourceResolver((entry,)), method)("sourceprobe.integrations.leaf")
46
+ assert source.path == right / "integrations/leaf.py"
47
+ assert source.kind == "app"
48
+ assert source.app == "sourceprobe"
49
+ assert not any(name.startswith("sourceprobe") for name in sys.modules)
50
+
51
+
52
+ def test_namespace_location_retains_all_portions_without_distribution_metadata(tmp_path, monkeypatch):
53
+ locations = tuple(tmp_path / name / "namespaceprobe" for name in ("first", "second"))
54
+ for location in locations:
55
+ location.mkdir(parents=True)
56
+ monkeypatch.syspath_prepend(str(location.parent))
57
+ leaf = locations[0] / "leaf.py"
58
+ leaf.write_text("raise AssertionError('must not execute')")
59
+
60
+ def unexpected():
61
+ raise AssertionError("location must not query distribution metadata")
62
+
63
+ monkeypatch.setattr(metadata, "distributions", unexpected)
64
+ resolver = SourceResolver()
65
+ namespace = resolver.locate("namespaceprobe")
66
+ assert namespace.path == locations[1]
67
+ assert namespace.search_locations == tuple(reversed(locations))
68
+ assert namespace.distributions == ()
69
+ assert namespace.kind == "project"
70
+ assert resolver.locate("namespaceprobe.leaf").path == leaf
71
+ assert "namespaceprobe" not in sys.modules
72
+
73
+
74
+ def test_record_ownership_is_exact_for_shared_namespace(tmp_path, monkeypatch):
75
+ package = tmp_path / "sharedprobe"
76
+ package.mkdir()
77
+ first = package / "first.py"
78
+ second = package / "second.py"
79
+ first.write_text("")
80
+ second.write_text("")
81
+ one = distribution(tmp_path, "first-dist", ("sharedprobe/first.py",))
82
+ two = distribution(tmp_path, "second-dist", ("sharedprobe/second.py",))
83
+ monkeypatch.setattr(metadata, "distributions", lambda: (one, two))
84
+ monkeypatch.syspath_prepend(str(tmp_path))
85
+ assert distribution_names(first) == ("first-dist",)
86
+ assert distribution_names(second) == ("second-dist",)
87
+ assert distribution_names(package / "missing.py") == ()
88
+ assert resolve_module("sharedprobe.first").distributions == ("first-dist",)
89
+ namespace = resolve_module("sharedprobe")
90
+ assert namespace.path == package
91
+ assert namespace.search_locations == (package,)
92
+ assert namespace.distributions == ("first-dist", "second-dist")
93
+
94
+
95
+ def test_pep610_project_ownership_uses_directory_boundary(tmp_path):
96
+ project = tmp_path / "editable"
97
+ project.mkdir()
98
+ source = project / "src/pkg/module.py"
99
+ source.parent.mkdir(parents=True)
100
+ source.write_text("")
101
+ native = distribution(tmp_path, "editable-dist", project=project)
102
+ resolver = SourceResolver(distributions=(native,))
103
+ assert resolver.distribution_names(source) == ("editable-dist",)
104
+ assert resolver.distribution_names(tmp_path / "editable-other/module.py") == ()
105
+
106
+
107
+ def test_interpreter_modules_are_classified_without_package_metadata(monkeypatch):
108
+ def unexpected():
109
+ raise AssertionError("interpreter imports must not query distribution metadata")
110
+
111
+ monkeypatch.setattr(metadata, "distributions", unexpected)
112
+ assert resolve_module("sys").kind == "builtin"
113
+ assert resolve_module("_frozen_importlib").kind == "frozen"
114
+ assert resolve_module("decimal").kind == "stdlib"
115
+ assert resolve_module("not_installed_sourceprobe").kind == "unresolved"
116
+
117
+
118
+ def test_nested_namespace_and_numeric_migration_module_are_located_without_import(tmp_path, monkeypatch):
119
+ package = tmp_path / "nativeprobe" / "compose_migrations" / "target"
120
+ package.mkdir(parents=True)
121
+ path = package / "0001_initial.py"
122
+ path.write_text("raise AssertionError('migration executed')")
123
+ monkeypatch.syspath_prepend(str(tmp_path))
124
+ monkeypatch.setattr(metadata, "distributions", lambda: ())
125
+ assert resolve_module("nativeprobe.compose_migrations.target.0001_initial").path == path
126
+ assert resolve_module("nativeprobe.compose_migrations.target").path == package
127
+ assert "nativeprobe" not in sys.modules
128
+
129
+
130
+ def test_regular_package_ownership_does_not_claim_every_child_distribution(tmp_path, monkeypatch):
131
+ package = tmp_path / "regularprobe"
132
+ package.mkdir()
133
+ (package / "__init__.py").write_text("")
134
+ (package / "extension.py").write_text("")
135
+ one = distribution(tmp_path, "package-dist", ("regularprobe/__init__.py",))
136
+ two = distribution(tmp_path, "extension-dist", ("regularprobe/extension.py",))
137
+ monkeypatch.setattr(metadata, "distributions", lambda: (one, two))
138
+ monkeypatch.syspath_prepend(str(tmp_path))
139
+ assert resolve_module("regularprobe").distributions == ("package-dist",)
140
+ assert resolve_module("regularprobe.extension").distributions == ("extension-dist",)
141
+
142
+
143
+ def test_directory_owners_are_the_owners_of_every_recorded_file_beneath_it(tmp_path):
144
+ site = tmp_path / "site"
145
+ for file in ("nestprobe/sub/deep/mod.py", "nestprobe/other/mod.py"):
146
+ (site / file).parent.mkdir(parents=True, exist_ok=True)
147
+ (site / file).write_text("")
148
+ (site / "nestprobe/sub/empty").mkdir()
149
+ deep = distribution(site, "deep-dist", ("nestprobe/sub/deep/mod.py",))
150
+ other = distribution(site, "other-dist", ("nestprobe/other/mod.py",))
151
+ resolver = SourceResolver(distributions=(deep, other))
152
+ assert resolver.distribution_names(site / "nestprobe/sub/deep/mod.py") == ("deep-dist",)
153
+ assert resolver.distribution_names(site / "nestprobe/sub/deep") == ("deep-dist",)
154
+ assert resolver.distribution_names(site / "nestprobe/sub") == ("deep-dist",)
155
+ assert resolver.distribution_names(site / "nestprobe/other") == ("other-dist",)
156
+ assert resolver.distribution_names(site / "nestprobe") == ("deep-dist", "other-dist")
157
+ assert resolver.distribution_names(site / "nestprobe/sub/empty") == ()
158
+
159
+
160
+ def test_namespace_portion_is_owned_only_by_files_recorded_beneath_it(tmp_path):
161
+ first, second = tmp_path / "first", tmp_path / "second"
162
+ for root, file in ((first, "portionprobe/one/mod.py"), (second, "portionprobe/two/mod.py")):
163
+ (root / file).parent.mkdir(parents=True)
164
+ (root / file).write_text("")
165
+ one = distribution(first, "portion-one", ("portionprobe/one/mod.py",))
166
+ two = distribution(second, "portion-two", ("portionprobe/two/mod.py",))
167
+ resolver = SourceResolver(distributions=(one, two))
168
+ assert resolver.distribution_names(first / "portionprobe") == ("portion-one",)
169
+ assert resolver.distribution_names(second / "portionprobe") == ("portion-two",)
170
+ assert resolver.distribution_names(tmp_path) == ("portion-one", "portion-two")
171
+
172
+
173
+ def test_pep610_project_directory_owns_itself_and_descendants_not_its_parent(tmp_path):
174
+ project = tmp_path / "workspace/editable"
175
+ (project / "src/pkg").mkdir(parents=True)
176
+ native = distribution(tmp_path / "site", "editable-dist", ("_editable.pth",), project=project)
177
+ (tmp_path / "site/_editable.pth").write_text("")
178
+ resolver = SourceResolver(distributions=(native,))
179
+ assert resolver.distribution_names(project) == ("editable-dist",)
180
+ assert resolver.distribution_names(project / "src/pkg") == ("editable-dist",)
181
+ assert resolver.distribution_names(project.parent) == ()
182
+ assert resolver.distribution_names(tmp_path / "site") == ("editable-dist",)
183
+
184
+
185
+ def test_recorded_file_identity_follows_symlinks_and_parent_entries_like_resolve(tmp_path):
186
+ store = tmp_path / "store"
187
+ store.mkdir()
188
+ (store / "mod.py").write_text("")
189
+ package = tmp_path / "real-site/linkprobe"
190
+ package.mkdir(parents=True)
191
+ (package / "mod.py").symlink_to(store / "mod.py") # a file-linking installer
192
+ (package / "plain.py").write_text("")
193
+ site = tmp_path / "site"
194
+ site.symlink_to(package.parent, target_is_directory=True) # a linked installation root
195
+ (tmp_path / "bin").mkdir()
196
+ (tmp_path / "bin/tool").write_text("")
197
+ files = ("linkprobe/mod.py", "linkprobe/plain.py", "../bin/tool")
198
+ resolver = SourceResolver(distributions=(distribution(site, "link-dist", files),))
199
+ for path in (
200
+ store / "mod.py",
201
+ store,
202
+ site / "linkprobe/mod.py",
203
+ site / "linkprobe/plain.py",
204
+ package,
205
+ tmp_path / "bin/tool",
206
+ tmp_path / "bin",
207
+ ):
208
+ assert resolver.distribution_names(path) == ("link-dist",), path
209
+ assert resolver.distribution_names(tmp_path / "real-site/bin") == ()
210
+
211
+
212
+ def lookup_calls(resolver, path):
213
+ """Count the Python and C calls one ownership lookup makes after its index exists."""
214
+ calls = 0
215
+
216
+ def profile(frame, event, arg):
217
+ nonlocal calls
218
+ calls += event in ("call", "c_call")
219
+
220
+ gc.collect()
221
+ sys.setprofile(profile)
222
+ try:
223
+ resolver.distribution_names(path)
224
+ finally:
225
+ sys.setprofile(None)
226
+ return calls
227
+
228
+
229
+ def test_ownership_lookup_work_does_not_grow_with_recorded_files_or_projects(tmp_path):
230
+ work = []
231
+ for count in (50, 500):
232
+ root = tmp_path / str(count)
233
+ files = [f"scaleprobe/part{index}/module{index}.py" for index in range(count)]
234
+ for file in files:
235
+ (root / file).parent.mkdir(parents=True)
236
+ (root / file).write_text("")
237
+ editables = [
238
+ distribution(root / f"editables/{index}", f"editable-{index}", project=root / f"e{index}")
239
+ for index in range(count // 10)
240
+ ]
241
+ resolver = SourceResolver(distributions=(distribution(root, "scale-dist", files), *editables))
242
+ package = root / "scaleprobe"
243
+ assert resolver.distribution_names(package) == ("scale-dist",) # builds the index once
244
+ work.append((lookup_calls(resolver, package), lookup_calls(resolver, package / "part7/module7.py")))
245
+ assert work[0] == work[1]
246
+
247
+
248
+ def test_ownership_index_is_stored_only_when_complete(tmp_path):
249
+ (tmp_path / "first.py").write_text("")
250
+ (tmp_path / "later.py").write_text("")
251
+ corrupt = tmp_path / "corrupt-dist.dist-info"
252
+ corrupt.mkdir()
253
+ (corrupt / "METADATA").write_bytes(b"Metadata-Version: 2.1\nName: \xff\n")
254
+ distributions = iter(
255
+ (
256
+ distribution(tmp_path, "first-dist", ("first.py",)),
257
+ metadata.PathDistribution(corrupt),
258
+ distribution(tmp_path, "later-dist", ("later.py",)),
259
+ )
260
+ )
261
+ resolver = SourceResolver(distributions=distributions)
262
+ for _ in range(2):
263
+ with pytest.raises(UnicodeDecodeError):
264
+ resolver.distribution_names(tmp_path / "later.py")
265
+
266
+
267
+ def test_zip_imported_namespace_portion_is_owned_by_its_recorded_files(tmp_path, monkeypatch):
268
+ archive = tmp_path / "installed.zip"
269
+ with zipfile.ZipFile(archive, "w") as contents:
270
+ contents.writestr("zipnsprobe/mod.py", "raise AssertionError('must not execute')")
271
+ contents.writestr("zipdist-1.dist-info/METADATA", "Name: zipdist\nVersion: 1\n")
272
+ contents.writestr("zipdist-1.dist-info/RECORD", "zipnsprobe/mod.py,,\n")
273
+ monkeypatch.syspath_prepend(str(archive))
274
+ resolver = SourceResolver(distributions=tuple(metadata.distributions(path=[str(archive)])))
275
+ assert resolver.distribution_names(archive / "zipnsprobe") == ("zipdist",)
276
+ assert resolver.distribution_names(archive / "zipnsprobe/mod.py") == ("zipdist",)
277
+ namespace = resolver.resolve("zipnsprobe")
278
+ assert namespace.search_locations == (archive / "zipnsprobe",)
279
+ assert (namespace.kind, namespace.distributions) == ("distribution", ("zipdist",))
280
+ assert "zipnsprobe" not in sys.modules
@@ -348,7 +348,7 @@ wheels = [
348
348
 
349
349
  [[package]]
350
350
  name = "django-compose"
351
- version = "0.1.0.dev9"
351
+ version = "0.1.0.dev11"
352
352
  source = { editable = "." }
353
353
  dependencies = [
354
354
  { name = "django" },
@@ -1,138 +0,0 @@
1
- """One import-free source and exact file ownership seam for every caller."""
2
-
3
- import json
4
- import sys
5
- from importlib import metadata
6
- from pathlib import Path
7
-
8
- import pytest
9
-
10
- from django_compose.snapshot import Entry
11
- from django_compose.sources import SourceResolver, distribution_names, resolve_module
12
-
13
-
14
- def distribution(root: Path, name: str, files=(), project: Path | None = None):
15
- info = root / f"{name}.dist-info"
16
- info.mkdir(parents=True)
17
- (info / "METADATA").write_text(f"Metadata-Version: 2.1\nName: {name}\nVersion: 1\n")
18
- (info / "RECORD").write_text("".join(f"{file},,\n" for file in files))
19
- if project:
20
- (info / "direct_url.json").write_text(
21
- json.dumps({"url": project.as_uri(), "dir_info": {"editable": True}})
22
- )
23
- return metadata.PathDistribution(info)
24
-
25
-
26
- @pytest.mark.parametrize("method", ["locate", "resolve"])
27
- def test_enabled_app_source_precedes_sys_path_without_importing_packages(tmp_path, monkeypatch, method):
28
- wrong = tmp_path / "wrong" / "sourceprobe"
29
- right = tmp_path / "right" / "sourceprobe"
30
- for root, value in ((wrong, "wrong"), (right, "right")):
31
- (root / "integrations").mkdir(parents=True)
32
- (root / "__init__.py").write_text("raise AssertionError('parent executed')")
33
- (root / "integrations" / "__init__.py").write_text("raise AssertionError('parent executed')")
34
- (root / "integrations" / "leaf.py").write_text(value)
35
- monkeypatch.syspath_prepend(str(wrong.parent))
36
-
37
- def distributions():
38
- assert method == "resolve", "location must not query distribution metadata"
39
- return ()
40
-
41
- monkeypatch.setattr(metadata, "distributions", distributions)
42
- entry = Entry("sourceprobe", "probe", "django.apps.AppConfig", str(right), "sourceprobe")
43
- source = getattr(SourceResolver((entry,)), method)("sourceprobe.integrations.leaf")
44
- assert source.path == right / "integrations/leaf.py"
45
- assert source.kind == "app"
46
- assert source.app == "sourceprobe"
47
- assert not any(name.startswith("sourceprobe") for name in sys.modules)
48
-
49
-
50
- def test_namespace_location_retains_all_portions_without_distribution_metadata(tmp_path, monkeypatch):
51
- locations = tuple(tmp_path / name / "namespaceprobe" for name in ("first", "second"))
52
- for location in locations:
53
- location.mkdir(parents=True)
54
- monkeypatch.syspath_prepend(str(location.parent))
55
- leaf = locations[0] / "leaf.py"
56
- leaf.write_text("raise AssertionError('must not execute')")
57
-
58
- def unexpected():
59
- raise AssertionError("location must not query distribution metadata")
60
-
61
- monkeypatch.setattr(metadata, "distributions", unexpected)
62
- resolver = SourceResolver()
63
- namespace = resolver.locate("namespaceprobe")
64
- assert namespace.path == locations[1]
65
- assert namespace.search_locations == tuple(reversed(locations))
66
- assert namespace.distributions == ()
67
- assert namespace.kind == "project"
68
- assert resolver.locate("namespaceprobe.leaf").path == leaf
69
- assert "namespaceprobe" not in sys.modules
70
-
71
-
72
- def test_record_ownership_is_exact_for_shared_namespace(tmp_path, monkeypatch):
73
- package = tmp_path / "sharedprobe"
74
- package.mkdir()
75
- first = package / "first.py"
76
- second = package / "second.py"
77
- first.write_text("")
78
- second.write_text("")
79
- one = distribution(tmp_path, "first-dist", ("sharedprobe/first.py",))
80
- two = distribution(tmp_path, "second-dist", ("sharedprobe/second.py",))
81
- monkeypatch.setattr(metadata, "distributions", lambda: (one, two))
82
- monkeypatch.syspath_prepend(str(tmp_path))
83
- assert distribution_names(first) == ("first-dist",)
84
- assert distribution_names(second) == ("second-dist",)
85
- assert distribution_names(package / "missing.py") == ()
86
- assert resolve_module("sharedprobe.first").distributions == ("first-dist",)
87
- namespace = resolve_module("sharedprobe")
88
- assert namespace.path == package
89
- assert namespace.search_locations == (package,)
90
- assert namespace.distributions == ("first-dist", "second-dist")
91
-
92
-
93
- def test_pep610_project_ownership_uses_directory_boundary(tmp_path):
94
- project = tmp_path / "editable"
95
- project.mkdir()
96
- source = project / "src/pkg/module.py"
97
- source.parent.mkdir(parents=True)
98
- source.write_text("")
99
- native = distribution(tmp_path, "editable-dist", project=project)
100
- resolver = SourceResolver(distributions=(native,))
101
- assert resolver.distribution_names(source) == ("editable-dist",)
102
- assert resolver.distribution_names(tmp_path / "editable-other/module.py") == ()
103
-
104
-
105
- def test_interpreter_modules_are_classified_without_package_metadata(monkeypatch):
106
- def unexpected():
107
- raise AssertionError("interpreter imports must not query distribution metadata")
108
-
109
- monkeypatch.setattr(metadata, "distributions", unexpected)
110
- assert resolve_module("sys").kind == "builtin"
111
- assert resolve_module("_frozen_importlib").kind == "frozen"
112
- assert resolve_module("decimal").kind == "stdlib"
113
- assert resolve_module("not_installed_sourceprobe").kind == "unresolved"
114
-
115
-
116
- def test_nested_namespace_and_numeric_migration_module_are_located_without_import(tmp_path, monkeypatch):
117
- package = tmp_path / "nativeprobe" / "compose_migrations" / "target"
118
- package.mkdir(parents=True)
119
- path = package / "0001_initial.py"
120
- path.write_text("raise AssertionError('migration executed')")
121
- monkeypatch.syspath_prepend(str(tmp_path))
122
- monkeypatch.setattr(metadata, "distributions", lambda: ())
123
- assert resolve_module("nativeprobe.compose_migrations.target.0001_initial").path == path
124
- assert resolve_module("nativeprobe.compose_migrations.target").path == package
125
- assert "nativeprobe" not in sys.modules
126
-
127
-
128
- def test_regular_package_ownership_does_not_claim_every_child_distribution(tmp_path, monkeypatch):
129
- package = tmp_path / "regularprobe"
130
- package.mkdir()
131
- (package / "__init__.py").write_text("")
132
- (package / "extension.py").write_text("")
133
- one = distribution(tmp_path, "package-dist", ("regularprobe/__init__.py",))
134
- two = distribution(tmp_path, "extension-dist", ("regularprobe/extension.py",))
135
- monkeypatch.setattr(metadata, "distributions", lambda: (one, two))
136
- monkeypatch.syspath_prepend(str(tmp_path))
137
- assert resolve_module("regularprobe").distributions == ("package-dist",)
138
- assert resolve_module("regularprobe.extension").distributions == ("extension-dist",)