deproc-python 0.3.0__tar.gz → 0.4.0__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 (41) hide show
  1. {deproc_python-0.3.0 → deproc_python-0.4.0}/PKG-INFO +3 -3
  2. {deproc_python-0.3.0 → deproc_python-0.4.0}/deproc/plugins/python/linker/main.py +14 -1
  3. deproc_python-0.4.0/deproc/plugins/python/utils/packages.py +260 -0
  4. {deproc_python-0.3.0 → deproc_python-0.4.0}/deproc_python.egg-info/PKG-INFO +3 -3
  5. {deproc_python-0.3.0 → deproc_python-0.4.0}/deproc_python.egg-info/SOURCES.txt +1 -0
  6. deproc_python-0.4.0/deproc_python.egg-info/requires.txt +4 -0
  7. {deproc_python-0.3.0 → deproc_python-0.4.0}/pyproject.toml +3 -3
  8. deproc_python-0.4.0/tests/test_shared_registry_precedence.py +421 -0
  9. deproc_python-0.3.0/deproc/plugins/python/utils/packages.py +0 -115
  10. deproc_python-0.3.0/deproc_python.egg-info/requires.txt +0 -4
  11. {deproc_python-0.3.0 → deproc_python-0.4.0}/deproc/plugins/python/__init__.py +0 -0
  12. {deproc_python-0.3.0 → deproc_python-0.4.0}/deproc/plugins/python/linker/__init__.py +0 -0
  13. {deproc_python-0.3.0 → deproc_python-0.4.0}/deproc/plugins/python/linker/models.py +0 -0
  14. {deproc_python-0.3.0 → deproc_python-0.4.0}/deproc/plugins/python/parser/__init__.py +0 -0
  15. {deproc_python-0.3.0 → deproc_python-0.4.0}/deproc/plugins/python/parser/main.py +0 -0
  16. {deproc_python-0.3.0 → deproc_python-0.4.0}/deproc/plugins/python/parser/models.py +0 -0
  17. {deproc_python-0.3.0 → deproc_python-0.4.0}/deproc/plugins/python/parser/utils/extraction.py +0 -0
  18. {deproc_python-0.3.0 → deproc_python-0.4.0}/deproc/plugins/python/parser/utils/misc.py +0 -0
  19. {deproc_python-0.3.0 → deproc_python-0.4.0}/deproc/plugins/python/parser/utils/tree_sitter_python.py +0 -0
  20. {deproc_python-0.3.0 → deproc_python-0.4.0}/deproc/plugins/python/resolver/__init__.py +0 -0
  21. {deproc_python-0.3.0 → deproc_python-0.4.0}/deproc/plugins/python/resolver/main.py +0 -0
  22. {deproc_python-0.3.0 → deproc_python-0.4.0}/deproc/plugins/python/resolver/models.py +0 -0
  23. {deproc_python-0.3.0 → deproc_python-0.4.0}/deproc/plugins/python/symbol_cache/__init__.py +0 -0
  24. {deproc_python-0.3.0 → deproc_python-0.4.0}/deproc/plugins/python/symbol_cache/main.py +0 -0
  25. {deproc_python-0.3.0 → deproc_python-0.4.0}/deproc/plugins/python/symbol_cache/models.py +0 -0
  26. {deproc_python-0.3.0 → deproc_python-0.4.0}/deproc/plugins/python/utils/exports.py +0 -0
  27. {deproc_python-0.3.0 → deproc_python-0.4.0}/deproc/plugins/python/utils/imports.py +0 -0
  28. {deproc_python-0.3.0 → deproc_python-0.4.0}/deproc/plugins/python/utils/mro.py +0 -0
  29. {deproc_python-0.3.0 → deproc_python-0.4.0}/deproc/plugins/python/utils/serialization.py +0 -0
  30. {deproc_python-0.3.0 → deproc_python-0.4.0}/deproc_python.egg-info/dependency_links.txt +0 -0
  31. {deproc_python-0.3.0 → deproc_python-0.4.0}/deproc_python.egg-info/top_level.txt +0 -0
  32. {deproc_python-0.3.0 → deproc_python-0.4.0}/setup.cfg +0 -0
  33. {deproc_python-0.3.0 → deproc_python-0.4.0}/tests/test_exports.py +0 -0
  34. {deproc_python-0.3.0 → deproc_python-0.4.0}/tests/test_imports.py +0 -0
  35. {deproc_python-0.3.0 → deproc_python-0.4.0}/tests/test_linker.py +0 -0
  36. {deproc_python-0.3.0 → deproc_python-0.4.0}/tests/test_mro.py +0 -0
  37. {deproc_python-0.3.0 → deproc_python-0.4.0}/tests/test_package_precedence.py +0 -0
  38. {deproc_python-0.3.0 → deproc_python-0.4.0}/tests/test_parser.py +0 -0
  39. {deproc_python-0.3.0 → deproc_python-0.4.0}/tests/test_python_serialization.py +0 -0
  40. {deproc_python-0.3.0 → deproc_python-0.4.0}/tests/test_resolver.py +0 -0
  41. {deproc_python-0.3.0 → deproc_python-0.4.0}/tests/test_symbol_cache.py +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: deproc-python
3
- Version: 0.3.0
3
+ Version: 0.4.0
4
4
  Summary: Python language plugin for deproc.
5
5
  Author-email: Gurveer Singh Virk <gurveervirk.15517@gmail.com>
