ai-editor-tree-engine-dev 1.0.176__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.
- ai_editor_tree_engine_dev-1.0.176.dist-info/METADATA +35 -0
- ai_editor_tree_engine_dev-1.0.176.dist-info/RECORD +121 -0
- ai_editor_tree_engine_dev-1.0.176.dist-info/WHEEL +5 -0
- ai_editor_tree_engine_dev-1.0.176.dist-info/licenses/LICENSE +21 -0
- ai_editor_tree_engine_dev-1.0.176.dist-info/top_level.txt +1 -0
- tree_engine/PUBLIC_API.md +161 -0
- tree_engine/__init__.py +327 -0
- tree_engine/checks/__init__.py +60 -0
- tree_engine/checks/builtin/__init__.py +5 -0
- tree_engine/checks/builtin/compile_check.py +53 -0
- tree_engine/checks/builtin/csv_syntax.py +51 -0
- tree_engine/checks/builtin/docstrings.py +211 -0
- tree_engine/checks/builtin/encoding.py +55 -0
- tree_engine/checks/builtin/fleet_rules.py +227 -0
- tree_engine/checks/builtin/format_syntax.py +82 -0
- tree_engine/checks/builtin/jsonl_syntax.py +49 -0
- tree_engine/checks/builtin/shipped.py +52 -0
- tree_engine/checks/builtin/syntax.py +118 -0
- tree_engine/checks/builtin/xml_wellformed.py +51 -0
- tree_engine/checks/chain.py +332 -0
- tree_engine/checks/external/__init__.py +5 -0
- tree_engine/checks/external/_base.py +61 -0
- tree_engine/checks/external/bandit.py +53 -0
- tree_engine/checks/external/black.py +48 -0
- tree_engine/checks/external/flake8.py +38 -0
- tree_engine/checks/external/isort.py +38 -0
- tree_engine/checks/external/mypy.py +45 -0
- tree_engine/checks/external/ruff.py +45 -0
- tree_engine/checks/external/runner.py +197 -0
- tree_engine/checks/model.py +110 -0
- tree_engine/checks/options.py +73 -0
- tree_engine/checks/plugin.py +171 -0
- tree_engine/checks/registry.py +349 -0
- tree_engine/core/address.py +376 -0
- tree_engine/core/identifier_map.py +266 -0
- tree_engine/core/identity.py +226 -0
- tree_engine/core/instrumentation.py +399 -0
- tree_engine/core/integrity.py +341 -0
- tree_engine/core/integrity_full.py +382 -0
- tree_engine/core/journal.py +260 -0
- tree_engine/core/journal_compose.py +571 -0
- tree_engine/core/live_tree.py +785 -0
- tree_engine/core/locking.py +188 -0
- tree_engine/core/move.py +585 -0
- tree_engine/core/move_references.py +323 -0
- tree_engine/core/node_types.py +408 -0
- tree_engine/core/nodes.py +348 -0
- tree_engine/core/offsets.py +24 -0
- tree_engine/core/operations.py +825 -0
- tree_engine/core/plugin_boundary.py +160 -0
- tree_engine/core/position_map.py +263 -0
- tree_engine/core/position_transfer.py +512 -0
- tree_engine/core/range_refresh.py +366 -0
- tree_engine/core/reference_cache.py +360 -0
- tree_engine/core/references.py +223 -0
- tree_engine/core/reparse.py +378 -0
- tree_engine/core/short_id.py +296 -0
- tree_engine/core/subtree_apply.py +397 -0
- tree_engine/core/subtree_copy.py +399 -0
- tree_engine/core/transactions.py +397 -0
- tree_engine/core/trivia.py +396 -0
- tree_engine/core/updates.py +398 -0
- tree_engine/core/validation.py +377 -0
- tree_engine/errors.py +104 -0
- tree_engine/exceptions.py +376 -0
- tree_engine/facade.py +4524 -0
- tree_engine/plugins/_statements.py +369 -0
- tree_engine/plugins/bsl/block_edit.py +449 -0
- tree_engine/plugins/bsl/blocks.py +127 -0
- tree_engine/plugins/bsl/checker.py +297 -0
- tree_engine/plugins/bsl/dialects.py +303 -0
- tree_engine/plugins/bsl/generator.py +481 -0
- tree_engine/plugins/bsl/import_map.py +995 -0
- tree_engine/plugins/bsl/plugin.py +452 -0
- tree_engine/plugins/contract.py +355 -0
- tree_engine/plugins/cpp/import_map.py +505 -0
- tree_engine/plugins/cpp/languages.py +99 -0
- tree_engine/plugins/cpp/plugin.py +501 -0
- tree_engine/plugins/csv_format.py +676 -0
- tree_engine/plugins/detachable.py +156 -0
- tree_engine/plugins/fallback.py +421 -0
- tree_engine/plugins/ini_format.py +330 -0
- tree_engine/plugins/json_format.py +813 -0
- tree_engine/plugins/json_pointer.py +203 -0
- tree_engine/plugins/jsonl_format.py +392 -0
- tree_engine/plugins/markdown_format.py +748 -0
- tree_engine/plugins/onec_query_format.py +61 -0
- tree_engine/plugins/parse_position.py +54 -0
- tree_engine/plugins/plain_text.py +1543 -0
- tree_engine/plugins/python/export_map.py +306 -0
- tree_engine/plugins/python/import_map.py +429 -0
- tree_engine/plugins/python/plugin.py +1710 -0
- tree_engine/plugins/registry.py +497 -0
- tree_engine/plugins/scan.py +87 -0
- tree_engine/plugins/selection.py +228 -0
- tree_engine/plugins/sql_format.py +61 -0
- tree_engine/plugins/toml_format.py +1072 -0
- tree_engine/plugins/xml_format.py +911 -0
- tree_engine/plugins/yaml/builder.py +49 -0
- tree_engine/plugins/yaml/emitter.py +225 -0
- tree_engine/plugins/yaml/flow.py +227 -0
- tree_engine/plugins/yaml/plugin.py +458 -0
- tree_engine/plugins/yaml/ranges.py +52 -0
- tree_engine/plugins/yaml/reader.py +359 -0
- tree_engine/plugins/yaml/scanner.py +298 -0
- tree_engine/query/adapter.py +283 -0
- tree_engine/query/engine.py +853 -0
- tree_engine/query/inspection.py +498 -0
- tree_engine/query/outline.py +288 -0
- tree_engine/query/predicates.py +263 -0
- tree_engine/query/rendered_lines.py +46 -0
- tree_engine/query/results.py +206 -0
- tree_engine/query/selector.py +400 -0
- tree_engine/query/xml_query.py +747 -0
- tree_engine/storage/codec.py +400 -0
- tree_engine/storage/document_bridge.py +579 -0
- tree_engine/storage/file_txn.py +459 -0
- tree_engine/storage/history.py +106 -0
- tree_engine/storage/lifecycle.py +622 -0
- tree_engine/storage/schema.py +403 -0
- tree_engine/storage/session_guard.py +398 -0
|
@@ -0,0 +1,171 @@
|
|
|
1
|
+
"""Checker plugin interface: ``CheckerMetadata``, ``CheckRequest`` and ``CheckerPlugin``.
|
|
2
|
+
|
|
3
|
+
Author: Vasiliy Zdanovskiy
|
|
4
|
+
email: vasilyvz@gmail.com
|
|
5
|
+
|
|
6
|
+
A checker is either ``builtin`` (pure, synchronous ``check(request)``, never touches the filesystem or a
|
|
7
|
+
subprocess) or ``external`` (additionally ``build_command``, ``parse_output`` and ``finding_exit_codes``;
|
|
8
|
+
the runner spawns it as ``python -m <tool>`` with a caller-supplied interpreter). A builtin plugin must
|
|
9
|
+
not define the three external members; an external plugin must define all three (rule R-CK-4).
|
|
10
|
+
"""
|
|
11
|
+
|
|
12
|
+
from __future__ import annotations
|
|
13
|
+
|
|
14
|
+
import abc
|
|
15
|
+
import os
|
|
16
|
+
from dataclasses import dataclass
|
|
17
|
+
from pathlib import Path
|
|
18
|
+
from typing import Any, List, Mapping, Optional, Sequence, Tuple, Union
|
|
19
|
+
|
|
20
|
+
from tree_engine.checks.model import Diagnostic
|
|
21
|
+
|
|
22
|
+
__all__ = [
|
|
23
|
+
"CheckerMetadata",
|
|
24
|
+
"CheckRequest",
|
|
25
|
+
"CheckerPlugin",
|
|
26
|
+
"FORMAT_CHECKER_ATTRIBUTE",
|
|
27
|
+
"format_plugin_checker",
|
|
28
|
+
"KIND_BUILTIN",
|
|
29
|
+
"KIND_EXTERNAL",
|
|
30
|
+
]
|
|
31
|
+
|
|
32
|
+
#: Optional member of a FORMAT plugin: ``checker_plugin`` -- a builtin :class:`CheckerPlugin` (or a
|
|
33
|
+
#: zero-argument callable returning one) that checks the syntax/structure of that format. The checks
|
|
34
|
+
#: registry finds it by itself (no registration call, no entry point of its own) and ``check_syntax``
|
|
35
|
+
#: uses it for that format in place of the generic parse. Its ``metadata.format_ids`` must contain the
|
|
36
|
+
#: format plugin's ``format_id``; its ``check`` must not call ``check_syntax`` for the same format.
|
|
37
|
+
FORMAT_CHECKER_ATTRIBUTE = "checker_plugin"
|
|
38
|
+
|
|
39
|
+
KIND_BUILTIN = "builtin"
|
|
40
|
+
KIND_EXTERNAL = "external"
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
def _str_tuple(name: str, value: Any) -> Tuple[str, ...]:
|
|
44
|
+
if isinstance(value, str) or not isinstance(value, (tuple, list)):
|
|
45
|
+
raise TypeError(f"{name} must be a tuple or list of str, got {type(value).__name__}")
|
|
46
|
+
for item in value:
|
|
47
|
+
if not isinstance(item, str):
|
|
48
|
+
raise TypeError(f"{name} must hold str, got {type(item).__name__}")
|
|
49
|
+
return tuple(value)
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
def _optional_path(name: str, value: Any) -> Optional[Path]:
|
|
53
|
+
if value is None or isinstance(value, Path):
|
|
54
|
+
return value
|
|
55
|
+
if isinstance(value, (str, os.PathLike)):
|
|
56
|
+
return Path(value)
|
|
57
|
+
raise TypeError(f"{name} must be a path or None, got {type(value).__name__}")
|
|
58
|
+
|
|
59
|
+
|
|
60
|
+
@dataclass(frozen=True)
|
|
61
|
+
class CheckerMetadata:
|
|
62
|
+
"""Static identity of a checker plugin."""
|
|
63
|
+
|
|
64
|
+
check_id: str
|
|
65
|
+
kind: str
|
|
66
|
+
contract_version: str
|
|
67
|
+
file_extensions: Tuple[str, ...] = ()
|
|
68
|
+
format_ids: Tuple[str, ...] = ()
|
|
69
|
+
requires: Tuple[str, ...] = ()
|
|
70
|
+
default_timeout_s: Optional[float] = None
|
|
71
|
+
|
|
72
|
+
def __post_init__(self) -> None:
|
|
73
|
+
if not isinstance(self.check_id, str):
|
|
74
|
+
raise TypeError(f"check_id must be str, got {type(self.check_id).__name__}")
|
|
75
|
+
if not self.check_id:
|
|
76
|
+
raise ValueError("check_id must be a non-empty str")
|
|
77
|
+
if self.kind not in (KIND_BUILTIN, KIND_EXTERNAL):
|
|
78
|
+
raise ValueError(f"kind must be {KIND_BUILTIN!r} or {KIND_EXTERNAL!r}, got {self.kind!r}")
|
|
79
|
+
if not isinstance(self.contract_version, str) or not self.contract_version:
|
|
80
|
+
raise ValueError("contract_version must be a non-empty str")
|
|
81
|
+
for name in ("file_extensions", "format_ids", "requires"):
|
|
82
|
+
object.__setattr__(self, name, _str_tuple(name, getattr(self, name)))
|
|
83
|
+
# D-CM.8: file extensions are always lower case with a leading dot ('bsl' -> '.bsl').
|
|
84
|
+
object.__setattr__(
|
|
85
|
+
self,
|
|
86
|
+
"file_extensions",
|
|
87
|
+
tuple(e if e.startswith(".") else "." + e for e in (x.lower() for x in self.file_extensions)),
|
|
88
|
+
)
|
|
89
|
+
if not self.file_extensions and not self.format_ids:
|
|
90
|
+
raise ValueError(
|
|
91
|
+
f"checker {self.check_id!r}: at least one of file_extensions and format_ids is required"
|
|
92
|
+
)
|
|
93
|
+
timeout = self.default_timeout_s
|
|
94
|
+
if timeout is not None:
|
|
95
|
+
if isinstance(timeout, bool) or not isinstance(timeout, (int, float)):
|
|
96
|
+
raise TypeError(f"default_timeout_s must be float or None, got {type(timeout).__name__}")
|
|
97
|
+
if timeout <= 0:
|
|
98
|
+
raise ValueError(f"default_timeout_s must be > 0, got {timeout}")
|
|
99
|
+
object.__setattr__(self, "default_timeout_s", float(timeout))
|
|
100
|
+
|
|
101
|
+
|
|
102
|
+
@dataclass(frozen=True)
|
|
103
|
+
class CheckRequest:
|
|
104
|
+
"""One file handed to a checker. ``source`` is the content; the filesystem is never read."""
|
|
105
|
+
|
|
106
|
+
path: str
|
|
107
|
+
source: Union[str, bytes]
|
|
108
|
+
format_id: Optional[str] = None
|
|
109
|
+
cwd: Optional[Path] = None
|
|
110
|
+
config_path: Optional[Path] = None
|
|
111
|
+
args: Sequence[str] = ()
|
|
112
|
+
python_executable: Optional[Path] = None
|
|
113
|
+
env: Optional[Mapping[str, str]] = None
|
|
114
|
+
|
|
115
|
+
def __post_init__(self) -> None:
|
|
116
|
+
if not isinstance(self.path, str):
|
|
117
|
+
raise TypeError(f"path must be str, got {type(self.path).__name__}")
|
|
118
|
+
if not isinstance(self.source, (str, bytes)):
|
|
119
|
+
raise TypeError(f"source must be str or bytes, got {type(self.source).__name__}")
|
|
120
|
+
if self.format_id is not None and not isinstance(self.format_id, str):
|
|
121
|
+
raise TypeError(f"format_id must be str or None, got {type(self.format_id).__name__}")
|
|
122
|
+
for name in ("cwd", "config_path", "python_executable"):
|
|
123
|
+
object.__setattr__(self, name, _optional_path(name, getattr(self, name)))
|
|
124
|
+
if isinstance(self.args, (str, bytes)) or not isinstance(self.args, Sequence):
|
|
125
|
+
raise TypeError(f"args must be a sequence of str, got {type(self.args).__name__}")
|
|
126
|
+
for item in self.args:
|
|
127
|
+
if not isinstance(item, str):
|
|
128
|
+
raise TypeError(f"args must hold str, got {type(item).__name__}")
|
|
129
|
+
object.__setattr__(self, "args", tuple(self.args))
|
|
130
|
+
if self.env is not None:
|
|
131
|
+
if not isinstance(self.env, Mapping):
|
|
132
|
+
raise TypeError(f"env must be a mapping or None, got {type(self.env).__name__}")
|
|
133
|
+
object.__setattr__(self, "env", dict(self.env))
|
|
134
|
+
|
|
135
|
+
|
|
136
|
+
class CheckerPlugin(abc.ABC):
|
|
137
|
+
"""Base of every checker.
|
|
138
|
+
|
|
139
|
+
``metadata`` is required. A builtin plugin overrides ``check(request) -> list[Diagnostic]``.
|
|
140
|
+
An external plugin instead defines ``build_command(request) -> Sequence[str]``,
|
|
141
|
+
``parse_output(returncode, stdout, stderr) -> list[Diagnostic] | None`` and
|
|
142
|
+
``finding_exit_codes`` (a ``frozenset[int]``); none of these three exists on this base class, so a
|
|
143
|
+
builtin plugin that defines one is refused at registration.
|
|
144
|
+
"""
|
|
145
|
+
|
|
146
|
+
@property
|
|
147
|
+
@abc.abstractmethod
|
|
148
|
+
def metadata(self) -> CheckerMetadata:
|
|
149
|
+
"""Static identity of this checker."""
|
|
150
|
+
|
|
151
|
+
def check(self, request: CheckRequest) -> List[Diagnostic]:
|
|
152
|
+
"""Builtin entry point: findings for ``request``. External plugins need not override it."""
|
|
153
|
+
raise NotImplementedError(f"checker {self.metadata.check_id!r} has no builtin check()")
|
|
154
|
+
|
|
155
|
+
|
|
156
|
+
def format_plugin_checker(format_plugin: Any) -> Optional["CheckerPlugin"]:
|
|
157
|
+
"""The checker a format plugin declares through ``checker_plugin``, or ``None``.
|
|
158
|
+
|
|
159
|
+
Raises ``TypeError`` when the declared object is not a :class:`CheckerPlugin`.
|
|
160
|
+
"""
|
|
161
|
+
declared = getattr(format_plugin, FORMAT_CHECKER_ATTRIBUTE, None)
|
|
162
|
+
if declared is None:
|
|
163
|
+
return None
|
|
164
|
+
if callable(declared) and not isinstance(declared, CheckerPlugin):
|
|
165
|
+
declared = declared()
|
|
166
|
+
if not isinstance(declared, CheckerPlugin):
|
|
167
|
+
raise TypeError(
|
|
168
|
+
f"{FORMAT_CHECKER_ATTRIBUTE} of format plugin {getattr(format_plugin, 'metadata', format_plugin)!r} "
|
|
169
|
+
f"must be a CheckerPlugin, got {type(declared).__name__}"
|
|
170
|
+
)
|
|
171
|
+
return declared
|
|
@@ -0,0 +1,349 @@
|
|
|
1
|
+
"""Checker registry: ``register_checker_plugin``, ``list_checkers`` and ``checker_capabilities``.
|
|
2
|
+
|
|
3
|
+
Author: Vasiliy Zdanovskiy
|
|
4
|
+
email: vasilyvz@gmail.com
|
|
5
|
+
|
|
6
|
+
The fifteen shipped checkers are registered first, in a fixed order; checkers offered by installed
|
|
7
|
+
packages under the entry-point group ``tree_engine.checkers`` follow, discovered lazily on first use
|
|
8
|
+
exactly like ``tree_engine.format_plugins``. A broken entry point is skipped and reported through
|
|
9
|
+
:func:`skipped_checkers` and a ``RuntimeWarning``; it never removes a shipped checker.
|
|
10
|
+
|
|
11
|
+
Rules (R-CK-3, R-CK-4): re-registering a ``check_id`` needs ``replace=True``; a shipped ``check_id``
|
|
12
|
+
is never replaceable; a file extension or format id already claimed by ANOTHER third-party plugin is
|
|
13
|
+
always an error (the shipped checkers legitimately share ``.py``, so they hold no exclusive claim);
|
|
14
|
+
an ``external`` plugin must define ``build_command``, ``parse_output`` and ``finding_exit_codes``, a
|
|
15
|
+
``builtin`` plugin must define none of them.
|
|
16
|
+
"""
|
|
17
|
+
|
|
18
|
+
from __future__ import annotations
|
|
19
|
+
|
|
20
|
+
import importlib.metadata
|
|
21
|
+
import importlib.util
|
|
22
|
+
import json
|
|
23
|
+
import subprocess
|
|
24
|
+
import sys
|
|
25
|
+
import threading
|
|
26
|
+
import warnings
|
|
27
|
+
from pathlib import Path
|
|
28
|
+
from typing import Any, Dict, List, Optional, Tuple, Union
|
|
29
|
+
|
|
30
|
+
from tree_engine.checks.plugin import CheckerPlugin, KIND_BUILTIN, KIND_EXTERNAL, format_plugin_checker
|
|
31
|
+
from tree_engine.errors import ErrorCode
|
|
32
|
+
from tree_engine.plugins.registry import PluginRegistrationError
|
|
33
|
+
|
|
34
|
+
__all__ = [
|
|
35
|
+
"ENTRY_POINT_GROUP",
|
|
36
|
+
"register_checker_plugin",
|
|
37
|
+
"get_checker_plugin",
|
|
38
|
+
"list_checkers",
|
|
39
|
+
"checker_capabilities",
|
|
40
|
+
"skipped_checkers",
|
|
41
|
+
]
|
|
42
|
+
|
|
43
|
+
ENTRY_POINT_GROUP = "tree_engine.checkers"
|
|
44
|
+
_EXTERNAL_MEMBERS = ("build_command", "parse_output", "finding_exit_codes")
|
|
45
|
+
_PROBE_TIMEOUT_S = 60.0
|
|
46
|
+
|
|
47
|
+
_LOCK = threading.RLock()
|
|
48
|
+
_PLUGINS: Dict[str, CheckerPlugin] = {}
|
|
49
|
+
_SHIPPED: set = set()
|
|
50
|
+
_CLAIMS: Dict[Tuple[str, str], str] = {}
|
|
51
|
+
_LOAD_ERRORS: List[Dict[str, str]] = []
|
|
52
|
+
_STATE = {"shipped": False, "entry_points": False}
|
|
53
|
+
_FORMATS_SEEN: set = set()
|
|
54
|
+
_FORMAT_DECLARED: set = set() # check ids declared by a format plugin (checker_plugin)
|
|
55
|
+
|
|
56
|
+
_PROBE_SCRIPT = r"""
|
|
57
|
+
import importlib.metadata, importlib.util, json, sys
|
|
58
|
+
out = {}
|
|
59
|
+
for name in sys.argv[1:]:
|
|
60
|
+
try:
|
|
61
|
+
found = importlib.util.find_spec(name) is not None
|
|
62
|
+
except Exception:
|
|
63
|
+
found = False
|
|
64
|
+
if not found:
|
|
65
|
+
out[name] = None
|
|
66
|
+
continue
|
|
67
|
+
try:
|
|
68
|
+
out[name] = importlib.metadata.version(name)
|
|
69
|
+
except Exception:
|
|
70
|
+
out[name] = ""
|
|
71
|
+
print(json.dumps(out))
|
|
72
|
+
"""
|
|
73
|
+
|
|
74
|
+
|
|
75
|
+
def _error(message: str, **details: Any) -> PluginRegistrationError:
|
|
76
|
+
return PluginRegistrationError(error_code=ErrorCode.FORMAT_PLUGIN_CONTRACT_ERROR, message=message, **details)
|
|
77
|
+
|
|
78
|
+
|
|
79
|
+
def _validate(plugin: Any) -> None:
|
|
80
|
+
if not isinstance(plugin, CheckerPlugin):
|
|
81
|
+
raise _error(f"{plugin!r} is not a CheckerPlugin")
|
|
82
|
+
metadata = plugin.metadata
|
|
83
|
+
check_id = metadata.check_id
|
|
84
|
+
if metadata.kind == KIND_BUILTIN:
|
|
85
|
+
if type(plugin).check is CheckerPlugin.check:
|
|
86
|
+
raise _error(f"builtin checker {check_id!r} does not implement check()", check_id=check_id)
|
|
87
|
+
extra = [name for name in _EXTERNAL_MEMBERS if hasattr(plugin, name)]
|
|
88
|
+
if extra:
|
|
89
|
+
raise _error(
|
|
90
|
+
f"builtin checker {check_id!r} must not define {', '.join(extra)}", check_id=check_id
|
|
91
|
+
)
|
|
92
|
+
elif metadata.kind == KIND_EXTERNAL:
|
|
93
|
+
missing = [name for name in _EXTERNAL_MEMBERS if not hasattr(plugin, name)]
|
|
94
|
+
if missing:
|
|
95
|
+
raise _error(
|
|
96
|
+
f"external checker {check_id!r} must define {', '.join(_EXTERNAL_MEMBERS)}; missing {', '.join(missing)}",
|
|
97
|
+
check_id=check_id,
|
|
98
|
+
)
|
|
99
|
+
if not callable(plugin.build_command) or not callable(plugin.parse_output):
|
|
100
|
+
raise _error(f"external checker {check_id!r}: build_command and parse_output must be callable", check_id=check_id)
|
|
101
|
+
if not isinstance(plugin.finding_exit_codes, (frozenset, set, tuple, list)):
|
|
102
|
+
raise _error(f"external checker {check_id!r}: finding_exit_codes must be a set of ints", check_id=check_id)
|
|
103
|
+
|
|
104
|
+
|
|
105
|
+
def _claims(plugin: CheckerPlugin) -> List[Tuple[str, str]]:
|
|
106
|
+
metadata = plugin.metadata
|
|
107
|
+
return [("extension", e.lower()) for e in metadata.file_extensions] + [
|
|
108
|
+
("format", f) for f in metadata.format_ids
|
|
109
|
+
]
|
|
110
|
+
|
|
111
|
+
|
|
112
|
+
def _insert(plugin: CheckerPlugin, *, replace: bool, shipped: bool) -> None:
|
|
113
|
+
_validate(plugin)
|
|
114
|
+
check_id = plugin.metadata.check_id
|
|
115
|
+
existing = _PLUGINS.get(check_id)
|
|
116
|
+
if existing is not None:
|
|
117
|
+
if check_id in _SHIPPED:
|
|
118
|
+
raise _error(f"checker {check_id!r} is a shipped checker and cannot be replaced", check_id=check_id)
|
|
119
|
+
if not replace:
|
|
120
|
+
raise _error(
|
|
121
|
+
f"checker {check_id!r} is already registered; pass replace=True to re-register it", check_id=check_id
|
|
122
|
+
)
|
|
123
|
+
if not shipped:
|
|
124
|
+
for claim in _claims(plugin):
|
|
125
|
+
owner = _CLAIMS.get(claim)
|
|
126
|
+
if owner is not None and owner != check_id:
|
|
127
|
+
raise _error(
|
|
128
|
+
f"{claim[0]} {claim[1]!r} is already claimed by checker {owner!r}, cannot register it for {check_id!r}",
|
|
129
|
+
check_id=check_id,
|
|
130
|
+
existing_check_id=owner,
|
|
131
|
+
)
|
|
132
|
+
if existing is not None:
|
|
133
|
+
for claim in [c for c, o in _CLAIMS.items() if o == check_id]:
|
|
134
|
+
del _CLAIMS[claim]
|
|
135
|
+
_PLUGINS[check_id] = plugin
|
|
136
|
+
else:
|
|
137
|
+
_PLUGINS[check_id] = plugin
|
|
138
|
+
if shipped:
|
|
139
|
+
_SHIPPED.add(check_id)
|
|
140
|
+
else:
|
|
141
|
+
for claim in _claims(plugin):
|
|
142
|
+
_CLAIMS[claim] = check_id
|
|
143
|
+
|
|
144
|
+
|
|
145
|
+
def _ensure_shipped() -> None:
|
|
146
|
+
if _STATE["shipped"]:
|
|
147
|
+
return
|
|
148
|
+
with _LOCK:
|
|
149
|
+
if _STATE["shipped"]:
|
|
150
|
+
return
|
|
151
|
+
from tree_engine.checks.builtin.shipped import shipped_checkers
|
|
152
|
+
|
|
153
|
+
for plugin in shipped_checkers():
|
|
154
|
+
_insert(plugin, replace=False, shipped=True)
|
|
155
|
+
_STATE["shipped"] = True
|
|
156
|
+
|
|
157
|
+
|
|
158
|
+
def _record_failure(name: str, value: str, exc: BaseException) -> None:
|
|
159
|
+
_LOAD_ERRORS.append(
|
|
160
|
+
{
|
|
161
|
+
"entry_point": name,
|
|
162
|
+
"value": value,
|
|
163
|
+
"code": ErrorCode.CHECK_CONFIG_INVALID.value,
|
|
164
|
+
"error_class": "CheckConfigInvalid",
|
|
165
|
+
"error": f"{type(exc).__name__}: {exc}",
|
|
166
|
+
}
|
|
167
|
+
)
|
|
168
|
+
warnings.warn(
|
|
169
|
+
f"tree_engine.checks: entry point {name!r} ({value}) skipped: {type(exc).__name__}: {exc}",
|
|
170
|
+
RuntimeWarning,
|
|
171
|
+
stacklevel=3,
|
|
172
|
+
)
|
|
173
|
+
|
|
174
|
+
|
|
175
|
+
def _ensure_format_checkers() -> None:
|
|
176
|
+
"""Register the checker every known FORMAT plugin declares (``checker_plugin``), once per format.
|
|
177
|
+
|
|
178
|
+
Known formats are the loaded ones plus every discoverable ``tree_engine.format_plugins`` entry
|
|
179
|
+
point (loaded here); a format added later is picked up by the next call. Nothing else to wire: a
|
|
180
|
+
format plugin that declares ``checker_plugin`` is enough. A failure is skipped and reported by
|
|
181
|
+
:func:`skipped_checkers`.
|
|
182
|
+
"""
|
|
183
|
+
from tree_engine import facade
|
|
184
|
+
|
|
185
|
+
reg = facade._REGISTRY
|
|
186
|
+
try:
|
|
187
|
+
reg._ensure_entry_points_scanned()
|
|
188
|
+
known = set(facade.list_formats()) | set(reg._entry_points)
|
|
189
|
+
except Exception as exc: # noqa: BLE001 - never break the checks over discovery
|
|
190
|
+
_record_failure("tree_engine.format_plugins", "", exc)
|
|
191
|
+
return
|
|
192
|
+
for format_id in sorted(known - _FORMATS_SEEN):
|
|
193
|
+
_FORMATS_SEEN.add(format_id)
|
|
194
|
+
try:
|
|
195
|
+
format_plugin = reg.get_format_plugin(format_id)
|
|
196
|
+
checker = format_plugin_checker(format_plugin)
|
|
197
|
+
if checker is None:
|
|
198
|
+
continue
|
|
199
|
+
if format_id not in checker.metadata.format_ids:
|
|
200
|
+
raise _error(
|
|
201
|
+
f"checker {checker.metadata.check_id!r} declared by format {format_id!r} must list "
|
|
202
|
+
f"{format_id!r} in format_ids",
|
|
203
|
+
check_id=checker.metadata.check_id,
|
|
204
|
+
)
|
|
205
|
+
if checker.metadata.kind != KIND_BUILTIN:
|
|
206
|
+
raise _error(f"checker declared by format {format_id!r} must be builtin", format_id=format_id)
|
|
207
|
+
_FORMAT_DECLARED.add(checker.metadata.check_id)
|
|
208
|
+
current = _PLUGINS.get(checker.metadata.check_id)
|
|
209
|
+
if current is not None and type(current) is type(checker):
|
|
210
|
+
continue
|
|
211
|
+
# A checker the engine itself ships with its format plugin is as fixed as the shipped ones.
|
|
212
|
+
_insert(checker, replace=False, shipped=type(checker).__module__.startswith("tree_engine."))
|
|
213
|
+
except Exception as exc: # noqa: BLE001 - skipped and reported
|
|
214
|
+
_record_failure(format_id, "format plugin checker_plugin", exc)
|
|
215
|
+
|
|
216
|
+
|
|
217
|
+
def _ensure_entry_points() -> None:
|
|
218
|
+
_ensure_shipped()
|
|
219
|
+
with _LOCK:
|
|
220
|
+
_ensure_format_checkers()
|
|
221
|
+
if _STATE["entry_points"]:
|
|
222
|
+
return
|
|
223
|
+
with _LOCK:
|
|
224
|
+
if _STATE["entry_points"]:
|
|
225
|
+
return
|
|
226
|
+
_STATE["entry_points"] = True
|
|
227
|
+
try:
|
|
228
|
+
candidates = list(importlib.metadata.entry_points(group=ENTRY_POINT_GROUP))
|
|
229
|
+
except Exception as exc: # noqa: BLE001 - a broken metadata index must not break the checks
|
|
230
|
+
_record_failure(ENTRY_POINT_GROUP, "", exc)
|
|
231
|
+
return
|
|
232
|
+
for entry in candidates:
|
|
233
|
+
try:
|
|
234
|
+
loaded = entry.load()
|
|
235
|
+
plugin = loaded() if isinstance(loaded, type) else loaded
|
|
236
|
+
_insert(plugin, replace=False, shipped=False)
|
|
237
|
+
except Exception as exc: # noqa: BLE001 - skipped and reported, never fatal
|
|
238
|
+
_record_failure(entry.name, entry.value, exc)
|
|
239
|
+
|
|
240
|
+
|
|
241
|
+
def register_checker_plugin(plugin: CheckerPlugin, *, replace: bool = False) -> None:
|
|
242
|
+
"""Register ``plugin`` under its ``check_id``.
|
|
243
|
+
|
|
244
|
+
Raises ``PluginRegistrationError`` for an already registered id without ``replace=True``, for a
|
|
245
|
+
shipped id, for an extension or format id claimed by another plugin, and for a ``kind`` that does
|
|
246
|
+
not match the members the plugin defines.
|
|
247
|
+
"""
|
|
248
|
+
if not isinstance(replace, bool):
|
|
249
|
+
raise TypeError(f"replace must be bool, got {type(replace).__name__}")
|
|
250
|
+
_ensure_entry_points()
|
|
251
|
+
with _LOCK:
|
|
252
|
+
_insert(plugin, replace=replace, shipped=False)
|
|
253
|
+
|
|
254
|
+
|
|
255
|
+
def get_checker_plugin(check_id: str) -> Optional[CheckerPlugin]:
|
|
256
|
+
"""The registered plugin for ``check_id`` or ``None``."""
|
|
257
|
+
_ensure_entry_points()
|
|
258
|
+
return _PLUGINS.get(check_id)
|
|
259
|
+
|
|
260
|
+
|
|
261
|
+
def list_checkers() -> Tuple[str, ...]:
|
|
262
|
+
"""Every registered ``check_id`` in registration order."""
|
|
263
|
+
_ensure_entry_points()
|
|
264
|
+
return tuple(_PLUGINS)
|
|
265
|
+
|
|
266
|
+
|
|
267
|
+
def format_declared_checkers() -> Tuple[str, ...]:
|
|
268
|
+
"""The ``check_id`` of every checker a format plugin declares through ``checker_plugin`` (registration order)."""
|
|
269
|
+
_ensure_entry_points()
|
|
270
|
+
return tuple(check_id for check_id in _PLUGINS if check_id in _FORMAT_DECLARED)
|
|
271
|
+
|
|
272
|
+
|
|
273
|
+
def skipped_checkers() -> Tuple[Dict[str, str], ...]:
|
|
274
|
+
"""Entry points that were skipped, each a ``CHECK_CONFIG_INVALID`` record.
|
|
275
|
+
|
|
276
|
+
Keys: ``entry_point`` (name), ``value`` (the ``module:attr`` target), ``code``
|
|
277
|
+
(``"CHECK_CONFIG_INVALID"``), ``error_class`` (``"CheckConfigInvalid"``) and ``error`` (what failed).
|
|
278
|
+
"""
|
|
279
|
+
_ensure_entry_points()
|
|
280
|
+
return tuple(dict(item) for item in _LOAD_ERRORS)
|
|
281
|
+
|
|
282
|
+
|
|
283
|
+
def _probe(modules: List[str], python_executable: Optional[Union[str, Path]]) -> Dict[str, Optional[str]]:
|
|
284
|
+
"""Map module name to its version ("" when unknown) or ``None`` when it cannot be imported."""
|
|
285
|
+
if not modules:
|
|
286
|
+
return {}
|
|
287
|
+
if python_executable is None:
|
|
288
|
+
result: Dict[str, Optional[str]] = {}
|
|
289
|
+
for name in modules:
|
|
290
|
+
try:
|
|
291
|
+
found = importlib.util.find_spec(name) is not None
|
|
292
|
+
except Exception: # noqa: BLE001
|
|
293
|
+
found = False
|
|
294
|
+
if not found:
|
|
295
|
+
result[name] = None
|
|
296
|
+
continue
|
|
297
|
+
try:
|
|
298
|
+
result[name] = importlib.metadata.version(name)
|
|
299
|
+
except Exception: # noqa: BLE001
|
|
300
|
+
result[name] = ""
|
|
301
|
+
return result
|
|
302
|
+
try:
|
|
303
|
+
proc = subprocess.run(
|
|
304
|
+
[str(python_executable), "-I", "-c", _PROBE_SCRIPT, *modules],
|
|
305
|
+
capture_output=True,
|
|
306
|
+
text=True,
|
|
307
|
+
timeout=_PROBE_TIMEOUT_S,
|
|
308
|
+
)
|
|
309
|
+
if proc.returncode == 0:
|
|
310
|
+
parsed = json.loads(proc.stdout.strip().splitlines()[-1])
|
|
311
|
+
return {name: parsed.get(name) for name in modules}
|
|
312
|
+
except (OSError, ValueError, IndexError, subprocess.SubprocessError):
|
|
313
|
+
pass
|
|
314
|
+
return {name: None for name in modules}
|
|
315
|
+
|
|
316
|
+
|
|
317
|
+
def checker_capabilities(python_executable: Optional[Union[str, Path]] = None) -> Dict[str, Dict[str, Any]]:
|
|
318
|
+
"""Per ``check_id``: ``kind``, ``file_extensions``, ``format_ids``, ``requires``, ``default_timeout_s``, ``available``, ``version``.
|
|
319
|
+
|
|
320
|
+
A builtin checker is always available (``version`` is ``None``). An external checker is
|
|
321
|
+
available when every module in ``requires`` imports under ``python_executable`` (``None`` is the
|
|
322
|
+
interpreter running this package); its ``version`` is the first required module's version, a
|
|
323
|
+
``str`` or ``None`` when unknown.
|
|
324
|
+
"""
|
|
325
|
+
if python_executable is not None and not isinstance(python_executable, (str, Path)):
|
|
326
|
+
raise TypeError(f"python_executable must be a path or None, got {type(python_executable).__name__}")
|
|
327
|
+
_ensure_entry_points()
|
|
328
|
+
with _LOCK:
|
|
329
|
+
plugins = list(_PLUGINS.values())
|
|
330
|
+
modules = sorted({m for p in plugins if p.metadata.kind == KIND_EXTERNAL for m in p.metadata.requires})
|
|
331
|
+
versions = _probe(modules, python_executable)
|
|
332
|
+
out: Dict[str, Dict[str, Any]] = {}
|
|
333
|
+
for plugin in plugins:
|
|
334
|
+
meta = plugin.metadata
|
|
335
|
+
available, version = True, None
|
|
336
|
+
if meta.kind == KIND_EXTERNAL:
|
|
337
|
+
available = all(versions.get(m) is not None for m in meta.requires)
|
|
338
|
+
if available and meta.requires:
|
|
339
|
+
version = versions.get(meta.requires[0]) or "unknown"
|
|
340
|
+
out[meta.check_id] = {
|
|
341
|
+
"kind": meta.kind,
|
|
342
|
+
"file_extensions": meta.file_extensions,
|
|
343
|
+
"format_ids": meta.format_ids,
|
|
344
|
+
"requires": meta.requires,
|
|
345
|
+
"available": available,
|
|
346
|
+
"version": version,
|
|
347
|
+
"default_timeout_s": meta.default_timeout_s,
|
|
348
|
+
}
|
|
349
|
+
return out
|