buttress 0.2.0__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.
- buttress/__init__.py +63 -0
- buttress/__main__.py +7 -0
- buttress/analysis/__init__.py +44 -0
- buttress/analysis/discovery.py +176 -0
- buttress/analysis/external.py +92 -0
- buttress/analysis/extractor.py +329 -0
- buttress/analysis/interfaces.py +49 -0
- buttress/analysis/manifest_parser.py +337 -0
- buttress/analysis/resolver.py +143 -0
- buttress/analysis/scanner.py +179 -0
- buttress/analysis/stdlib.py +60 -0
- buttress/api/__init__.py +129 -0
- buttress/api/analysis.py +51 -0
- buttress/api/baselines.py +29 -0
- buttress/api/contracts.py +85 -0
- buttress/api/project.py +881 -0
- buttress/api/synchronization.py +40 -0
- buttress/application/__init__.py +24 -0
- buttress/application/analysis_service.py +209 -0
- buttress/application/baseline_service.py +62 -0
- buttress/application/context.py +45 -0
- buttress/application/contract_service.py +236 -0
- buttress/application/report_service.py +164 -0
- buttress/application/sync_service.py +100 -0
- buttress/application/test_impact_service.py +219 -0
- buttress/cli/__init__.py +6 -0
- buttress/cli/commands/__init__.py +2 -0
- buttress/cli/commands/architecture_cmd.py +231 -0
- buttress/cli/commands/baseline_cmd.py +157 -0
- buttress/cli/commands/cache_cmd.py +120 -0
- buttress/cli/commands/check_cmd.py +232 -0
- buttress/cli/commands/check_external_cmd.py +197 -0
- buttress/cli/commands/config_cmd.py +153 -0
- buttress/cli/commands/configure_cmd.py +297 -0
- buttress/cli/commands/contracts_cmd.py +205 -0
- buttress/cli/commands/deadcode_cmd.py +166 -0
- buttress/cli/commands/doctor_cmd.py +105 -0
- buttress/cli/commands/explain_cmd.py +116 -0
- buttress/cli/commands/fix_cmd.py +320 -0
- buttress/cli/commands/graph_cmd.py +64 -0
- buttress/cli/commands/init_cmd.py +143 -0
- buttress/cli/commands/install_cmd.py +42 -0
- buttress/cli/commands/map_cmd.py +67 -0
- buttress/cli/commands/mod_cmd.py +266 -0
- buttress/cli/commands/report_cmd.py +148 -0
- buttress/cli/commands/scan_cmd.py +183 -0
- buttress/cli/commands/show_cmd.py +65 -0
- buttress/cli/commands/sync_cmd.py +200 -0
- buttress/cli/commands/test_cmd.py +130 -0
- buttress/cli/entrypoint.py +316 -0
- buttress/cli/formatters/__init__.py +2 -0
- buttress/cli/formatters/console.py +64 -0
- buttress/configuration/__init__.py +67 -0
- buttress/configuration/discovery.py +158 -0
- buttress/configuration/domain.py +153 -0
- buttress/configuration/loader.py +225 -0
- buttress/configuration/migration.py +159 -0
- buttress/configuration/models.py +361 -0
- buttress/configuration/precedence.py +93 -0
- buttress/configuration/schema.py +25 -0
- buttress/configuration/validator.py +263 -0
- buttress/configuration/writer.py +236 -0
- buttress/contracts/__init__.py +41 -0
- buttress/contracts/acyclic_siblings.py +187 -0
- buttress/contracts/analyzer.py +225 -0
- buttress/contracts/base.py +236 -0
- buttress/contracts/declarative.py +701 -0
- buttress/contracts/forbidden.py +155 -0
- buttress/contracts/independence.py +126 -0
- buttress/contracts/layers.py +505 -0
- buttress/contracts/module_policy.py +313 -0
- buttress/contracts/protected.py +126 -0
- buttress/contracts/public_interface.py +128 -0
- buttress/contracts/registry.py +452 -0
- buttress/domain/__init__.py +137 -0
- buttress/domain/baseline.py +146 -0
- buttress/domain/contract.py +122 -0
- buttress/domain/exceptions.py +637 -0
- buttress/domain/finding.py +118 -0
- buttress/domain/graph.py +607 -0
- buttress/domain/import_statement.py +67 -0
- buttress/domain/module.py +230 -0
- buttress/domain/policy.py +131 -0
- buttress/domain/suppression.py +128 -0
- buttress/infrastructure/cache/__init__.py +12 -0
- buttress/infrastructure/cache/manager.py +146 -0
- buttress/infrastructure/cache/models.py +99 -0
- buttress/infrastructure/cache/sqlite_store.py +340 -0
- buttress/infrastructure/exporters/__init__.py +18 -0
- buttress/infrastructure/exporters/dot.py +49 -0
- buttress/infrastructure/exporters/json_export.py +39 -0
- buttress/infrastructure/exporters/mermaid.py +49 -0
- buttress/infrastructure/exporters/sarif.py +115 -0
- buttress/infrastructure/grimp_adapter.py +80 -0
- buttress/infrastructure/vcs/__init__.py +6 -0
- buttress/infrastructure/vcs/git_adapter.py +115 -0
- buttress/integrations/__init__.py +20 -0
- buttress/integrations/github_actions.py +74 -0
- buttress/integrations/pre_commit.py +91 -0
- buttress/integrations/pytest_plugin.py +74 -0
- buttress/plugins/__init__.py +13 -0
- buttress/plugins/loader.py +339 -0
- buttress/plugins/manager.py +136 -0
- buttress/py.typed +1 -0
- buttress/remediation/__init__.py +32 -0
- buttress/remediation/conflicts.py +113 -0
- buttress/remediation/diff.py +63 -0
- buttress/remediation/models.py +307 -0
- buttress/remediation/rules/__init__.py +7 -0
- buttress/remediation/rules/ast_utils.py +214 -0
- buttress/remediation/rules/base.py +58 -0
- buttress/remediation/rules/builtin/__init__.py +23 -0
- buttress/remediation/rules/builtin/lazy_import_wrapper.py +378 -0
- buttress/remediation/rules/builtin/module_policy_deprecation.py +129 -0
- buttress/remediation/rules/builtin/remove_stale_ignore_comment.py +100 -0
- buttress/remediation/rules/builtin/remove_unused_forbidden_import.py +159 -0
- buttress/remediation/rules/builtin/replace_with_public_facade.py +173 -0
- buttress/remediation/rules/builtin/type_checking_guard.py +192 -0
- buttress/remediation/rules/custom.py +210 -0
- buttress/remediation/rules/registry.py +100 -0
- buttress/remediation/service.py +259 -0
- buttress/remediation/transaction.py +348 -0
- buttress/remediation/transformer.py +983 -0
- buttress/remediation/verifier.py +118 -0
- buttress/server/__init__.py +11 -0
- buttress/server/api/__init__.py +6 -0
- buttress/server/api/handlers.py +879 -0
- buttress/server/api/metadata.py +395 -0
- buttress/server/router.py +186 -0
- buttress/server/security.py +91 -0
- buttress/server/server.py +304 -0
- buttress/server/static/css/components.css +862 -0
- buttress/server/static/css/diff.css +119 -0
- buttress/server/static/css/graph.css +256 -0
- buttress/server/static/css/layout.css +570 -0
- buttress/server/static/css/reset.css +76 -0
- buttress/server/static/css/tokens.css +67 -0
- buttress/server/static/img/logo.png +0 -0
- buttress/server/static/index.html +191 -0
- buttress/server/static/js/app.js +345 -0
- buttress/server/static/js/components/diff_viewer.js +100 -0
- buttress/server/static/js/core/api.js +119 -0
- buttress/server/static/js/core/dom.js +152 -0
- buttress/server/static/js/core/state.js +103 -0
- buttress/server/static/js/graph/canvas.js +189 -0
- buttress/server/static/js/graph/layout.js +224 -0
- buttress/server/static/js/graph/renderer.js +76 -0
- buttress/server/static/js/graph/table_fallback.js +65 -0
- buttress/server/static/js/icons.js +29 -0
- buttress/server/static/js/views/about_panel.js +73 -0
- buttress/server/static/js/views/architecture.js +240 -0
- buttress/server/static/js/views/baselines.js +226 -0
- buttress/server/static/js/views/contracts.js +643 -0
- buttress/server/static/js/views/dependencies.js +324 -0
- buttress/server/static/js/views/help_panel.js +397 -0
- buttress/server/static/js/views/impact.js +149 -0
- buttress/server/static/js/views/inspector.js +213 -0
- buttress/server/static/js/views/overview.js +344 -0
- buttress/server/static/js/views/remediation.js +398 -0
- buttress/server/static/js/views/reports.js +113 -0
- buttress/server/static/js/views/settings.js +511 -0
- buttress/server/static/js/views/violations.js +278 -0
- buttress/utils/__init__.py +2 -0
- buttress/utils/atomic_write.py +262 -0
- buttress/utils/path_utils.py +120 -0
- buttress/version.py +5 -0
- buttress-0.2.0.dist-info/METADATA +268 -0
- buttress-0.2.0.dist-info/RECORD +172 -0
- buttress-0.2.0.dist-info/WHEEL +5 -0
- buttress-0.2.0.dist-info/entry_points.txt +5 -0
- buttress-0.2.0.dist-info/licenses/LICENSE +21 -0
- buttress-0.2.0.dist-info/top_level.txt +1 -0
buttress/__init__.py
ADDED
|
@@ -0,0 +1,63 @@
|
|
|
1
|
+
"""Buttress — Enterprise-grade Python architecture analysis and enforcement."""
|
|
2
|
+
|
|
3
|
+
from buttress.contracts.base import ContractBase
|
|
4
|
+
from buttress.contracts.registry import ContractMetadata, ContractRegistry
|
|
5
|
+
from buttress.domain import (
|
|
6
|
+
BaseContract,
|
|
7
|
+
Baseline,
|
|
8
|
+
ContractResult,
|
|
9
|
+
DependencyEdge,
|
|
10
|
+
DependencyGraph,
|
|
11
|
+
Finding,
|
|
12
|
+
ImportKind,
|
|
13
|
+
ImportSite,
|
|
14
|
+
ImportStatement,
|
|
15
|
+
Module,
|
|
16
|
+
ModuleId,
|
|
17
|
+
ModulePolicy,
|
|
18
|
+
Project,
|
|
19
|
+
Severity,
|
|
20
|
+
SourceFile,
|
|
21
|
+
SourceLocation,
|
|
22
|
+
SourceRoot,
|
|
23
|
+
Suppression,
|
|
24
|
+
SuppressionKind,
|
|
25
|
+
SuppressionManager,
|
|
26
|
+
WorkspaceId,
|
|
27
|
+
)
|
|
28
|
+
from buttress.plugins.loader import PluginLoader
|
|
29
|
+
from buttress.plugins.manager import PluginManager
|
|
30
|
+
from buttress.version import VERSION, __version__
|
|
31
|
+
|
|
32
|
+
__all__ = [
|
|
33
|
+
"__version__",
|
|
34
|
+
"VERSION",
|
|
35
|
+
# Domain Models
|
|
36
|
+
"Project",
|
|
37
|
+
"WorkspaceId",
|
|
38
|
+
"SourceRoot",
|
|
39
|
+
"ModuleId",
|
|
40
|
+
"Module",
|
|
41
|
+
"SourceFile",
|
|
42
|
+
"SourceLocation",
|
|
43
|
+
"ImportStatement",
|
|
44
|
+
"ImportKind",
|
|
45
|
+
"ImportSite",
|
|
46
|
+
"DependencyEdge",
|
|
47
|
+
"DependencyGraph",
|
|
48
|
+
"Finding",
|
|
49
|
+
"Severity",
|
|
50
|
+
"BaseContract",
|
|
51
|
+
"ContractBase",
|
|
52
|
+
"ContractMetadata",
|
|
53
|
+
"ContractRegistry",
|
|
54
|
+
"PluginLoader",
|
|
55
|
+
"PluginManager",
|
|
56
|
+
"ContractResult",
|
|
57
|
+
"ModulePolicy",
|
|
58
|
+
"Suppression",
|
|
59
|
+
"SuppressionKind",
|
|
60
|
+
"SuppressionManager",
|
|
61
|
+
"Baseline",
|
|
62
|
+
]
|
|
63
|
+
|
buttress/__main__.py
ADDED
|
@@ -0,0 +1,44 @@
|
|
|
1
|
+
"""Analysis Layer for Buttress.
|
|
2
|
+
|
|
3
|
+
Provides source discovery, AST extraction, import classification, resolution,
|
|
4
|
+
public interface analysis, and project scanning.
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
from buttress.analysis.discovery import (
|
|
8
|
+
SourceInventoryScanner,
|
|
9
|
+
compute_file_sha256,
|
|
10
|
+
)
|
|
11
|
+
from buttress.analysis.external import (
|
|
12
|
+
ExternalDependencyResolver,
|
|
13
|
+
get_distribution_map,
|
|
14
|
+
)
|
|
15
|
+
from buttress.analysis.extractor import (
|
|
16
|
+
extract_inline_suppressions,
|
|
17
|
+
extract_source_imports,
|
|
18
|
+
)
|
|
19
|
+
from buttress.analysis.interfaces import extract_public_interface
|
|
20
|
+
from buttress.analysis.resolver import ImportResolver
|
|
21
|
+
from buttress.analysis.scanner import (
|
|
22
|
+
ProjectScanner,
|
|
23
|
+
ScanResult,
|
|
24
|
+
)
|
|
25
|
+
from buttress.analysis.stdlib import is_stdlib_module
|
|
26
|
+
|
|
27
|
+
__all__ = [
|
|
28
|
+
# Discovery & Hashes
|
|
29
|
+
"SourceInventoryScanner",
|
|
30
|
+
"compute_file_sha256",
|
|
31
|
+
# Classifiers
|
|
32
|
+
"is_stdlib_module",
|
|
33
|
+
"ExternalDependencyResolver",
|
|
34
|
+
"get_distribution_map",
|
|
35
|
+
# Extraction
|
|
36
|
+
"extract_source_imports",
|
|
37
|
+
"extract_inline_suppressions",
|
|
38
|
+
"extract_public_interface",
|
|
39
|
+
# Resolution & Scanning
|
|
40
|
+
"ImportResolver",
|
|
41
|
+
"ProjectScanner",
|
|
42
|
+
"ScanResult",
|
|
43
|
+
]
|
|
44
|
+
|
|
@@ -0,0 +1,176 @@
|
|
|
1
|
+
"""Python source file and module inventory discovery.
|
|
2
|
+
|
|
3
|
+
Scans source roots, maps file paths to ModuleIds, detects PEP 420 namespace packages,
|
|
4
|
+
and produces an immutable Project snapshot.
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
from __future__ import annotations
|
|
8
|
+
|
|
9
|
+
import hashlib
|
|
10
|
+
import os
|
|
11
|
+
from pathlib import Path
|
|
12
|
+
from typing import Optional, Sequence
|
|
13
|
+
|
|
14
|
+
import pathspec
|
|
15
|
+
|
|
16
|
+
from buttress.domain.module import (
|
|
17
|
+
Module,
|
|
18
|
+
ModuleId,
|
|
19
|
+
Project,
|
|
20
|
+
SourceFile,
|
|
21
|
+
)
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
def compute_file_sha256(path: Path) -> str:
|
|
25
|
+
"""Calculate SHA-256 hash of file content."""
|
|
26
|
+
hasher = hashlib.sha256()
|
|
27
|
+
try:
|
|
28
|
+
with path.open("rb") as f:
|
|
29
|
+
while chunk := f.read(65536):
|
|
30
|
+
hasher.update(chunk)
|
|
31
|
+
return hasher.hexdigest()
|
|
32
|
+
except OSError:
|
|
33
|
+
return ""
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
class SourceInventoryScanner:
|
|
37
|
+
"""Scans filesystem roots and indexes all Python modules and files."""
|
|
38
|
+
|
|
39
|
+
def __init__(
|
|
40
|
+
self,
|
|
41
|
+
project_root: Path,
|
|
42
|
+
source_roots: Sequence[Path],
|
|
43
|
+
exclude_patterns: Optional[Sequence[str]] = None,
|
|
44
|
+
) -> None:
|
|
45
|
+
self.project_root = project_root.resolve()
|
|
46
|
+
self.source_roots = [r.resolve() for r in source_roots]
|
|
47
|
+
patterns = list(exclude_patterns or [])
|
|
48
|
+
self._has_negation = any(p.strip().startswith("!") for p in patterns)
|
|
49
|
+
self.spec = pathspec.PathSpec.from_lines("gitignore", patterns)
|
|
50
|
+
|
|
51
|
+
def scan_project(self) -> Project:
|
|
52
|
+
"""Perform full directory walk and return Project domain entity."""
|
|
53
|
+
modules_by_name: dict[str, list[SourceFile]] = {}
|
|
54
|
+
|
|
55
|
+
for s_root in self.source_roots:
|
|
56
|
+
if not s_root.is_dir():
|
|
57
|
+
continue
|
|
58
|
+
self._scan_source_root(s_root, modules_by_name)
|
|
59
|
+
|
|
60
|
+
project_modules: dict[str, Module] = {}
|
|
61
|
+
for mod_name, files in modules_by_name.items():
|
|
62
|
+
is_package = any(f.is_package_init for f in files)
|
|
63
|
+
mod_id = ModuleId(mod_name)
|
|
64
|
+
project_modules[mod_name] = Module(
|
|
65
|
+
id=mod_id,
|
|
66
|
+
source_files=tuple(files),
|
|
67
|
+
is_package=is_package,
|
|
68
|
+
is_external=False,
|
|
69
|
+
is_stdlib=False,
|
|
70
|
+
)
|
|
71
|
+
|
|
72
|
+
# PEP 420 & Multi-Root Namespaces: Synthesize namespace packages for ancestor modules
|
|
73
|
+
for mod_name in list(project_modules.keys()):
|
|
74
|
+
parts = mod_name.split(".")
|
|
75
|
+
for i in range(1, len(parts)):
|
|
76
|
+
ancestor = ".".join(parts[:i])
|
|
77
|
+
if ancestor not in project_modules:
|
|
78
|
+
project_modules[ancestor] = Module(
|
|
79
|
+
id=ModuleId(ancestor),
|
|
80
|
+
source_files=(),
|
|
81
|
+
is_package=True,
|
|
82
|
+
is_external=False,
|
|
83
|
+
is_stdlib=False,
|
|
84
|
+
)
|
|
85
|
+
|
|
86
|
+
return Project(
|
|
87
|
+
root_path=self.project_root,
|
|
88
|
+
source_roots=tuple(self.source_roots),
|
|
89
|
+
modules=project_modules,
|
|
90
|
+
)
|
|
91
|
+
|
|
92
|
+
def _scan_source_root(
|
|
93
|
+
self,
|
|
94
|
+
source_root: Path,
|
|
95
|
+
modules_by_name: dict[str, list[SourceFile]],
|
|
96
|
+
) -> None:
|
|
97
|
+
"""Walk a single source root directory collecting .py and .pyi files with directory pruning."""
|
|
98
|
+
for dirpath, dirnames, filenames in os.walk(source_root, topdown=True, followlinks=False):
|
|
99
|
+
current_dir = Path(dirpath)
|
|
100
|
+
if not self._has_negation:
|
|
101
|
+
kept_dirs: list[str] = []
|
|
102
|
+
for d in dirnames:
|
|
103
|
+
if d == "__pycache__":
|
|
104
|
+
continue
|
|
105
|
+
d_path = current_dir / d
|
|
106
|
+
rel_src_dir = d_path.relative_to(source_root).as_posix()
|
|
107
|
+
try:
|
|
108
|
+
rel_proj_dir = d_path.relative_to(self.project_root).as_posix()
|
|
109
|
+
except ValueError:
|
|
110
|
+
# Source root may point outside project_root in multi-repo setups
|
|
111
|
+
rel_proj_dir = rel_src_dir
|
|
112
|
+
if (
|
|
113
|
+
self.spec.match_file(f"{rel_proj_dir}/")
|
|
114
|
+
or self.spec.match_file(f"{rel_proj_dir}/__dir__")
|
|
115
|
+
or self.spec.match_file(f"{rel_src_dir}/")
|
|
116
|
+
or self.spec.match_file(f"{rel_src_dir}/__dir__")
|
|
117
|
+
):
|
|
118
|
+
continue
|
|
119
|
+
kept_dirs.append(d)
|
|
120
|
+
dirnames[:] = kept_dirs
|
|
121
|
+
|
|
122
|
+
for fname in filenames:
|
|
123
|
+
path = current_dir / fname
|
|
124
|
+
if path.suffix not in (".py", ".pyi"):
|
|
125
|
+
continue
|
|
126
|
+
|
|
127
|
+
# Check relative path against exclusion spec
|
|
128
|
+
rel_source_posix = path.relative_to(source_root).as_posix()
|
|
129
|
+
try:
|
|
130
|
+
rel_project = path.relative_to(self.project_root).as_posix()
|
|
131
|
+
except ValueError:
|
|
132
|
+
rel_project = rel_source_posix
|
|
133
|
+
if self.spec.match_file(rel_project) or self.spec.match_file(rel_source_posix):
|
|
134
|
+
continue
|
|
135
|
+
|
|
136
|
+
rel_source_path = path.relative_to(source_root)
|
|
137
|
+
is_stub = path.suffix == ".pyi"
|
|
138
|
+
is_init = path.stem == "__init__"
|
|
139
|
+
|
|
140
|
+
# Derive module name from relative path parts
|
|
141
|
+
# e.g., ('myapp', 'domain', 'model.py') -> ('myapp', 'domain', 'model')
|
|
142
|
+
parts = list(rel_source_path.parts)
|
|
143
|
+
if is_init:
|
|
144
|
+
parts = parts[:-1]
|
|
145
|
+
else:
|
|
146
|
+
parts[-1] = path.stem
|
|
147
|
+
|
|
148
|
+
if not parts:
|
|
149
|
+
continue
|
|
150
|
+
|
|
151
|
+
mod_name = ".".join(parts)
|
|
152
|
+
mod_id = ModuleId(mod_name)
|
|
153
|
+
|
|
154
|
+
try:
|
|
155
|
+
stat = path.stat()
|
|
156
|
+
size = stat.st_size
|
|
157
|
+
mtime = stat.st_mtime
|
|
158
|
+
except OSError:
|
|
159
|
+
size = 0
|
|
160
|
+
mtime = 0.0
|
|
161
|
+
|
|
162
|
+
content_hash = compute_file_sha256(path)
|
|
163
|
+
|
|
164
|
+
source_file = SourceFile(
|
|
165
|
+
path=path,
|
|
166
|
+
relative_path=Path(rel_project),
|
|
167
|
+
module_id=mod_id,
|
|
168
|
+
source_root=source_root,
|
|
169
|
+
is_package_init=is_init,
|
|
170
|
+
is_stub=is_stub,
|
|
171
|
+
size_bytes=size,
|
|
172
|
+
mtime=mtime,
|
|
173
|
+
content_hash=content_hash,
|
|
174
|
+
)
|
|
175
|
+
|
|
176
|
+
modules_by_name.setdefault(mod_name, []).append(source_file)
|
|
@@ -0,0 +1,92 @@
|
|
|
1
|
+
"""External third-party dependency detection and distribution mapping.
|
|
2
|
+
|
|
3
|
+
Queries importlib.metadata to associate imported modules with installed distributions.
|
|
4
|
+
"""
|
|
5
|
+
|
|
6
|
+
from __future__ import annotations
|
|
7
|
+
|
|
8
|
+
import functools
|
|
9
|
+
import sys
|
|
10
|
+
from importlib import metadata
|
|
11
|
+
from typing import Optional
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
@functools.lru_cache(maxsize=1)
|
|
15
|
+
def get_distribution_map() -> dict[str, list[str]]:
|
|
16
|
+
"""Return mapping of top-level import package name to distribution name(s).
|
|
17
|
+
|
|
18
|
+
Example: {'yaml': ['PyYAML'], 'PIL': ['pillow'], 'click': ['click']}
|
|
19
|
+
"""
|
|
20
|
+
mapping: dict[str, list[str]] = {}
|
|
21
|
+
if hasattr(metadata, "packages_distributions"):
|
|
22
|
+
try:
|
|
23
|
+
mapping = dict(metadata.packages_distributions())
|
|
24
|
+
except Exception:
|
|
25
|
+
mapping = {}
|
|
26
|
+
|
|
27
|
+
# In Python 3.11+, stdlib packages_distributions() inspects RECORD files and is complete.
|
|
28
|
+
if sys.version_info >= (3, 11) and mapping:
|
|
29
|
+
return mapping
|
|
30
|
+
|
|
31
|
+
# Python 3.10 stdlib packages_distributions() only checked top_level.txt,
|
|
32
|
+
# which is omitted by modern wheel builders (bpo-46382). Augment with
|
|
33
|
+
# package discovery from distribution files and names.
|
|
34
|
+
try:
|
|
35
|
+
for dist in metadata.distributions():
|
|
36
|
+
meta = dist.metadata
|
|
37
|
+
dist_name = meta["Name"] if meta and "Name" in meta else getattr(dist, "name", "")
|
|
38
|
+
if not dist_name:
|
|
39
|
+
continue
|
|
40
|
+
|
|
41
|
+
top_levels: set[str] = set()
|
|
42
|
+
top_txt = dist.read_text("top_level.txt")
|
|
43
|
+
if top_txt:
|
|
44
|
+
top_levels.update(top_txt.split())
|
|
45
|
+
|
|
46
|
+
if dist.files:
|
|
47
|
+
for file_path in dist.files:
|
|
48
|
+
parts = file_path.parts
|
|
49
|
+
if len(parts) > 1 and parts[0] != "..":
|
|
50
|
+
top_levels.add(parts[0])
|
|
51
|
+
elif len(parts) == 1 and parts[0].endswith(".py") and parts[0] != "__init__.py":
|
|
52
|
+
top_levels.add(parts[0][:-3])
|
|
53
|
+
|
|
54
|
+
norm = dist_name.replace("-", "_").lower()
|
|
55
|
+
top_levels.add(norm)
|
|
56
|
+
|
|
57
|
+
for top in top_levels:
|
|
58
|
+
if top.endswith(".dist-info") or top.endswith(".egg-info") or top == "__pycache__":
|
|
59
|
+
continue
|
|
60
|
+
if top not in mapping:
|
|
61
|
+
mapping[top] = [dist_name]
|
|
62
|
+
elif dist_name not in mapping[top]:
|
|
63
|
+
mapping[top].append(dist_name)
|
|
64
|
+
except Exception:
|
|
65
|
+
pass
|
|
66
|
+
|
|
67
|
+
return mapping
|
|
68
|
+
|
|
69
|
+
|
|
70
|
+
class ExternalDependencyResolver:
|
|
71
|
+
"""Classifies external modules and resolves distribution package names."""
|
|
72
|
+
|
|
73
|
+
def __init__(self) -> None:
|
|
74
|
+
self._dist_map: dict[str, list[str]] = get_distribution_map()
|
|
75
|
+
|
|
76
|
+
def is_installed_external(self, module_name: str) -> bool:
|
|
77
|
+
"""Return True if root package corresponds to an installed third-party package."""
|
|
78
|
+
if not module_name:
|
|
79
|
+
return False
|
|
80
|
+
root = module_name.split(".")[0]
|
|
81
|
+
return root in self._dist_map
|
|
82
|
+
|
|
83
|
+
def get_distribution_name(self, module_name: str) -> Optional[str]:
|
|
84
|
+
"""Return the installed PyPI distribution name for module_name if known."""
|
|
85
|
+
if not module_name:
|
|
86
|
+
return None
|
|
87
|
+
root = module_name.split(".")[0]
|
|
88
|
+
dists = self._dist_map.get(root)
|
|
89
|
+
if dists:
|
|
90
|
+
return dists[0]
|
|
91
|
+
return None
|
|
92
|
+
|