6
6
  License: Apache-2.0
@@ -17,6 +17,6 @@ Classifier: Programming Language :: Python :: 3.13
17
17
  Classifier: Topic :: Software Development :: Libraries
18
18
  Requires-Python: >=3.12
19
19
  Requires-Dist: deproc-core>=0.4.0
20
- Requires-Dist: deproc-utils-tree-sitter>=0.1.2
21
- Requires-Dist: tree-sitter>=0.25.2
20
+ Requires-Dist: deproc-utils-tree-sitter>=0.1.3
21
+ Requires-Dist: tree-sitter<0.26,>=0.25.2
22
22
  Requires-Dist: tree-sitter-python>=0.25.0
@@ -6,10 +6,14 @@ from deproc.core.interfaces import Linker
6
6
  from deproc.core.interfaces.parser.models import SemanticContainer
7
7
 
8
8
  from ..parser.models import PythonModule
9
+ from ..utils.packages import apply_regular_package_precedence_to_registry
9
10
  from .models import Node, PythonNamespacePackage, PythonPackage
10
11
 
11
12
 
12
13
  class PythonLinker(Linker[PythonModule, Node | SemanticContainer]):
14
+ def __init__(self, *, apply_package_precedence: bool = True) -> None:
15
+ self.apply_package_precedence = apply_package_precedence
16
+
13
17
  def _check_skip_patterns(self, path: str, skip_patterns: set[str]) -> bool:
14
18
  return any(fnmatch.fnmatch(path, pattern) for pattern in skip_patterns)
15
19
 
@@ -47,7 +51,16 @@ class PythonLinker(Linker[PythonModule, Node | SemanticContainer]):
47
51
  sub_node.parent_id = None
48
52
  top_level.append(sub_node)
49
53
 
50
- return top_level
54
+ if not self.apply_package_precedence:
55
+ return top_level
56
+
57
+ apply_regular_package_precedence_to_registry(context.entity_registry)
58
+ return [
59
+ node
60
+ for node in top_level
61
+ if not isinstance(node, SemanticContainer)
62
+ or node.id in context.entity_registry
63
+ ]
51
64
 
52
65
  def validate_path(self, path: str) -> bool:
