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,118 @@
|
|
|
1
|
+
"""``check_syntax`` and the ``syntax`` builtin checker (group G4, decisions D-BO, D-BX).
|
|
2
|
+
|
|
3
|
+
Author: Vasiliy Zdanovskiy
|
|
4
|
+
email: vasilyvz@gmail.com
|
|
5
|
+
|
|
6
|
+
Parses the content with the format's own plugin through :func:`tree_engine.facade.loads` with the
|
|
7
|
+
plain-text fallback OFF and keeps nothing: one ``Diagnostic`` per failure, ``[]`` when the content
|
|
8
|
+
is well formed. Nothing is read from or written to the filesystem; ``file_path`` is only a name
|
|
9
|
+
used to pick the format and echoed into ``Diagnostic.path``.
|
|
10
|
+
"""
|
|
11
|
+
|
|
12
|
+
from __future__ import annotations
|
|
13
|
+
|
|
14
|
+
import json
|
|
15
|
+
from typing import List, Optional, Union
|
|
16
|
+
|
|
17
|
+
from tree_engine.checks.model import Diagnostic, Severity
|
|
18
|
+
from tree_engine.checks.plugin import (
|
|
19
|
+
CheckerMetadata,
|
|
20
|
+
CheckerPlugin,
|
|
21
|
+
CheckRequest,
|
|
22
|
+
KIND_BUILTIN,
|
|
23
|
+
format_plugin_checker,
|
|
24
|
+
)
|
|
25
|
+
from tree_engine.errors import ErrorCode
|
|
26
|
+
from tree_engine.exceptions import FormatContentParseFailed
|
|
27
|
+
|
|
28
|
+
__all__ = ["check_syntax", "SyntaxChecker", "SYNTAX_FORMATS", "TOLERANT_FORMATS"]
|
|
29
|
+
|
|
30
|
+
#: Formats whose syntax is checked, mapped to the upper-case suffix of the diagnostic code.
|
|
31
|
+
SYNTAX_FORMATS = ("python", "json", "yaml", "toml", "ini", "xml")
|
|
32
|
+
#: Formats that accept any text: nothing to report.
|
|
33
|
+
TOLERANT_FORMATS = ("markdown", "jsonl", "plain_text")
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
def _decode(content: Union[str, bytes]) -> str:
|
|
37
|
+
if isinstance(content, bytes):
|
|
38
|
+
return content.decode("utf-8")
|
|
39
|
+
return content
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
def _json_is_valid(content: Union[str, bytes]) -> bool:
|
|
43
|
+
"""Cheap validity test that retains no tree; ``False`` only means "ask the plugin for the position"."""
|
|
44
|
+
try:
|
|
45
|
+
json.loads(_decode(content))
|
|
46
|
+
except (ValueError, UnicodeDecodeError, RecursionError):
|
|
47
|
+
return False
|
|
48
|
+
return True
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
def check_syntax(
|
|
52
|
+
content: Union[str, bytes],
|
|
53
|
+
format_id: Optional[str] = None,
|
|
54
|
+
file_path: Optional[str] = None,
|
|
55
|
+
) -> List[Diagnostic]:
|
|
56
|
+
"""Syntax diagnostics of ``content``; ``[]`` when it parses.
|
|
57
|
+
|
|
58
|
+
The format is ``format_id`` when given, else the one claiming ``file_path``'s extension; with
|
|
59
|
+
neither resolving a format ``FormatUnknownExtension`` is raised. Markdown and plain text
|
|
60
|
+
always give ``[]``. No plain-text fallback is used and no document is retained.
|
|
61
|
+
|
|
62
|
+
A format plugin may declare its own checker (``checker_plugin``, see
|
|
63
|
+
:data:`tree_engine.checks.plugin.FORMAT_CHECKER_ATTRIBUTE`); for that format its diagnostics are
|
|
64
|
+
returned instead of the generic parse result.
|
|
65
|
+
"""
|
|
66
|
+
if not isinstance(content, (str, bytes)):
|
|
67
|
+
raise TypeError(f"content must be str or bytes, got {type(content).__name__}")
|
|
68
|
+
from tree_engine import facade
|
|
69
|
+
|
|
70
|
+
with facade._typed(ErrorCode.FORMAT_UNKNOWN_EXTENSION):
|
|
71
|
+
plugin_format = facade._plugin(format_id, file_path).metadata.format_id
|
|
72
|
+
declared = format_plugin_checker(facade._plugin(plugin_format, None))
|
|
73
|
+
if declared is not None:
|
|
74
|
+
return list(
|
|
75
|
+
declared.check(
|
|
76
|
+
CheckRequest(path=file_path or "", source=content, format_id=plugin_format)
|
|
77
|
+
)
|
|
78
|
+
)
|
|
79
|
+
if plugin_format not in SYNTAX_FORMATS:
|
|
80
|
+
return []
|
|
81
|
+
if plugin_format == "json" and _json_is_valid(content):
|
|
82
|
+
return []
|
|
83
|
+
try:
|
|
84
|
+
facade.loads(content, format_id=plugin_format, allow_plain_text_fallback=False)
|
|
85
|
+
except FormatContentParseFailed as exc:
|
|
86
|
+
details = dict(exc.details)
|
|
87
|
+
line, column = details.get("line"), details.get("column")
|
|
88
|
+
return [
|
|
89
|
+
Diagnostic(
|
|
90
|
+
tool="syntax",
|
|
91
|
+
code=f"SYNTAX-{plugin_format.upper()}",
|
|
92
|
+
severity=Severity.ERROR,
|
|
93
|
+
message=str(details.get("message") or exc),
|
|
94
|
+
path=file_path or "",
|
|
95
|
+
line=line if isinstance(line, int) and not isinstance(line, bool) and line >= 1 else 1,
|
|
96
|
+
column=column if isinstance(column, int) and not isinstance(column, bool) and column >= 1 else 1,
|
|
97
|
+
)
|
|
98
|
+
]
|
|
99
|
+
return []
|
|
100
|
+
|
|
101
|
+
|
|
102
|
+
class SyntaxChecker(CheckerPlugin):
|
|
103
|
+
"""Builtin ``syntax`` checker: :func:`check_syntax` over a request."""
|
|
104
|
+
|
|
105
|
+
_METADATA = CheckerMetadata(
|
|
106
|
+
check_id="syntax",
|
|
107
|
+
kind=KIND_BUILTIN,
|
|
108
|
+
contract_version="1",
|
|
109
|
+
file_extensions=(".py", ".json", ".yaml", ".yml", ".toml", ".ini", ".xml"),
|
|
110
|
+
format_ids=SYNTAX_FORMATS,
|
|
111
|
+
)
|
|
112
|
+
|
|
113
|
+
@property
|
|
114
|
+
def metadata(self) -> CheckerMetadata:
|
|
115
|
+
return self._METADATA
|
|
116
|
+
|
|
117
|
+
def check(self, request: CheckRequest) -> List[Diagnostic]:
|
|
118
|
+
return check_syntax(request.source, format_id=request.format_id, file_path=request.path or None)
|
|
@@ -0,0 +1,51 @@
|
|
|
1
|
+
"""The ``xml_wellformed`` builtin checker: namespace-aware expat well-formedness (group G4).
|
|
2
|
+
|
|
3
|
+
Author: Vasiliy Zdanovskiy
|
|
4
|
+
email: vasilyvz@gmail.com
|
|
5
|
+
|
|
6
|
+
Codes are ``XML<n>`` with ``n`` the expat error number, as the Code Analysis Server reports them.
|
|
7
|
+
"""
|
|
8
|
+
|
|
9
|
+
from __future__ import annotations
|
|
10
|
+
|
|
11
|
+
from typing import List
|
|
12
|
+
|
|
13
|
+
from tree_engine.checks.model import Diagnostic, Severity
|
|
14
|
+
from tree_engine.checks.plugin import CheckerMetadata, CheckerPlugin, CheckRequest, KIND_BUILTIN
|
|
15
|
+
from tree_engine.plugins.xml_format import well_formed_failure
|
|
16
|
+
|
|
17
|
+
__all__ = ["XmlWellformedChecker"]
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
class XmlWellformedChecker(CheckerPlugin):
|
|
21
|
+
"""Reports the first well-formedness error of an XML document, including namespace rules."""
|
|
22
|
+
|
|
23
|
+
_METADATA = CheckerMetadata(
|
|
24
|
+
check_id="xml_wellformed",
|
|
25
|
+
kind=KIND_BUILTIN,
|
|
26
|
+
contract_version="1",
|
|
27
|
+
file_extensions=(".xml",),
|
|
28
|
+
format_ids=("xml",),
|
|
29
|
+
)
|
|
30
|
+
|
|
31
|
+
@property
|
|
32
|
+
def metadata(self) -> CheckerMetadata:
|
|
33
|
+
return self._METADATA
|
|
34
|
+
|
|
35
|
+
def check(self, request: CheckRequest) -> List[Diagnostic]:
|
|
36
|
+
source = request.source
|
|
37
|
+
text = source.decode("utf-8", errors="replace") if isinstance(source, bytes) else source
|
|
38
|
+
failure = well_formed_failure(text, namespaces=True)
|
|
39
|
+
if failure is None:
|
|
40
|
+
return []
|
|
41
|
+
return [
|
|
42
|
+
Diagnostic(
|
|
43
|
+
tool="xml_wellformed",
|
|
44
|
+
code=f"XML{failure['code']}",
|
|
45
|
+
severity=Severity.ERROR,
|
|
46
|
+
message=failure["message"],
|
|
47
|
+
path=request.path,
|
|
48
|
+
line=failure["line"],
|
|
49
|
+
column=failure["column"],
|
|
50
|
+
)
|
|
51
|
+
]
|
|
@@ -0,0 +1,332 @@
|
|
|
1
|
+
"""Chain element, chain configuration and the chain runner (groups G4 and G8, decisions D-BZ, D-CA, Q17 a).
|
|
2
|
+
|
|
3
|
+
Author: Vasiliy Zdanovskiy
|
|
4
|
+
email: vasilyvz@gmail.com
|
|
5
|
+
|
|
6
|
+
``run_chain`` runs every element in order; one element's findings never stop the next (no short-circuit).
|
|
7
|
+
A builtin checker runs in process, an external one as ``python -m <tool>`` through
|
|
8
|
+
:mod:`tree_engine.checks.external.runner`. ``Diagnostic.blocking`` is set from the element. Per element the
|
|
9
|
+
findings are sorted by ``(line, column, code)``; elements keep their order. A blocking element fails the run
|
|
10
|
+
when it reports an error (a builtin) or any finding (an external tool, whose finding exit code is the
|
|
11
|
+
verdict), and when its tool is not installed. Typed failures: ``CheckToolTimeout``, ``CheckToolCrashed``,
|
|
12
|
+
``CheckConfigInvalid``; a set cancel token ends the run and returns what was collected.
|
|
13
|
+
|
|
14
|
+
The package ships a default chain table (D-CM, reversing Q17 a): :func:`default_chain_table` is derived from the
|
|
15
|
+
registered checkers and the format extension table, every element blocking; callers take it through
|
|
16
|
+
:meth:`CheckChainRegistry.from_defaults`, may replace the chain of any extension, or keep building a registry
|
|
17
|
+
from their own mapping with :meth:`CheckChainRegistry.from_mapping`. A request without ``python_executable``
|
|
18
|
+
runs the external tools under the interpreter that runs the package (D-CM.10, reversing Q18 a).
|
|
19
|
+
"""
|
|
20
|
+
|
|
21
|
+
from __future__ import annotations
|
|
22
|
+
|
|
23
|
+
import asyncio
|
|
24
|
+
import dataclasses
|
|
25
|
+
import threading
|
|
26
|
+
import time
|
|
27
|
+
from dataclasses import dataclass
|
|
28
|
+
from pathlib import Path
|
|
29
|
+
from typing import Any, Callable, Dict, List, Mapping, Optional, Sequence, Tuple
|
|
30
|
+
|
|
31
|
+
from tree_engine.checks import registry
|
|
32
|
+
from tree_engine.checks.model import CheckOutcome, Diagnostic, Severity
|
|
33
|
+
from tree_engine.checks.plugin import CheckRequest, KIND_BUILTIN, KIND_EXTERNAL
|
|
34
|
+
from tree_engine.exceptions import CheckConfigInvalid
|
|
35
|
+
|
|
36
|
+
__all__ = [
|
|
37
|
+
"ChainElement",
|
|
38
|
+
"validate_chain_mapping",
|
|
39
|
+
"CheckChainRegistry",
|
|
40
|
+
"default_chain_table",
|
|
41
|
+
"run_chain",
|
|
42
|
+
"run_chain_async",
|
|
43
|
+
]
|
|
44
|
+
|
|
45
|
+
DEFAULT_TIMEOUT_S = 60.0
|
|
46
|
+
_ELEMENT_KEYS = ("tool", "blocking", "config_source", "args")
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
@dataclass(frozen=True, kw_only=True)
|
|
50
|
+
class ChainElement:
|
|
51
|
+
"""One step of a chain: a checker id, its config source, whether its findings block, extra args."""
|
|
52
|
+
|
|
53
|
+
tool: str
|
|
54
|
+
blocking: bool
|
|
55
|
+
config_source: str = "auto"
|
|
56
|
+
args: Sequence[str] = ()
|
|
57
|
+
|
|
58
|
+
def __post_init__(self) -> None:
|
|
59
|
+
if not isinstance(self.tool, str) or not self.tool:
|
|
60
|
+
raise TypeError("tool must be a non-empty str")
|
|
61
|
+
if not isinstance(self.blocking, bool):
|
|
62
|
+
raise TypeError(f"blocking must be bool, got {type(self.blocking).__name__}")
|
|
63
|
+
if not isinstance(self.config_source, str) or not self.config_source:
|
|
64
|
+
raise TypeError("config_source must be a non-empty str")
|
|
65
|
+
if isinstance(self.args, (str, bytes)) or not isinstance(self.args, Sequence):
|
|
66
|
+
raise TypeError(f"args must be a sequence of str, got {type(self.args).__name__}")
|
|
67
|
+
for item in self.args:
|
|
68
|
+
if not isinstance(item, str):
|
|
69
|
+
raise TypeError(f"args must hold str, got {type(item).__name__}")
|
|
70
|
+
object.__setattr__(self, "args", tuple(self.args))
|
|
71
|
+
|
|
72
|
+
|
|
73
|
+
# --------------------------------------------------------------------------
|
|
74
|
+
# Chain configuration
|
|
75
|
+
# --------------------------------------------------------------------------
|
|
76
|
+
|
|
77
|
+
|
|
78
|
+
def _invalid(section: str, extension: str, reason: str) -> CheckConfigInvalid:
|
|
79
|
+
return CheckConfigInvalid(
|
|
80
|
+
f"invalid check chain ({section}{' ' + extension if extension else ''}): {reason}",
|
|
81
|
+
{"section": section, "extension": extension, "reason": reason},
|
|
82
|
+
)
|
|
83
|
+
|
|
84
|
+
|
|
85
|
+
def _normalize_extension(extension: str) -> str:
|
|
86
|
+
text = extension.strip().lower()
|
|
87
|
+
return text if text.startswith(".") else "." + text
|
|
88
|
+
|
|
89
|
+
|
|
90
|
+
def _element(extension: str, index: int, raw: Any) -> ChainElement:
|
|
91
|
+
where = f"element {index}"
|
|
92
|
+
if isinstance(raw, ChainElement):
|
|
93
|
+
raw = {"tool": raw.tool, "blocking": raw.blocking, "config_source": raw.config_source, "args": list(raw.args)}
|
|
94
|
+
if not isinstance(raw, Mapping):
|
|
95
|
+
raise _invalid("element", extension, f"{where} must be a mapping, got {type(raw).__name__}")
|
|
96
|
+
unknown = sorted(str(k) for k in raw if k not in _ELEMENT_KEYS)
|
|
97
|
+
if unknown:
|
|
98
|
+
raise _invalid("element", extension, f"{where} has unknown keys {unknown}; allowed: {list(_ELEMENT_KEYS)}")
|
|
99
|
+
for required in ("tool", "blocking"):
|
|
100
|
+
if required not in raw:
|
|
101
|
+
raise _invalid("element", extension, f"{where} is missing {required!r}")
|
|
102
|
+
tool, blocking = raw["tool"], raw["blocking"]
|
|
103
|
+
if not isinstance(tool, str) or not tool:
|
|
104
|
+
raise _invalid("element", extension, f"{where}: tool must be a non-empty str")
|
|
105
|
+
if registry.get_checker_plugin(tool) is None:
|
|
106
|
+
raise _invalid("element", extension, f"{where}: tool {tool!r} is not a registered checker")
|
|
107
|
+
if not isinstance(blocking, bool):
|
|
108
|
+
raise _invalid("element", extension, f"{where}: blocking must be bool, got {type(blocking).__name__}")
|
|
109
|
+
config_source = raw.get("config_source", "auto")
|
|
110
|
+
if not isinstance(config_source, str) or not config_source:
|
|
111
|
+
raise _invalid("element", extension, f"{where}: config_source must be a non-empty str")
|
|
112
|
+
args = raw.get("args", ())
|
|
113
|
+
if isinstance(args, (str, bytes)) or not isinstance(args, (list, tuple)) or not all(isinstance(a, str) for a in args):
|
|
114
|
+
raise _invalid("element", extension, f"{where}: args must be a list of str")
|
|
115
|
+
return ChainElement(tool=tool, blocking=blocking, config_source=config_source, args=tuple(args))
|
|
116
|
+
|
|
117
|
+
|
|
118
|
+
def validate_chain_mapping(mapping: Any) -> Dict[str, Tuple[ChainElement, ...]]:
|
|
119
|
+
"""Validate ``{extension: [element, ...]}`` and return it as ``{extension: tuple[ChainElement, ...]}``.
|
|
120
|
+
|
|
121
|
+
An element is ``{"tool": str, "blocking": bool}`` with optional ``config_source`` (str, default
|
|
122
|
+
``"auto"``) and ``args`` (list of str). Extensions are normalised (lower case, leading dot). The input
|
|
123
|
+
is not modified.
|
|
124
|
+
|
|
125
|
+
Raises:
|
|
126
|
+
CheckConfigInvalid: with ``details`` ``section``, ``extension`` and ``reason``.
|
|
127
|
+
"""
|
|
128
|
+
if not isinstance(mapping, Mapping):
|
|
129
|
+
raise _invalid("mapping", "", f"must be a mapping of extension to elements, got {type(mapping).__name__}")
|
|
130
|
+
result: Dict[str, Tuple[ChainElement, ...]] = {}
|
|
131
|
+
for extension, elements in mapping.items():
|
|
132
|
+
if not isinstance(extension, str) or not extension.strip():
|
|
133
|
+
raise _invalid("extension", "", f"extension key must be a non-empty str, got {extension!r}")
|
|
134
|
+
key = _normalize_extension(extension)
|
|
135
|
+
if isinstance(elements, (str, bytes)) or not isinstance(elements, (list, tuple)):
|
|
136
|
+
raise _invalid("elements", key, f"must be a list of elements, got {type(elements).__name__}")
|
|
137
|
+
result[key] = tuple(_element(key, i, raw) for i, raw in enumerate(elements))
|
|
138
|
+
return result
|
|
139
|
+
|
|
140
|
+
|
|
141
|
+
def default_chain_table() -> Dict[str, Tuple[ChainElement, ...]]:
|
|
142
|
+
"""The shipped extension -> chain table (D-CM), a NEW dict on every call.
|
|
143
|
+
|
|
144
|
+
Derived, never hand-typed: for every extension of ``tree_engine.list_extensions()`` the chain is every
|
|
145
|
+
registered checker whose ``format_ids`` holds the extension's format id or whose ``file_extensions`` holds
|
|
146
|
+
the extension: first the checkers the format plugin itself declares, then the others in ``list_checkers()``
|
|
147
|
+
order; each element ``blocking=True``. An extension with no checker
|
|
148
|
+
has no entry. A format plugin that declares a checker joins the table with no engine edit.
|
|
149
|
+
"""
|
|
150
|
+
from tree_engine import facade
|
|
151
|
+
|
|
152
|
+
names = registry.list_checkers() # also registers the checkers declared by the format plugins
|
|
153
|
+
declared = set(registry.format_declared_checkers())
|
|
154
|
+
names = tuple(n for n in names if n in declared) + tuple(n for n in names if n not in declared)
|
|
155
|
+
metas = [registry.get_checker_plugin(name).metadata for name in names] # type: ignore[union-attr]
|
|
156
|
+
table: Dict[str, Tuple[ChainElement, ...]] = {}
|
|
157
|
+
for extension, format_id in facade.list_extensions().items():
|
|
158
|
+
key = _normalize_extension(extension)
|
|
159
|
+
chain = tuple(
|
|
160
|
+
ChainElement(tool=meta.check_id, blocking=True)
|
|
161
|
+
for meta in metas
|
|
162
|
+
if format_id in meta.format_ids or key in {_normalize_extension(e) for e in meta.file_extensions}
|
|
163
|
+
)
|
|
164
|
+
if chain:
|
|
165
|
+
table[key] = chain
|
|
166
|
+
return table
|
|
167
|
+
|
|
168
|
+
|
|
169
|
+
class CheckChainRegistry:
|
|
170
|
+
"""A validated extension-to-chain table: caller-supplied (:meth:`from_mapping`) or the shipped one (:meth:`from_defaults`)."""
|
|
171
|
+
|
|
172
|
+
def __init__(self, chains: Mapping[str, Tuple[ChainElement, ...]]) -> None:
|
|
173
|
+
self._chains: Dict[str, Tuple[ChainElement, ...]] = dict(chains)
|
|
174
|
+
|
|
175
|
+
@classmethod
|
|
176
|
+
def from_mapping(cls, mapping: Any) -> "CheckChainRegistry":
|
|
177
|
+
"""Validate ``mapping`` (see :func:`validate_chain_mapping`) and keep it."""
|
|
178
|
+
return cls(validate_chain_mapping(mapping))
|
|
179
|
+
|
|
180
|
+
@classmethod
|
|
181
|
+
def from_defaults(cls, additions: Optional[Mapping[str, Any]] = None) -> "CheckChainRegistry":
|
|
182
|
+
"""The :func:`default_chain_table`, then each extension of ``additions`` REPLACES that extension's whole chain.
|
|
183
|
+
|
|
184
|
+
An empty list replaces too (no merge). ``additions`` is validated like :func:`validate_chain_mapping`.
|
|
185
|
+
|
|
186
|
+
Raises:
|
|
187
|
+
CheckConfigInvalid: for a bad mapping, with ``details`` ``section``, ``extension`` and ``reason``.
|
|
188
|
+
"""
|
|
189
|
+
chains = default_chain_table()
|
|
190
|
+
if additions is not None:
|
|
191
|
+
chains.update(validate_chain_mapping(additions))
|
|
192
|
+
return cls(chains)
|
|
193
|
+
|
|
194
|
+
def resolve(self, extension: str, overrides: Optional[Mapping[str, Any]] = None) -> Tuple[ChainElement, ...]:
|
|
195
|
+
"""The chain of ``extension``: an entry of ``overrides`` (even an empty list) wins, else the table, else ``()``."""
|
|
196
|
+
if not isinstance(extension, str):
|
|
197
|
+
raise TypeError(f"extension must be str, got {type(extension).__name__}")
|
|
198
|
+
key = _normalize_extension(extension)
|
|
199
|
+
if overrides is not None:
|
|
200
|
+
override = validate_chain_mapping(overrides)
|
|
201
|
+
if key in override:
|
|
202
|
+
return override[key]
|
|
203
|
+
return self._chains.get(key, ())
|
|
204
|
+
|
|
205
|
+
|
|
206
|
+
# --------------------------------------------------------------------------
|
|
207
|
+
# Runner
|
|
208
|
+
# --------------------------------------------------------------------------
|
|
209
|
+
|
|
210
|
+
|
|
211
|
+
def _check_arguments(
|
|
212
|
+
chain: Any, request: Any, timeout_s: Any, process_hook: Any, cancel: Any
|
|
213
|
+
) -> List[Any]:
|
|
214
|
+
if isinstance(chain, (str, bytes)) or not isinstance(chain, Sequence):
|
|
215
|
+
raise TypeError(f"chain must be a sequence of ChainElement, got {type(chain).__name__}")
|
|
216
|
+
for element in chain:
|
|
217
|
+
if not isinstance(element, ChainElement):
|
|
218
|
+
raise TypeError(f"chain must hold ChainElement, got {type(element).__name__}")
|
|
219
|
+
if not isinstance(request, CheckRequest):
|
|
220
|
+
raise TypeError(f"request must be CheckRequest, got {type(request).__name__}")
|
|
221
|
+
if timeout_s is not None:
|
|
222
|
+
if isinstance(timeout_s, bool) or not isinstance(timeout_s, (int, float)):
|
|
223
|
+
raise TypeError(f"timeout_s must be float or None, got {type(timeout_s).__name__}")
|
|
224
|
+
if timeout_s <= 0:
|
|
225
|
+
raise ValueError(f"timeout_s must be > 0, got {timeout_s}")
|
|
226
|
+
if process_hook is not None and not callable(process_hook):
|
|
227
|
+
raise TypeError("process_hook must be callable or None")
|
|
228
|
+
if cancel is not None and not callable(getattr(cancel, "is_set", None)):
|
|
229
|
+
raise TypeError("cancel must expose is_set()")
|
|
230
|
+
plugins = []
|
|
231
|
+
for element in chain:
|
|
232
|
+
plugin = registry.get_checker_plugin(element.tool)
|
|
233
|
+
if plugin is None:
|
|
234
|
+
raise CheckConfigInvalid(
|
|
235
|
+
f"chain element names unregistered checker {element.tool!r}",
|
|
236
|
+
{"tool": element.tool, "reason": "unregistered tool"},
|
|
237
|
+
)
|
|
238
|
+
plugins.append(plugin)
|
|
239
|
+
return plugins
|
|
240
|
+
|
|
241
|
+
|
|
242
|
+
def _element_request(element: ChainElement, request: CheckRequest) -> CheckRequest:
|
|
243
|
+
config = request.config_path
|
|
244
|
+
if element.config_source != "auto":
|
|
245
|
+
config = Path(element.config_source)
|
|
246
|
+
if not config.is_absolute() and request.cwd is not None:
|
|
247
|
+
config = request.cwd / config
|
|
248
|
+
return dataclasses.replace(request, args=tuple(request.args) + tuple(element.args), config_path=config)
|
|
249
|
+
|
|
250
|
+
|
|
251
|
+
def run_chain(
|
|
252
|
+
chain: Sequence[ChainElement],
|
|
253
|
+
request: CheckRequest,
|
|
254
|
+
timeout_s: Optional[float] = None,
|
|
255
|
+
process_hook: Optional[Callable[[int], Any]] = None,
|
|
256
|
+
cancel: Optional[Any] = None,
|
|
257
|
+
) -> CheckOutcome:
|
|
258
|
+
"""Run ``chain`` over ``request`` and return the :class:`CheckOutcome`.
|
|
259
|
+
|
|
260
|
+
``timeout_s`` is the budget of each external element (default: the checker's ``default_timeout_s``);
|
|
261
|
+
``process_hook(pid)`` is told the pid of each external process; ``cancel`` is any object with
|
|
262
|
+
``is_set()``. All arguments are validated before anything runs.
|
|
263
|
+
"""
|
|
264
|
+
plugins = _check_arguments(chain, request, timeout_s, process_hook, cancel)
|
|
265
|
+
from tree_engine.checks.external.runner import run_external
|
|
266
|
+
|
|
267
|
+
started = time.monotonic()
|
|
268
|
+
diagnostics: List[Diagnostic] = []
|
|
269
|
+
blocking_failed = False
|
|
270
|
+
missing_blocking: List[str] = []
|
|
271
|
+
missing_nonblocking: List[str] = []
|
|
272
|
+
for element, plugin in zip(chain, plugins):
|
|
273
|
+
if cancel is not None and cancel.is_set():
|
|
274
|
+
break
|
|
275
|
+
element_request = _element_request(element, request)
|
|
276
|
+
if plugin.metadata.kind == KIND_BUILTIN:
|
|
277
|
+
found = plugin.check(element_request)
|
|
278
|
+
failed = any(d.severity is Severity.ERROR for d in found)
|
|
279
|
+
else:
|
|
280
|
+
budget = timeout_s if timeout_s is not None else (plugin.metadata.default_timeout_s or DEFAULT_TIMEOUT_S)
|
|
281
|
+
result = run_external(plugin, element_request, budget, process_hook, cancel)
|
|
282
|
+
if result.cancelled:
|
|
283
|
+
break
|
|
284
|
+
if result.missing:
|
|
285
|
+
(missing_blocking if element.blocking else missing_nonblocking).append(element.tool)
|
|
286
|
+
blocking_failed = blocking_failed or element.blocking
|
|
287
|
+
continue
|
|
288
|
+
found = result.diagnostics
|
|
289
|
+
failed = bool(found)
|
|
290
|
+
found = sorted(found, key=lambda d: (d.line, d.column, d.code))
|
|
291
|
+
diagnostics.extend(dataclasses.replace(d, blocking=element.blocking) for d in found)
|
|
292
|
+
if element.blocking and failed:
|
|
293
|
+
blocking_failed = True
|
|
294
|
+
return CheckOutcome(
|
|
295
|
+
diagnostics=diagnostics,
|
|
296
|
+
blocking_failed=blocking_failed,
|
|
297
|
+
missing_blocking=missing_blocking,
|
|
298
|
+
missing_nonblocking=missing_nonblocking,
|
|
299
|
+
elapsed_s=time.monotonic() - started,
|
|
300
|
+
)
|
|
301
|
+
|
|
302
|
+
|
|
303
|
+
class _EitherSet:
|
|
304
|
+
"""``is_set()`` true when the caller's token or the internal event is set."""
|
|
305
|
+
|
|
306
|
+
def __init__(self, token: Optional[Any], event: threading.Event) -> None:
|
|
307
|
+
self._token = token
|
|
308
|
+
self._event = event
|
|
309
|
+
|
|
310
|
+
def is_set(self) -> bool:
|
|
311
|
+
return self._event.is_set() or (self._token is not None and bool(self._token.is_set()))
|
|
312
|
+
|
|
313
|
+
|
|
314
|
+
async def run_chain_async(
|
|
315
|
+
chain: Sequence[ChainElement],
|
|
316
|
+
request: CheckRequest,
|
|
317
|
+
timeout_s: Optional[float] = None,
|
|
318
|
+
process_hook: Optional[Callable[[int], Any]] = None,
|
|
319
|
+
cancel: Optional[Any] = None,
|
|
320
|
+
) -> CheckOutcome:
|
|
321
|
+
""":func:`run_chain` in a worker thread: the same outcome, the event loop stays free.
|
|
322
|
+
|
|
323
|
+
Cancelling the awaiting task sets the internal cancel token, which kills the running tool's process group.
|
|
324
|
+
"""
|
|
325
|
+
_check_arguments(chain, request, timeout_s, process_hook, cancel)
|
|
326
|
+
stop = threading.Event()
|
|
327
|
+
token = _EitherSet(cancel, stop)
|
|
328
|
+
try:
|
|
329
|
+
return await asyncio.to_thread(run_chain, chain, request, timeout_s, process_hook, token)
|
|
330
|
+
except asyncio.CancelledError:
|
|
331
|
+
stop.set()
|
|
332
|
+
raise
|
|
@@ -0,0 +1,61 @@
|
|
|
1
|
+
"""Shared base of the six external checkers.
|
|
2
|
+
|
|
3
|
+
Author: Vasiliy Zdanovskiy
|
|
4
|
+
email: vasilyvz@gmail.com
|
|
5
|
+
|
|
6
|
+
``build_command(request)`` returns the argument tail that follows ``python -m <module>``; the file
|
|
7
|
+
checked is ``request.path``. ``config_path`` and ``args`` of the request are applied by the runner
|
|
8
|
+
before the call. ``parse_output(returncode, stdout, stderr)`` returns diagnostics, or ``None`` when the
|
|
9
|
+
output cannot be read as that tool's report. Paths in the diagnostics are as the tool printed them (the
|
|
10
|
+
runner makes them relative to the working directory); a diagnostic without a path carries ``""``.
|
|
11
|
+
"""
|
|
12
|
+
|
|
13
|
+
from __future__ import annotations
|
|
14
|
+
|
|
15
|
+
import re
|
|
16
|
+
from typing import FrozenSet, List, Optional, Sequence
|
|
17
|
+
|
|
18
|
+
from tree_engine.checks.model import Diagnostic, Severity
|
|
19
|
+
from tree_engine.checks.plugin import CheckerMetadata, CheckerPlugin, CheckRequest, KIND_EXTERNAL
|
|
20
|
+
|
|
21
|
+
__all__ = ["ExternalChecker", "finding"]
|
|
22
|
+
|
|
23
|
+
MAX_RAW_MESSAGE_CHARS = 500
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
def finding(tool: str, text: str, code: Optional[str] = None) -> Diagnostic:
|
|
27
|
+
"""A generic error diagnostic for output that signals a finding but matches no known format."""
|
|
28
|
+
message = " ".join(text.split())[:MAX_RAW_MESSAGE_CHARS] or f"{tool} reported a finding"
|
|
29
|
+
return Diagnostic(tool=tool, code=code or f"{tool}-finding", severity=Severity.ERROR, message=message, path="")
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
class ExternalChecker(CheckerPlugin):
|
|
33
|
+
"""Base: subclasses set ``TOOL``, ``TIMEOUT_S``, ``EXIT_CODES`` and implement the two hooks."""
|
|
34
|
+
|
|
35
|
+
TOOL = ""
|
|
36
|
+
TIMEOUT_S = 30.0
|
|
37
|
+
EXIT_CODES: FrozenSet[int] = frozenset({1})
|
|
38
|
+
|
|
39
|
+
@property
|
|
40
|
+
def metadata(self) -> CheckerMetadata:
|
|
41
|
+
return CheckerMetadata(
|
|
42
|
+
check_id=self.TOOL, kind=KIND_EXTERNAL, contract_version="1", file_extensions=(".py",),
|
|
43
|
+
format_ids=("python",), requires=(self.TOOL,), default_timeout_s=self.TIMEOUT_S,
|
|
44
|
+
)
|
|
45
|
+
|
|
46
|
+
@property
|
|
47
|
+
def finding_exit_codes(self) -> FrozenSet[int]:
|
|
48
|
+
return self.EXIT_CODES
|
|
49
|
+
|
|
50
|
+
@staticmethod
|
|
51
|
+
def config_flag(request: CheckRequest, flag: str) -> List[str]:
|
|
52
|
+
return [flag, str(request.config_path)] if request.config_path is not None else []
|
|
53
|
+
|
|
54
|
+
def build_command(self, request: CheckRequest) -> Sequence[str]:
|
|
55
|
+
raise NotImplementedError # overridden by every shipped subclass
|
|
56
|
+
|
|
57
|
+
def parse_output(self, returncode: int, stdout: str, stderr: str) -> Optional[List[Diagnostic]]:
|
|
58
|
+
raise NotImplementedError # overridden by every shipped subclass
|
|
59
|
+
|
|
60
|
+
|
|
61
|
+
FLAKE8_RE = re.compile(r"^(?P<path>.+?):(?P<line>\d+):(?P<col>\d+): (?P<code>\S+) (?P<msg>.*)$")
|
|
@@ -0,0 +1,53 @@
|
|
|
1
|
+
"""The ``bandit`` external checker (30 s default timeout; exit 1 means findings).
|
|
2
|
+
|
|
3
|
+
Author: Vasiliy Zdanovskiy
|
|
4
|
+
email: vasilyvz@gmail.com
|
|
5
|
+
|
|
6
|
+
Bandit's own issue severity maps to the package severity: HIGH to error, MEDIUM to warning, LOW to info.
|
|
7
|
+
"""
|
|
8
|
+
|
|
9
|
+
from __future__ import annotations
|
|
10
|
+
|
|
11
|
+
import json
|
|
12
|
+
from typing import List, Optional, Sequence
|
|
13
|
+
|
|
14
|
+
from tree_engine.checks.external._base import ExternalChecker
|
|
15
|
+
from tree_engine.checks.model import Diagnostic, Severity
|
|
16
|
+
from tree_engine.checks.plugin import CheckRequest
|
|
17
|
+
|
|
18
|
+
__all__ = ["BanditChecker"]
|
|
19
|
+
|
|
20
|
+
_SEVERITY = {"high": Severity.ERROR, "medium": Severity.WARNING, "low": Severity.INFO}
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
class BanditChecker(ExternalChecker):
|
|
24
|
+
"""``python -m bandit -f json``."""
|
|
25
|
+
|
|
26
|
+
TOOL = "bandit"
|
|
27
|
+
TIMEOUT_S = 30.0
|
|
28
|
+
|
|
29
|
+
def build_command(self, request: CheckRequest) -> Sequence[str]:
|
|
30
|
+
return ["-f", "json", *self.config_flag(request, "-c"), *request.args, request.path]
|
|
31
|
+
|
|
32
|
+
def parse_output(self, returncode: int, stdout: str, stderr: str) -> Optional[List[Diagnostic]]:
|
|
33
|
+
try:
|
|
34
|
+
payload = json.loads(stdout)
|
|
35
|
+
except (TypeError, ValueError):
|
|
36
|
+
return None
|
|
37
|
+
if not isinstance(payload, dict) or not isinstance(payload.get("results"), list):
|
|
38
|
+
return None
|
|
39
|
+
found: List[Diagnostic] = []
|
|
40
|
+
for item in payload["results"]:
|
|
41
|
+
if not isinstance(item, dict):
|
|
42
|
+
continue
|
|
43
|
+
found.append(Diagnostic(
|
|
44
|
+
tool="bandit", code=str(item.get("test_id") or "bandit"),
|
|
45
|
+
severity=_SEVERITY.get(str(item.get("issue_severity") or "").lower(), Severity.WARNING),
|
|
46
|
+
message=str(item.get("issue_text") or "").strip(), path=str(item.get("filename") or ""),
|
|
47
|
+
line=max(int(item.get("line_number") or 1), 1), column=max(int(item.get("col_offset") or 0) + 1, 1)))
|
|
48
|
+
for item in payload.get("errors") or []:
|
|
49
|
+
if isinstance(item, dict):
|
|
50
|
+
found.append(Diagnostic(
|
|
51
|
+
tool="bandit", code="bandit-error", severity=Severity.ERROR, path=str(item.get("filename") or ""),
|
|
52
|
+
message=str(item.get("reason") or "bandit could not process the file")))
|
|
53
|
+
return found
|
|
@@ -0,0 +1,48 @@
|
|
|
1
|
+
"""The ``black`` external checker (30 s default timeout; exit 1 means would reformat, 123 an internal error).
|
|
2
|
+
|
|
3
|
+
Author: Vasiliy Zdanovskiy
|
|
4
|
+
email: vasilyvz@gmail.com
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
from __future__ import annotations
|
|
8
|
+
|
|
9
|
+
import re
|
|
10
|
+
from typing import FrozenSet, List, Optional, Sequence
|
|
11
|
+
|
|
12
|
+
from tree_engine.checks.external._base import ExternalChecker
|
|
13
|
+
from tree_engine.checks.model import Diagnostic, Severity
|
|
14
|
+
from tree_engine.checks.plugin import CheckRequest
|
|
15
|
+
|
|
16
|
+
__all__ = ["BlackChecker"]
|
|
17
|
+
|
|
18
|
+
_WOULD_RE = re.compile(r"^would reformat (?P<path>.+)$")
|
|
19
|
+
_ERROR_RE = re.compile(r"^error: cannot format (?P<path>.+?): (?P<msg>.*?)(?:: (?P<line>\d+):(?P<col>\d+).*)?$")
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
class BlackChecker(ExternalChecker):
|
|
23
|
+
"""``python -m black --check``; the file is never modified."""
|
|
24
|
+
|
|
25
|
+
TOOL = "black"
|
|
26
|
+
TIMEOUT_S = 30.0
|
|
27
|
+
EXIT_CODES: FrozenSet[int] = frozenset({1, 123})
|
|
28
|
+
|
|
29
|
+
def build_command(self, request: CheckRequest) -> Sequence[str]:
|
|
30
|
+
return ["--check", "--no-color", *self.config_flag(request, "--config"), *request.args, request.path]
|
|
31
|
+
|
|
32
|
+
def parse_output(self, returncode: int, stdout: str, stderr: str) -> Optional[List[Diagnostic]]:
|
|
33
|
+
found: List[Diagnostic] = []
|
|
34
|
+
for raw in (stdout + "\n" + stderr).splitlines():
|
|
35
|
+
text = raw.strip()
|
|
36
|
+
would = _WOULD_RE.match(text)
|
|
37
|
+
if would:
|
|
38
|
+
found.append(Diagnostic(
|
|
39
|
+
tool="black", code="black-would-reformat", severity=Severity.ERROR, path=would["path"],
|
|
40
|
+
message="file would be reformatted by black (check-only; content not modified)"))
|
|
41
|
+
continue
|
|
42
|
+
failed = _ERROR_RE.match(text)
|
|
43
|
+
if failed:
|
|
44
|
+
found.append(Diagnostic(
|
|
45
|
+
tool="black", code="black-cannot-format", severity=Severity.ERROR, path=failed["path"],
|
|
46
|
+
message=failed["msg"].strip(), line=max(int(failed["line"] or 1), 1),
|
|
47
|
+
column=max(int(failed["col"] or 1), 1)))
|
|
48
|
+
return found
|