53
66
  return (
@@ -0,0 +1,260 @@
1
+ from __future__ import annotations
2
+
3
+ import logging
4
+ from collections.abc import Sequence
5
+ from dataclasses import dataclass
6
+
7
+ from deproc.core.interfaces.parser.models import SymbolID
8
+ from deproc.core.runtime import EntityRegistry
9
+
10
+ from ..linker.models import PythonNamespacePackage, PythonPackage
11
+ from ..parser.models import PythonModule
12
+
13
+ logger = logging.getLogger(__name__)
14
+
15
+
16
+ @dataclass(frozen=True)
17
+ class ShadowedNamespacePortion:
18
+ fqn: str
19
+ path: str
20
+ registry_index: int
21
+ detached_ids: tuple[SymbolID, ...]
22
+
23
+
24
+ @dataclass(frozen=True)
25
+ class RegularPackageConflict:
26
+ fqn: str
27
+ source_root_ids: tuple[str | None, ...]
28
+
29
+
30
+ def _shadows(regular_fqns: set[str], fqn: str) -> bool:
31
+ return any(
32
+ fqn == regular or fqn.startswith(f"{regular}.") for regular in regular_fqns
33
+ )
34
+
35
+
36
+ def _root_label(root_id: str | None) -> str:
37
+ return root_id if root_id is not None else "<no root id>"
38
+
39
+
40
+ def _log_shadowed(fqn: str, detached: int) -> None:
41
+ logger.warning(
42
+ "namespace portion '%s' is shadowed by a regular package of the "
43
+ "same name in another root; its %d module(s) stay indexed "
44
+ "without a parent package",
45
+ fqn,
46
+ detached,
47
+ )
48
+
49
+
50
+ def find_regular_package_conflicts(
51
+ registries: Sequence[EntityRegistry],
52
+ ) -> list[RegularPackageConflict]:
53
+ by_fqn: dict[str, dict[SymbolID, PythonPackage]] = {}
54
+ for registry in registries:
55
+ for entity in registry.values():
56
+ if isinstance(entity, PythonPackage):
57
+ by_fqn.setdefault(entity.fqn, {})[entity.id] = entity
58
+ return [
59
+ RegularPackageConflict(
60
+ fqn=fqn,
61
+ source_root_ids=tuple(
62
+ sorted(
63
+ (package.source_root_id for package in packages.values()),
64
+ key=lambda root_id: root_id or "",
65
+ )
66
+ ),
67
+ )
68
+ for fqn, packages in sorted(by_fqn.items())
69
+ if len(packages) > 1
70
+ ]
71
+
72
+
73
+ def _log_conflicts(conflicts: Sequence[RegularPackageConflict]) -> None:
74
+ for conflict in conflicts:
75
+ logger.warning(
76
+ "regular package '%s' is defined in more than one root (%s); Python "
77
+ "imports only the first one on its path, and all of them stay indexed",
78
+ conflict.fqn,
79
+ ", ".join(_root_label(root_id) for root_id in conflict.source_root_ids),
80
+ )
81
+
82
+
83
+ def apply_regular_package_precedence(
84
+ registries: Sequence[EntityRegistry],
85
+ ) -> list[ShadowedNamespacePortion]:
86
+ """Apply Python's rule that a regular package wins over a namespace portion.
87
+
88
+ ``registries`` are the per-root link results, before they are merged. A
89
+ namespace portion in one registry is shadowed when a different registry
90
+ holds a regular package (one with ``__init__.py``) of the same name, or of
91
+ an ancestor name. Python then never imports that portion, so its container
92
+ is removed and the modules it held stay in the registry without a parent.
93
+ A warning is logged for each regular package name that more than one
94
+ registry defines; all of them are kept.
95
+ """
96
+ _log_conflicts(find_regular_package_conflicts(registries))
97
+ regular_by_registry = [
98
+ {
99
+ entity.fqn
100
+ for entity in registry.values()
101
+ if isinstance(entity, PythonPackage)
102
+ }
103
+ for registry in registries
104
+ ]
105
+ shadowed: list[ShadowedNamespacePortion] = []
106
+ for index, registry in enumerate(registries):
107
+ foreign_regular = {
108
+ fqn
109
+ for other, fqns in enumerate(regular_by_registry)
110
+ if other != index
111
+ for fqn in fqns
112
+ }
113
+ if not foreign_regular:
114
+ continue
115
+ candidates = sorted(
116
+ (
117
+ entity
118
+ for entity in registry.values()
119
+ if isinstance(entity, PythonNamespacePackage)
120
+ and _shadows(foreign_regular, entity.fqn)
121
+ ),
122
+ key=lambda entity: (entity.fqn, entity.path),
123
+ )
124
+ for container in candidates:
125
+ if container.id not in registry:
126
+ continue
127
+ detached = _drop_portion(registry, container)
128
+ portion = ShadowedNamespacePortion(
129
+ fqn=container.fqn,
130
+ path=container.path,
131
+ registry_index=index,
132
+ detached_ids=tuple(detached),
133
+ )
134
+ shadowed.append(portion)
135
+ _log_shadowed(container.fqn, len(detached))
136
+ return shadowed
137
+
138
+
139
+ def apply_regular_package_precedence_to_registry(
140
+ registry: EntityRegistry,
141
+ ) -> list[ShadowedNamespacePortion]:
142
+ regular: dict[str, list[PythonPackage]] = {}
143
+ for entity in registry.values():
144
+ if isinstance(entity, PythonPackage):
145
+ regular.setdefault(entity.fqn, []).append(entity)
146
+ _log_conflicts(find_regular_package_conflicts([registry]))
147
+ if not regular:
148
+ return []
149
+
150
+ containers = sorted(
151
+ (
152
+ entity
153
+ for entity in registry.values()
154
+ if isinstance(entity, PythonNamespacePackage)
155
+ and _shadows(set(regular), entity.fqn)
156
+ ),
157
+ key=lambda entity: (-entity.fqn.count("."), entity.fqn, entity.path),
158
+ )
159
+ shadowed: list[ShadowedNamespacePortion] = []
160
+ for container in containers:
161
+ if container.id not in registry:
162
+ continue
163
+ exact = container.fqn in regular
164
+ regular_roots = {
165
+ package.source_root_id
166
+ for fqn, packages in regular.items()
167
+ if _shadows({fqn}, container.fqn)
168
+ for package in packages
169
+ }
170
+ owner = (
171
+ min(
172
+ regular[container.fqn],
173
+ key=lambda package: (package.source_root_id or "", package.path),
174
+ )
175
+ if exact
176
+ else None
177
+ )
178
+ kept: list[SymbolID] = []
179
+ detached: list[SymbolID] = []
180
+ for child_id in container.submodule_ids:
181
+ child = registry.get(child_id)
182
+ if child is None:
183
+ continue
184
+ if isinstance(child, PythonNamespacePackage):
185
+ if owner is not None:
186
+ child.parent_id = owner.id
187
+ if child.id not in owner.submodule_ids:
188
+ owner.submodule_ids.append(child.id)
189
+ else:
190
+ kept.append(child_id)
191
+ continue
192
+ if (
193
+ owner is None
194
+ and isinstance(child, PythonModule)
195
+ and child.source_root_id in regular_roots
196
+ ):
197
+ kept.append(child_id)
198
+ continue
199
+ child.parent_id = None
200
+ detached.append(child.id)
201
+ removed = owner is not None or (bool(detached) and not kept)
202
+ if removed:
203
+ parent = registry.get(container.parent_id) if container.parent_id else None
204
+ if isinstance(parent, (PythonNamespacePackage, PythonPackage)):
205
+ parent.submodule_ids = [
206
+ entity_id
207
+ for entity_id in parent.submodule_ids
208
+ if entity_id != container.id
209
+ ]
210
+ registry.remove(container.id)
211
+ else:
212
+ container.submodule_ids = kept
213
+ if removed or detached:
214
+ shadowed.append(
215
+ ShadowedNamespacePortion(
216
+ fqn=container.fqn,
217
+ path=container.path,
218
+ registry_index=0,
219
+ detached_ids=tuple(sorted(detached)),
220
+ )
221
+ )
222
+ _log_shadowed(container.fqn, len(detached))
223
+ shadowed.sort(key=lambda portion: (portion.fqn, portion.path))
224
+ return shadowed
225
+
226
+
227
+ def _drop_portion(
228
+ registry: EntityRegistry, container: PythonNamespacePackage
229
+ ) -> list[SymbolID]:
230
+ detached: list[SymbolID] = []
231
+ pending = [container]
232
+ while pending:
233
+ current = pending.pop()
234
+ parent = registry.get(current.parent_id) if current.parent_id else None
235
+ if isinstance(parent, (PythonNamespacePackage, PythonPackage)):
236
+ parent.submodule_ids = [
237
+ entity_id
238
+ for entity_id in parent.submodule_ids
239
+ if entity_id != current.id
240
+ ]
241
+ registry.remove(current.id)
242
+ for child_id in current.submodule_ids:
243
+ child = registry.get(child_id)
244
+ if child is None:
245
+ continue
246
+ if isinstance(child, PythonNamespacePackage):
247
+ pending.append(child)
248
+ else:
249
+ child.parent_id = None
250
+ detached.append(child.id)
251
+ return sorted(detached)
252
+
253
+
254
+ __all__ = [
255
+ "RegularPackageConflict",
256
+ "ShadowedNamespacePortion",
257
+ "apply_regular_package_precedence",
258
+ "apply_regular_package_precedence_to_registry",
259
+ "find_regular_package_conflicts",
260
+ ]
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: deproc-python
3
- Version: 0.3.0
3
+ Version: 0.4.0
4
4
  Summary: Python language plugin for deproc.
5
5
  Author-email: Gurveer Singh Virk <gurveervirk.15517@gmail.com>
6
6
  License: Apache-2.0
@@ -17,6 +17,6 @@ Classifier: Programming Language :: Python :: 3.13
17
17
  Classifier: Topic :: Software Development :: Libraries
18
18
  Requires-Python: >=3.12
19
19
  Requires-Dist: deproc-core>=0.4.0
20
- Requires-Dist: deproc-utils-tree-sitter>=0.1.2
21
- Requires-Dist: tree-sitter>=0.25.2
20
+ Requires-Dist: deproc-utils-tree-sitter>=0.1.3
21
+ Requires-Dist: tree-sitter<0.26,>=0.25.2
22
22
  Requires-Dist: tree-sitter-python>=0.25.0
@@ -33,4 +33,5 @@ tests/test_package_precedence.py
33
33
  tests/test_parser.py
34
34
  tests/test_python_serialization.py
35
35
  tests/test_resolver.py
36
+ tests/test_shared_registry_precedence.py
36
37
  tests/test_symbol_cache.py
@@ -0,0 +1,4 @@
1
+ deproc-core>=0.4.0
2
+ deproc-utils-tree-sitter>=0.1.3
3
+ tree-sitter<0.26,>=0.25.2
4
+ tree-sitter-python>=0.25.0
@@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta"
4
4
 
5
5
  [project]
6
6
  name = "deproc-python"
7
- version = "0.3.0"
7
+ version = "0.4.0"
8
8
  description = "Python language plugin for deproc."
9
9
  authors = [
10
10
  { name = "Gurveer Singh Virk", email = "gurveervirk.15517@gmail.com" }
@@ -13,8 +13,8 @@ license = {text = "Apache-2.0"}
13
13
  requires-python = ">=3.12"
14
14
  dependencies = [
15
15
  "deproc-core>=0.4.0",
16
- "deproc-utils-tree-sitter>=0.1.2",
17
- "tree-sitter>=0.25.2",
16
+ "deproc-utils-tree-sitter>=0.1.3",
17
+ "tree-sitter>=0.25.2,<0.26",
18
18
  "tree-sitter-python>=0.25.0",
19
19
  ]
20
20
  classifiers = [
@@ -0,0 +1,421 @@
1
+ import itertools
2
+ import logging
3
+ from pathlib import Path
4
+
5
+ import pytest
6
+ from deproc.core.context import Context
7
+ from deproc.core.runtime import EntityRegistry
8
+ from deproc.plugins.python.linker.main import PythonLinker
9
+ from deproc.plugins.python.linker.models import PythonNamespacePackage, PythonPackage
10
+ from deproc.plugins.python.parser.main import PythonSourceParser
11
+ from deproc.plugins.python.parser.models import PythonModule
12
+ from deproc.plugins.python.utils.packages import apply_regular_package_precedence
13
+
14
+ PACKAGES_LOGGER = "deproc.plugins.python.utils.packages"
15
+
16
+ Layout = dict[str, dict[str, str]]
17
+
18
+ REGULAR_AND_NAMESPACE: Layout = {
19
+ "core": {"acme/__init__.py": "", "acme/a.py": "class A: pass\n"},
20
+ "plugins": {"acme/billing.py": "class B: pass\n"},
21
+ }
22
+ NESTED_NAMESPACE: Layout = {
23
+ "core": {"acme/__init__.py": "", "acme/sub/x.py": "class X: pass\n"},
24
+ "plugins": {"acme/sub/y.py": "class Y: pass\n"},
25
+ }
26
+ NAMESPACE_ONLY: Layout = {
27
+ "core": {"acme/a.py": "class A: pass\n"},
28
+ "plugins": {"acme/b.py": "class B: pass\n"},
29
+ }
30
+ THREE_ROOTS: Layout = {
31
+ "r1": {"acme/one.py": "class One: pass\n"},
32
+ "r2": {"acme/__init__.py": "", "acme/two.py": "class Two: pass\n"},
33
+ "r3": {"acme/three.py": "class Three: pass\n"},
34
+ }
35
+ TWO_REGULAR: Layout = {
36
+ "first": {"acme/__init__.py": "", "acme/one.py": "class One: pass\n"},
37
+ "second": {"acme/__init__.py": "", "acme/two.py": "class Two: pass\n"},
38
+ }
39
+ LAYOUTS = {
40
+ "regular-and-namespace": REGULAR_AND_NAMESPACE,
41
+ "nested-namespace": NESTED_NAMESPACE,
42
+ "namespace-only": NAMESPACE_ONLY,
43
+ "three-roots": THREE_ROOTS,
44
+ }
45
+
46
+
47
+ def _write(base: Path, files: dict[str, str]) -> None:
48
+ for relative_path, source in files.items():
49
+ path = base / relative_path
50
+ path.parent.mkdir(parents=True, exist_ok=True)
51
+ path.write_text(source)
52
+
53
+
54
+ def _link_into(
55
+ registry: EntityRegistry,
56
+ base: Path,
57
+ name: str,
58
+ files: dict[str, str],
59
+ root_id: str | None,
60
+ linker: PythonLinker | None = None,
61
+ ) -> list:
62
+ _write(base / name, files)
63
+ context = Context(base_path=str(base / name))
64
+ context.source_root_id = root_id
65
+ context.entity_registry = registry
66
+ modules = [
67
+ PythonSourceParser().parse_file(str(base / name / relative_path), context)
68
+ for relative_path in sorted(files)
69
+ ]
70
+ return (linker or PythonLinker()).link_files(modules, context)
71
+
72
+
73
+ def _link_shared(
74
+ base: Path, layout: Layout, order: tuple[str, ...], root_ids: bool = True
75
+ ) -> EntityRegistry:
76
+ registry = EntityRegistry()
77
+ for name in order:
78
+ _link_into(registry, base, name, layout[name], name if root_ids else None)
79
+ return registry
80
+
81
+
82
+ def _link_per_root(
83
+ base: Path, layout: Layout, order: tuple[str, ...]
84
+ ) -> EntityRegistry:
85
+ registries = []
86
+ for name in order:
87
+ registry = EntityRegistry()
88
+ _link_into(registry, base, name, layout[name], name)
89
+ registries.append(registry)
90
+ apply_regular_package_precedence(registries)
91
+ merged = EntityRegistry()
92
+ for registry in registries:
93
+ merged.merge_from(registry)
94
+ return merged
95
+
96
+
97
+ def _fqn_of(registry: EntityRegistry, entity_id: str | None) -> str | None:
98
+ entity = registry.get(entity_id) if entity_id else None
99
+ return getattr(entity, "fqn", None)
100
+
101
+
102
+ def _summary(registry: EntityRegistry) -> list[tuple]:
103
+ rows = []
104
+ for entity in registry.values():
105
+ if isinstance(entity, (PythonPackage, PythonNamespacePackage)):
106
+ children = tuple(
107
+ sorted(
108
+ f"{type(registry.get(child)).__name__}:{_fqn_of(registry, child)}"
109
+ for child in entity.submodule_ids
110
+ )
111
+ )
112
+ parent = registry.get(entity.parent_id) if entity.parent_id else None
113
+ parent_label = (
114
+ f"{type(parent).__name__}:{parent.fqn}" if parent is not None else None
115
+ )
116
+ rows.append((type(entity).__name__, entity.fqn, children, parent_label))
117
+ elif isinstance(entity, PythonModule):
118
+ parent = registry.get(entity.parent_id) if entity.parent_id else None
119
+ parent_label = (
120
+ f"{type(parent).__name__}:{parent.fqn}" if parent is not None else None
121
+ )
122
+ rows.append((type(entity).__name__, entity.fqn, (), parent_label))
123
+ return sorted(rows, key=str)
124
+
125
+
126
+ def _module(registry: EntityRegistry, fqn: str) -> PythonModule:
127
+ (entity_id,) = registry.get_ids_by_fqn(fqn)
128
+ entity = registry.get(entity_id)
129
+ assert isinstance(entity, PythonModule)
130
+ return entity
131
+
132
+
133
+ def _containers(registry: EntityRegistry, fqn: str) -> list:
134
+ return [
135
+ entity
136
+ for entity in registry.values()
137
+ if isinstance(entity, PythonNamespacePackage) and entity.fqn == fqn
138
+ ]
139
+
140
+
141
+ @pytest.mark.parametrize("order", [("core", "plugins"), ("plugins", "core")])
142
+ def test_shared_registry_drops_namespace_portion_shadowed_by_a_regular_package(
143
+ tmp_path, order
144
+ ):
145
+ registry = _link_shared(tmp_path, REGULAR_AND_NAMESPACE, order)
146
+
147
+ assert _containers(registry, "acme") == []
148
+ (package_id,) = registry.get_ids_by_fqn("acme")
149
+ package = registry.get(package_id)
150
+ assert isinstance(package, PythonPackage)
151
+ assert package.submodule_ids == [_module(registry, "acme.a").id]
152
+ assert _module(registry, "acme.a").parent_id == package.id
153
+ assert _module(registry, "acme.billing").parent_id is None
154
+
155
+
156
+ @pytest.mark.parametrize("order", [("core", "plugins"), ("plugins", "core")])
157
+ def test_shared_registry_keeps_modules_of_the_regular_root_in_nested_namespaces(
158
+ tmp_path, order
159
+ ):
160
+ registry = _link_shared(tmp_path, NESTED_NAMESPACE, order)
161
+
162
+ (package_id,) = registry.get_ids_by_fqn("acme")
163
+ package = registry.get(package_id)
164
+ assert isinstance(package, PythonPackage)
165
+ (sub,) = _containers(registry, "acme.sub")
166
+ assert sub.parent_id == package.id
167
+ assert sub.submodule_ids == [_module(registry, "acme.sub.x").id]
168
+ assert _module(registry, "acme.sub.y").parent_id is None
169
+ assert _containers(registry, "acme") == []
170
+
171
+
172
+ @pytest.mark.parametrize("name", sorted(LAYOUTS))
173
+ def test_shared_registry_matches_per_root_linking_in_every_root_order(tmp_path, name):
174
+ layout = LAYOUTS[name]
175
+ for index, order in enumerate(itertools.permutations(layout)):
176
+ shared = _link_shared(tmp_path / f"shared-{index}", layout, order)
177
+ per_root = _link_per_root(tmp_path / f"per-root-{index}", layout, order)
178
+
179
+ assert _summary(shared) == _summary(per_root), order
180
+
181
+
182
+ def test_shared_registry_leaves_namespace_portions_without_a_regular_package(
183
+ tmp_path,
184
+ ):
185
+ registry = _link_shared(tmp_path, NAMESPACE_ONLY, ("core", "plugins"))
186
+
187
+ (namespace,) = _containers(registry, "acme")
188
+ assert sorted(namespace.submodule_ids) == sorted(
189
+ [_module(registry, "acme.a").id, _module(registry, "acme.b").id]
190
+ )
191
+ assert _module(registry, "acme.a").parent_id == namespace.id
192
+ assert _module(registry, "acme.b").parent_id == namespace.id
193
+
194
+
195
+ def test_shared_registry_without_root_ids_still_drops_a_same_named_portion(tmp_path):
196
+ registry = _link_shared(
197
+ tmp_path, REGULAR_AND_NAMESPACE, ("core", "plugins"), root_ids=False
198
+ )
199
+
200
+ assert _containers(registry, "acme") == []
201
+ assert _module(registry, "acme.billing").parent_id is None
202
+
203
+
204
+ def test_shared_registry_without_root_ids_cannot_tell_nested_portions_apart(tmp_path):
205
+ registry = _link_shared(
206
+ tmp_path, NESTED_NAMESPACE, ("core", "plugins"), root_ids=False
207
+ )
208
+
209
+ (sub,) = _containers(registry, "acme.sub")
210
+ assert _module(registry, "acme.sub.y").parent_id == sub.id
211
+
212
+
213
+ def test_link_files_returns_only_containers_that_survive_precedence(tmp_path):
214
+ registry = EntityRegistry()
215
+ _link_into(registry, tmp_path, "core", REGULAR_AND_NAMESPACE["core"], "core")
216
+
217
+ returned = _link_into(
218
+ registry, tmp_path, "plugins", REGULAR_AND_NAMESPACE["plugins"], "plugins"
219
+ )
220
+
221
+ assert all(entity.id in registry for entity in returned)
222
+ assert not any(isinstance(entity, PythonNamespacePackage) for entity in returned)
223
+
224
+
225
+ def test_precedence_function_for_one_registry_reports_and_is_idempotent(tmp_path):
226
+ from deproc.plugins.python.utils.packages import (
227
+ apply_regular_package_precedence_to_registry,
228
+ )
229
+
230
+ merged = EntityRegistry()
231
+ for name, files in REGULAR_AND_NAMESPACE.items():
232
+ registry = EntityRegistry()
233
+ _link_into(registry, tmp_path, name, files, name)
234
+ merged.merge_from(registry)
235
+ assert len(_containers(merged, "acme")) == 1
236
+
237
+ shadowed = apply_regular_package_precedence_to_registry(merged)
238
+
239
+ assert [portion.fqn for portion in shadowed] == ["acme"]
240
+ assert shadowed[0].detached_ids == (_module(merged, "acme.billing").id,)
241
+ assert _containers(merged, "acme") == []
242
+ assert apply_regular_package_precedence_to_registry(merged) == []
243
+
244
+
245
+ def test_two_same_named_regular_packages_are_both_kept_and_a_warning_is_logged(
246
+ tmp_path, caplog
247
+ ):
248
+ with caplog.at_level(logging.WARNING, logger=PACKAGES_LOGGER):
249
+ registry = _link_shared(tmp_path, TWO_REGULAR, ("first", "second"))
250
+
251
+ packages = [
252
+ entity
253
+ for entity in registry.values()
254
+ if isinstance(entity, PythonPackage) and entity.fqn == "acme"
255
+ ]
256
+ assert len(packages) == 2
257
+ assert _module(registry, "acme.one").parent_id in {p.id for p in packages}
258
+ assert _module(registry, "acme.two").parent_id in {p.id for p in packages}
259
+ messages = [r.getMessage() for r in caplog.records if r.name == PACKAGES_LOGGER]
260
+ assert any(
261
+ "regular package 'acme'" in m and "first" in m and "second" in m
262
+ for m in messages
263
+ ), messages
264
+
265
+
266
+ def test_per_root_registries_with_same_named_regular_packages_log_a_warning(
267
+ tmp_path, caplog
268
+ ):
269
+ registries = []
270
+ for name, files in TWO_REGULAR.items():
271
+ registry = EntityRegistry()
272
+ _link_into(registry, tmp_path, name, files, name)
273
+ registries.append(registry)
274
+
275
+ with caplog.at_level(logging.WARNING, logger=PACKAGES_LOGGER):
276
+ shadowed = apply_regular_package_precedence(registries)
277
+
278
+ assert shadowed == []
279
+ messages = [r.getMessage() for r in caplog.records if r.name == PACKAGES_LOGGER]
280
+ assert any("regular package 'acme'" in m for m in messages), messages
281
+
282
+
283
+ def test_find_regular_package_conflicts_lists_each_name_with_its_roots(tmp_path):
284
+ from deproc.plugins.python.utils.packages import (
285
+ RegularPackageConflict,
286
+ find_regular_package_conflicts,
287
+ )
288
+
289
+ registries = []
290
+ for name, files in TWO_REGULAR.items():
291
+ registry = EntityRegistry()
292
+ _link_into(registry, tmp_path, name, files, name)
293
+ registries.append(registry)
294
+
295
+ assert find_regular_package_conflicts(registries) == [
296
+ RegularPackageConflict(fqn="acme", source_root_ids=("first", "second"))
297
+ ]
298
+
299
+
300
+ def test_find_regular_package_conflicts_ignores_a_single_regular_package(tmp_path):
301
+ from deproc.plugins.python.utils.packages import find_regular_package_conflicts
302
+
303
+ registry = _link_shared(tmp_path, REGULAR_AND_NAMESPACE, ("core", "plugins"))
304
+
305
+ assert find_regular_package_conflicts([registry]) == []
306
+
307
+
308
+ def test_no_warning_when_a_regular_package_only_shadows_a_namespace_portion(
309
+ tmp_path, caplog
310
+ ):
311
+ with caplog.at_level(logging.WARNING, logger=PACKAGES_LOGGER):
312
+ _link_shared(tmp_path, REGULAR_AND_NAMESPACE, ("core", "plugins"))
313
+
314
+ assert not any(
315
+ "defined in more than one root" in r.getMessage() for r in caplog.records
316
+ )
317
+
318
+
319
+ @pytest.mark.parametrize("root_id", ["core", None])
320
+ def test_single_root_regular_package_tree_is_left_untouched(tmp_path, caplog, root_id):
321
+ from deproc.plugins.python.utils.packages import (
322
+ apply_regular_package_precedence_to_registry,
323
+ )
324
+
325
+ (tmp_path / "core" / "acme" / ".hidden").mkdir(parents=True)
326
+ registry = EntityRegistry()
327
+
328
+ with caplog.at_level(logging.WARNING, logger=PACKAGES_LOGGER):
329
+ _link_into(
330
+ registry,
331
+ tmp_path,
332
+ "core",
333
+ {
334
+ "acme/__init__.py": "",
335
+ "acme/a.py": "class A: pass\n",
336
+ "acme/sub/x.py": "class X: pass\n",
337
+ },
338
+ root_id,
339
+ )
340
+
341
+ (hidden,) = _containers(registry, "acme..hidden")
342
+ assert hidden.submodule_ids == []
343
+ (sub,) = _containers(registry, "acme.sub")
344
+ assert sub.submodule_ids == [_module(registry, "acme.sub.x").id]
345
+ (package_id,) = registry.get_ids_by_fqn("acme")
346
+ package = registry.get(package_id)
347
+ assert isinstance(package, PythonPackage)
348
+ assert {hidden.parent_id, sub.parent_id} == {package.id}
349
+ assert [r for r in caplog.records if r.name == PACKAGES_LOGGER] == []
350
+ assert apply_regular_package_precedence_to_registry(registry) == []
351
+
352
+
353
+ def test_linker_can_skip_package_precedence(tmp_path, caplog):
354
+ from deproc.plugins.python.utils.packages import (
355
+ apply_regular_package_precedence_to_registry,
356
+ )
357
+
358
+ registry = EntityRegistry()
359
+ linker = PythonLinker(apply_package_precedence=False)
360
+
361
+ with caplog.at_level(logging.WARNING, logger=PACKAGES_LOGGER):
362
+ for name in ("core", "plugins"):
363
+ _link_into(
364
+ registry, tmp_path, name, REGULAR_AND_NAMESPACE[name], name, linker
365
+ )
366
+
367
+ (container,) = _containers(registry, "acme")
368
+ assert _module(registry, "acme.billing").parent_id == container.id
369
+ assert [r for r in caplog.records if r.name == PACKAGES_LOGGER] == []
370
+
371
+ shadowed = apply_regular_package_precedence_to_registry(registry)
372
+
373
+ assert [portion.fqn for portion in shadowed] == ["acme"]
374
+ assert _containers(registry, "acme") == []
375
+
376
+
377
+ def test_linker_skipping_precedence_logs_no_conflict_warning(tmp_path, caplog):
378
+ registry = EntityRegistry()
379
+ linker = PythonLinker(apply_package_precedence=False)
380
+
381
+ with caplog.at_level(logging.WARNING, logger=PACKAGES_LOGGER):
382
+ for name in ("first", "second"):
383
+ _link_into(registry, tmp_path, name, TWO_REGULAR[name], name, linker)
384
+
385
+ assert [r for r in caplog.records if r.name == PACKAGES_LOGGER] == []
386
+
387
+
388
+ def test_linker_applies_package_precedence_by_default():
389
+ assert PythonLinker().apply_package_precedence is True
390
+ assert (
391
+ PythonLinker(apply_package_precedence=False).apply_package_precedence is False
392
+ )
393
+
394
+
395
+ @pytest.mark.parametrize("order", [("first", "second"), ("second", "first")])
396
+ def test_two_same_named_regular_packages_are_kept_in_either_root_order(
397
+ tmp_path, caplog, order
398
+ ):
399
+ from deproc.plugins.python.utils.packages import (
400
+ RegularPackageConflict,
401
+ find_regular_package_conflicts,
402
+ )
403
+
404
+ with caplog.at_level(logging.WARNING, logger=PACKAGES_LOGGER):
405
+ registry = _link_shared(tmp_path, TWO_REGULAR, order)
406
+
407
+ packages = [
408
+ entity
409
+ for entity in registry.values()
410
+ if isinstance(entity, PythonPackage) and entity.fqn == "acme"
411
+ ]
412
+ assert len(packages) == 2
413
+ one = _module(registry, "acme.one")
414
+ two = _module(registry, "acme.two")
415
+ assert {one.parent_id, two.parent_id} == {package.id for package in packages}
416
+ assert find_regular_package_conflicts([registry]) == [
417
+ RegularPackageConflict(fqn="acme", source_root_ids=("first", "second"))
418
+ ]
419
+ assert any(
420
+ "defined in more than one root" in r.getMessage() for r in caplog.records
421
+ )
@@ -1,115 +0,0 @@
1
- from __future__ import annotations
2
-
3
- import logging
4
- from collections.abc import Sequence
5
- from dataclasses import dataclass
6
-
7
- from deproc.core.interfaces.parser.models import SymbolID
8
- from deproc.core.runtime import EntityRegistry
9
-
10
- from ..linker.models import PythonNamespacePackage, PythonPackage
11
-
12
- logger = logging.getLogger(__name__)
13
-
14
-
15
- @dataclass(frozen=True)
16
- class ShadowedNamespacePortion:
17
- fqn: str
18
- path: str
19
- registry_index: int
20
- detached_ids: tuple[SymbolID, ...]
21
-
22
-
23
- def _shadows(regular_fqns: set[str], fqn: str) -> bool:
24
- return any(
25
- fqn == regular or fqn.startswith(f"{regular}.") for regular in regular_fqns
26
- )
27
-
28
-
29
- def apply_regular_package_precedence(
30
- registries: Sequence[EntityRegistry],
31
- ) -> list[ShadowedNamespacePortion]:
32
- """Apply Python's rule that a regular package wins over a namespace portion.
33
-
34
- ``registries`` are the per-root link results, before they are merged. A
35
- namespace portion in one registry is shadowed when a different registry
36
- holds a regular package (one with ``__init__.py``) of the same name, or of
37
- an ancestor name. Python then never imports that portion, so its container
38
- is removed and the modules it held stay in the registry without a parent.
39
- """
40
- regular_by_registry = [
41
- {
42
- entity.fqn
43
- for entity in registry.values()
44
- if isinstance(entity, PythonPackage)
45
- }
46
- for registry in registries
47
- ]
48
- shadowed: list[ShadowedNamespacePortion] = []
49
- for index, registry in enumerate(registries):
50
- foreign_regular = {
51
- fqn
52
- for other, fqns in enumerate(regular_by_registry)
53
- if other != index
54
- for fqn in fqns
55
- }
56
- if not foreign_regular:
57
- continue
58
- candidates = sorted(
59
- (
60
- entity
61
- for entity in registry.values()
62
- if isinstance(entity, PythonNamespacePackage)
63
- and _shadows(foreign_regular, entity.fqn)
64
- ),
65
- key=lambda entity: (entity.fqn, entity.path),
66
- )
67
- for container in candidates:
68
- if container.id not in registry:
69
- continue
70
- detached = _drop_portion(registry, container)
71
- portion = ShadowedNamespacePortion(
72
- fqn=container.fqn,
73
- path=container.path,
74
- registry_index=index,
75
- detached_ids=tuple(detached),
76
- )
77
- shadowed.append(portion)
78
- logger.warning(
79
- "namespace portion '%s' is shadowed by a regular package of the "
80
- "same name in another root; its %d module(s) stay indexed "
81
- "without a parent package",
82
- container.fqn,
83
- len(detached),
84
- )
85
- return shadowed
86
-
87
-
88
- def _drop_portion(
89
- registry: EntityRegistry, container: PythonNamespacePackage
90
- ) -> list[SymbolID]:
91
- detached: list[SymbolID] = []
92
- pending = [container]
93
- while pending:
94
- current = pending.pop()
95
- parent = registry.get(current.parent_id) if current.parent_id else None
96
- if isinstance(parent, (PythonNamespacePackage, PythonPackage)):
97
- parent.submodule_ids = [
98
- entity_id
99
- for entity_id in parent.submodule_ids
100
- if entity_id != current.id
101
- ]
102
- registry.remove(current.id)
103
- for child_id in current.submodule_ids:
104
- child = registry.get(child_id)
105
- if child is None:
106
- continue
107
- if isinstance(child, PythonNamespacePackage):
108
- pending.append(child)
109
- else:
110
- child.parent_id = None
111
- detached.append(child.id)
112
- return sorted(detached)
113
-
114
-
115
- __all__ = ["ShadowedNamespacePortion", "apply_regular_package_precedence"]
@@ -1,4 +0,0 @@
1
- deproc-core>=0.4.0
2
- deproc-utils-tree-sitter>=0.1.2
3
- tree-sitter>=0.25.2
4
- tree-sitter-python>=0.25.0
File without changes