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.
Files changed (121) hide show
  1. ai_editor_tree_engine_dev-1.0.176.dist-info/METADATA +35 -0
  2. ai_editor_tree_engine_dev-1.0.176.dist-info/RECORD +121 -0
  3. ai_editor_tree_engine_dev-1.0.176.dist-info/WHEEL +5 -0
  4. ai_editor_tree_engine_dev-1.0.176.dist-info/licenses/LICENSE +21 -0
  5. ai_editor_tree_engine_dev-1.0.176.dist-info/top_level.txt +1 -0
  6. tree_engine/PUBLIC_API.md +161 -0
  7. tree_engine/__init__.py +327 -0
  8. tree_engine/checks/__init__.py +60 -0
  9. tree_engine/checks/builtin/__init__.py +5 -0
  10. tree_engine/checks/builtin/compile_check.py +53 -0
  11. tree_engine/checks/builtin/csv_syntax.py +51 -0
  12. tree_engine/checks/builtin/docstrings.py +211 -0
  13. tree_engine/checks/builtin/encoding.py +55 -0
  14. tree_engine/checks/builtin/fleet_rules.py +227 -0
  15. tree_engine/checks/builtin/format_syntax.py +82 -0
  16. tree_engine/checks/builtin/jsonl_syntax.py +49 -0
  17. tree_engine/checks/builtin/shipped.py +52 -0
  18. tree_engine/checks/builtin/syntax.py +118 -0
  19. tree_engine/checks/builtin/xml_wellformed.py +51 -0
  20. tree_engine/checks/chain.py +332 -0
  21. tree_engine/checks/external/__init__.py +5 -0
  22. tree_engine/checks/external/_base.py +61 -0
  23. tree_engine/checks/external/bandit.py +53 -0
  24. tree_engine/checks/external/black.py +48 -0
  25. tree_engine/checks/external/flake8.py +38 -0
  26. tree_engine/checks/external/isort.py +38 -0
  27. tree_engine/checks/external/mypy.py +45 -0
  28. tree_engine/checks/external/ruff.py +45 -0
  29. tree_engine/checks/external/runner.py +197 -0
  30. tree_engine/checks/model.py +110 -0
  31. tree_engine/checks/options.py +73 -0
  32. tree_engine/checks/plugin.py +171 -0
  33. tree_engine/checks/registry.py +349 -0
  34. tree_engine/core/address.py +376 -0
  35. tree_engine/core/identifier_map.py +266 -0
  36. tree_engine/core/identity.py +226 -0
  37. tree_engine/core/instrumentation.py +399 -0
  38. tree_engine/core/integrity.py +341 -0
  39. tree_engine/core/integrity_full.py +382 -0
  40. tree_engine/core/journal.py +260 -0
  41. tree_engine/core/journal_compose.py +571 -0
  42. tree_engine/core/live_tree.py +785 -0
  43. tree_engine/core/locking.py +188 -0
  44. tree_engine/core/move.py +585 -0
  45. tree_engine/core/move_references.py +323 -0
  46. tree_engine/core/node_types.py +408 -0
  47. tree_engine/core/nodes.py +348 -0
  48. tree_engine/core/offsets.py +24 -0
  49. tree_engine/core/operations.py +825 -0
  50. tree_engine/core/plugin_boundary.py +160 -0
  51. tree_engine/core/position_map.py +263 -0
  52. tree_engine/core/position_transfer.py +512 -0
  53. tree_engine/core/range_refresh.py +366 -0
  54. tree_engine/core/reference_cache.py +360 -0
  55. tree_engine/core/references.py +223 -0
  56. tree_engine/core/reparse.py +378 -0
  57. tree_engine/core/short_id.py +296 -0
  58. tree_engine/core/subtree_apply.py +397 -0
  59. tree_engine/core/subtree_copy.py +399 -0
  60. tree_engine/core/transactions.py +397 -0
  61. tree_engine/core/trivia.py +396 -0
  62. tree_engine/core/updates.py +398 -0
  63. tree_engine/core/validation.py +377 -0
  64. tree_engine/errors.py +104 -0
  65. tree_engine/exceptions.py +376 -0
  66. tree_engine/facade.py +4524 -0
  67. tree_engine/plugins/_statements.py +369 -0
  68. tree_engine/plugins/bsl/block_edit.py +449 -0
  69. tree_engine/plugins/bsl/blocks.py +127 -0
  70. tree_engine/plugins/bsl/checker.py +297 -0
  71. tree_engine/plugins/bsl/dialects.py +303 -0
  72. tree_engine/plugins/bsl/generator.py +481 -0
  73. tree_engine/plugins/bsl/import_map.py +995 -0
  74. tree_engine/plugins/bsl/plugin.py +452 -0
  75. tree_engine/plugins/contract.py +355 -0
  76. tree_engine/plugins/cpp/import_map.py +505 -0
  77. tree_engine/plugins/cpp/languages.py +99 -0
  78. tree_engine/plugins/cpp/plugin.py +501 -0
  79. tree_engine/plugins/csv_format.py +676 -0
  80. tree_engine/plugins/detachable.py +156 -0
  81. tree_engine/plugins/fallback.py +421 -0
  82. tree_engine/plugins/ini_format.py +330 -0
  83. tree_engine/plugins/json_format.py +813 -0
  84. tree_engine/plugins/json_pointer.py +203 -0
  85. tree_engine/plugins/jsonl_format.py +392 -0
  86. tree_engine/plugins/markdown_format.py +748 -0
  87. tree_engine/plugins/onec_query_format.py +61 -0
  88. tree_engine/plugins/parse_position.py +54 -0
  89. tree_engine/plugins/plain_text.py +1543 -0
  90. tree_engine/plugins/python/export_map.py +306 -0
  91. tree_engine/plugins/python/import_map.py +429 -0
  92. tree_engine/plugins/python/plugin.py +1710 -0
  93. tree_engine/plugins/registry.py +497 -0
  94. tree_engine/plugins/scan.py +87 -0
  95. tree_engine/plugins/selection.py +228 -0
  96. tree_engine/plugins/sql_format.py +61 -0
  97. tree_engine/plugins/toml_format.py +1072 -0
  98. tree_engine/plugins/xml_format.py +911 -0
  99. tree_engine/plugins/yaml/builder.py +49 -0
  100. tree_engine/plugins/yaml/emitter.py +225 -0
  101. tree_engine/plugins/yaml/flow.py +227 -0
  102. tree_engine/plugins/yaml/plugin.py +458 -0
  103. tree_engine/plugins/yaml/ranges.py +52 -0
  104. tree_engine/plugins/yaml/reader.py +359 -0
  105. tree_engine/plugins/yaml/scanner.py +298 -0
  106. tree_engine/query/adapter.py +283 -0
  107. tree_engine/query/engine.py +853 -0
  108. tree_engine/query/inspection.py +498 -0
  109. tree_engine/query/outline.py +288 -0
  110. tree_engine/query/predicates.py +263 -0
  111. tree_engine/query/rendered_lines.py +46 -0
  112. tree_engine/query/results.py +206 -0
  113. tree_engine/query/selector.py +400 -0
  114. tree_engine/query/xml_query.py +747 -0
  115. tree_engine/storage/codec.py +400 -0
  116. tree_engine/storage/document_bridge.py +579 -0
  117. tree_engine/storage/file_txn.py +459 -0
  118. tree_engine/storage/history.py +106 -0
  119. tree_engine/storage/lifecycle.py +622 -0
  120. tree_engine/storage/schema.py +403 -0
  121. tree_engine/storage/session_guard.py +398 -0
@@ -0,0 +1,38 @@
1
+ """The ``flake8`` external checker (30 s default timeout; exit 1 means findings).
2
+
3
+ Author: Vasiliy Zdanovskiy
4
+ email: vasilyvz@gmail.com
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ from typing import List, Optional, Sequence
10
+
11
+ from tree_engine.checks.external._base import FLAKE8_RE, ExternalChecker, finding
12
+ from tree_engine.checks.model import Diagnostic, Severity
13
+ from tree_engine.checks.plugin import CheckRequest
14
+
15
+ __all__ = ["Flake8Checker"]
16
+
17
+
18
+ class Flake8Checker(ExternalChecker):
19
+ """``python -m flake8`` with a fixed machine format."""
20
+
21
+ TOOL = "flake8"
22
+ TIMEOUT_S = 30.0
23
+
24
+ def build_command(self, request: CheckRequest) -> Sequence[str]:
25
+ return ["--format=%(path)s:%(row)d:%(col)d: %(code)s %(text)s", *self.config_flag(request, "--config"),
26
+ *request.args, request.path]
27
+
28
+ def parse_output(self, returncode: int, stdout: str, stderr: str) -> Optional[List[Diagnostic]]:
29
+ found: List[Diagnostic] = []
30
+ for raw in stdout.splitlines():
31
+ match = FLAKE8_RE.match(raw)
32
+ if match:
33
+ found.append(Diagnostic(
34
+ tool="flake8", code=match["code"], severity=Severity.ERROR, message=match["msg"].strip(),
35
+ path=match["path"], line=max(int(match["line"]), 1), column=max(int(match["col"]), 1)))
36
+ if returncode != 0 and not found and stdout.strip():
37
+ return [finding("flake8", stdout)]
38
+ return found
@@ -0,0 +1,38 @@
1
+ """The ``isort`` external checker (30 s default timeout; exit 1 means unsorted imports).
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 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__ = ["IsortChecker"]
17
+
18
+ _ISORT_RE = re.compile(r"^ERROR: (?P<path>.+?) (?P<msg>Imports are incorrectly sorted.*)$")
19
+
20
+
21
+ class IsortChecker(ExternalChecker):
22
+ """``python -m isort --check-only``; the file is never modified."""
23
+
24
+ TOOL = "isort"
25
+ TIMEOUT_S = 30.0
26
+
27
+ def build_command(self, request: CheckRequest) -> Sequence[str]:
28
+ return ["--check-only", *self.config_flag(request, "--settings-path"), *request.args, request.path]
29
+
30
+ def parse_output(self, returncode: int, stdout: str, stderr: str) -> Optional[List[Diagnostic]]:
31
+ found: List[Diagnostic] = []
32
+ for raw in (stdout + "\n" + stderr).splitlines():
33
+ match = _ISORT_RE.match(raw.strip())
34
+ if match:
35
+ found.append(Diagnostic(
36
+ tool="isort", code="isort-imports-unsorted", severity=Severity.ERROR, path=match["path"],
37
+ message=match["msg"].strip()))
38
+ return found
@@ -0,0 +1,45 @@
1
+ """The ``mypy`` external checker (60 s default timeout; exit 1 means findings).
2
+
3
+ Author: Vasiliy Zdanovskiy
4
+ email: vasilyvz@gmail.com
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ import os
10
+ import re
11
+ from typing import List, Optional, Sequence
12
+
13
+ from tree_engine.checks.external._base import ExternalChecker
14
+ from tree_engine.checks.model import Diagnostic, Severity
15
+ from tree_engine.checks.plugin import CheckRequest
16
+
17
+ __all__ = ["MypyChecker"]
18
+
19
+ _MYPY_RE = re.compile(
20
+ r"^(?P<path>.+?):(?P<line>\d+):(?:(?P<col>\d+):)? (?P<sev>error|warning|note): (?P<msg>.*?)"
21
+ r"(?:\s+\[(?P<code>[\w-]+)\])?$"
22
+ )
23
+
24
+
25
+ class MypyChecker(ExternalChecker):
26
+ """``python -m mypy`` with a fixed machine format; notes are skipped."""
27
+
28
+ TOOL = "mypy"
29
+ TIMEOUT_S = 60.0
30
+
31
+ def build_command(self, request: CheckRequest) -> Sequence[str]:
32
+ return ["--no-error-summary", "--follow-imports=silent", "--show-column-numbers", "--show-error-codes",
33
+ "--no-pretty", "--no-color-output", f"--cache-dir={os.devnull}",
34
+ *self.config_flag(request, "--config-file"), *request.args, request.path]
35
+
36
+ def parse_output(self, returncode: int, stdout: str, stderr: str) -> Optional[List[Diagnostic]]:
37
+ found: List[Diagnostic] = []
38
+ for raw in stdout.splitlines():
39
+ match = _MYPY_RE.match(raw)
40
+ if not match or match["sev"] == "note":
41
+ continue
42
+ found.append(Diagnostic(
43
+ tool="mypy", code=match["code"] or "mypy", severity=Severity(match["sev"]), message=match["msg"].strip(),
44
+ path=match["path"], line=max(int(match["line"]), 1), column=max(int(match["col"] or 1), 1)))
45
+ return found
@@ -0,0 +1,45 @@
1
+ """The ``ruff`` external checker: ``ruff check`` only (Q5 a), 30 s default timeout, exit 1 means findings.
2
+
3
+ Author: Vasiliy Zdanovskiy
4
+ email: vasilyvz@gmail.com
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ import json
10
+ from typing import 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__ = ["RuffChecker"]
17
+
18
+
19
+ class RuffChecker(ExternalChecker):
20
+ """``python -m ruff check --output-format=json`` without fixes and without a cache."""
21
+
22
+ TOOL = "ruff"
23
+ TIMEOUT_S = 30.0
24
+
25
+ def build_command(self, request: CheckRequest) -> Sequence[str]:
26
+ return ["check", "--output-format=json", "--no-fix", "--no-cache", *self.config_flag(request, "--config"),
27
+ *request.args, request.path]
28
+
29
+ def parse_output(self, returncode: int, stdout: str, stderr: str) -> Optional[List[Diagnostic]]:
30
+ try:
31
+ payload = json.loads(stdout)
32
+ except (TypeError, ValueError):
33
+ return None
34
+ if not isinstance(payload, list):
35
+ return None
36
+ found: List[Diagnostic] = []
37
+ for item in payload:
38
+ if not isinstance(item, dict):
39
+ continue
40
+ location = item.get("location") or {}
41
+ found.append(Diagnostic(
42
+ tool="ruff", code=str(item.get("code") or "ruff"), severity=Severity.ERROR,
43
+ message=str(item.get("message") or "").strip(), path=str(item.get("filename") or ""),
44
+ line=max(int(location.get("row") or 1), 1), column=max(int(location.get("column") or 1), 1)))
45
+ return found
@@ -0,0 +1,197 @@
1
+ """Subprocess runner of the external checkers (TODO 15a86bcb, group G7, decisions D-BP, D-BZ, Q13, Q18).
2
+
3
+ Author: Vasiliy Zdanovskiy
4
+ email: vasilyvz@gmail.com
5
+
6
+ A tool runs as ``<python_executable> -m <module> <args from build_command>`` in its own process group,
7
+ with the working directory ``request.cwd`` and exactly the environment ``request.env`` (the caller's
8
+ mapping; ``None`` inherits the current environment). The tool reads the file at ``request.path``
9
+ (resolved against ``cwd``): external tools need a file on disk, ``request.source`` is not written.
10
+
11
+ Outcomes: findings (exit 0, or an exit code in ``finding_exit_codes``) become diagnostics; a module the
12
+ interpreter cannot import is ``missing``; a timeout raises ``CheckToolTimeout`` after the whole process
13
+ group is killed; any other exit or unparseable output raises ``CheckToolCrashed``; a set cancel token
14
+ kills the group and ends the run with ``cancelled``.
15
+ """
16
+
17
+ from __future__ import annotations
18
+
19
+ import dataclasses
20
+ import os
21
+ import signal
22
+ import subprocess
23
+ import sys
24
+ import threading
25
+ import time
26
+ from dataclasses import dataclass
27
+ from pathlib import Path
28
+ from typing import Any, Callable, List, Optional
29
+
30
+ from tree_engine.checks.external._base import finding
31
+ from tree_engine.checks.model import Diagnostic
32
+ from tree_engine.checks.plugin import CheckerPlugin, CheckRequest
33
+ from tree_engine.exceptions import CheckConfigInvalid, CheckToolCrashed, CheckToolTimeout
34
+
35
+ __all__ = ["ExternalResult", "run_external", "require_interpreter", "normalize_path", "module_missing"]
36
+
37
+ _POLL_S = 0.05
38
+ _TAIL = 400
39
+ _REAP_S = 5.0
40
+
41
+
42
+ @dataclass
43
+ class ExternalResult:
44
+ """What one external element produced."""
45
+
46
+ diagnostics: List[Diagnostic]
47
+ missing: bool = False
48
+ cancelled: bool = False
49
+
50
+
51
+ def require_interpreter(tool: str, request: CheckRequest) -> Path:
52
+ """The caller's interpreter, else the interpreter running the package (D-CM.10, reversing Q18 a)."""
53
+ if request.python_executable is None:
54
+ return Path(sys.executable)
55
+ return request.python_executable
56
+
57
+
58
+ def module_missing(stderr: str, tool: str) -> bool:
59
+ """True when ``stderr`` says the tool's module is not installed for that interpreter."""
60
+ low = (stderr or "").lower()
61
+ return f"no module named {tool}" in low or f"no module named '{tool}'" in low
62
+
63
+
64
+ def normalize_path(path: str, cwd: Optional[Path]) -> str:
65
+ """Make a tool-reported path relative to ``cwd`` with ``/`` separators and no ``./`` prefix."""
66
+ text = path.replace("\\", "/")
67
+ if cwd is not None:
68
+ prefix = str(cwd).replace("\\", "/").rstrip("/") + "/"
69
+ if text.startswith(prefix):
70
+ text = text[len(prefix):]
71
+ while text.startswith("./"):
72
+ text = text[2:]
73
+ return text
74
+
75
+
76
+ def _kill_group(proc: "subprocess.Popen[bytes]") -> None:
77
+ try:
78
+ if os.name == "posix":
79
+ os.killpg(proc.pid, signal.SIGKILL)
80
+ else: # pragma: no cover - the fleet runs POSIX
81
+ proc.kill()
82
+ except (ProcessLookupError, PermissionError):
83
+ pass
84
+ try:
85
+ proc.wait(timeout=_REAP_S)
86
+ except subprocess.TimeoutExpired: # pragma: no cover
87
+ pass
88
+
89
+
90
+ def _drain(stream: Any, sink: List[bytes]) -> None:
91
+ try:
92
+ sink.append(stream.read())
93
+ except (OSError, ValueError):
94
+ pass
95
+
96
+
97
+ def run_external(
98
+ plugin: CheckerPlugin,
99
+ request: CheckRequest,
100
+ timeout_s: float,
101
+ process_hook: Optional[Callable[[int], Any]] = None,
102
+ cancel: Optional[Any] = None,
103
+ ) -> ExternalResult:
104
+ """Run one external checker over ``request`` and parse its output."""
105
+ meta = plugin.metadata
106
+ tool = meta.requires[0] if meta.requires else meta.check_id
107
+ interpreter = require_interpreter(meta.check_id, request)
108
+ argv = [str(interpreter), "-m", tool, *plugin.build_command(request)] # type: ignore[attr-defined]
109
+ env = dict(request.env) if request.env is not None else dict(os.environ)
110
+ cwd = str(request.cwd) if request.cwd is not None else None
111
+ try:
112
+ proc = subprocess.Popen(
113
+ argv,
114
+ cwd=cwd,
115
+ env=env,
116
+ stdin=subprocess.DEVNULL,
117
+ stdout=subprocess.PIPE,
118
+ stderr=subprocess.PIPE,
119
+ start_new_session=(os.name == "posix"),
120
+ )
121
+ except OSError as exc:
122
+ raise CheckToolCrashed(
123
+ f"{meta.check_id}: could not start {argv[0]!r}: {exc}",
124
+ {"tool": meta.check_id, "reason": f"could not start: {exc}"},
125
+ ) from exc
126
+ out: List[bytes] = []
127
+ err: List[bytes] = []
128
+ readers = [
129
+ threading.Thread(target=_drain, args=(proc.stdout, out), daemon=True),
130
+ threading.Thread(target=_drain, args=(proc.stderr, err), daemon=True),
131
+ ]
132
+ for reader in readers:
133
+ reader.start()
134
+ if process_hook is not None:
135
+ process_hook(proc.pid)
136
+ deadline = time.monotonic() + timeout_s
137
+ cancelled = False
138
+ timed_out = False
139
+ while True:
140
+ try:
141
+ proc.wait(timeout=_POLL_S)
142
+ break
143
+ except subprocess.TimeoutExpired:
144
+ pass
145
+ if cancel is not None and cancel.is_set():
146
+ cancelled = True
147
+ break
148
+ if time.monotonic() >= deadline:
149
+ timed_out = True
150
+ break
151
+ if cancelled or timed_out:
152
+ _kill_group(proc)
153
+ elif os.name == "posix":
154
+ # The tool exited; tidy any descendant it left in the group.
155
+ try:
156
+ os.killpg(proc.pid, signal.SIGKILL)
157
+ except (ProcessLookupError, PermissionError):
158
+ pass
159
+ for reader in readers:
160
+ reader.join(timeout=_REAP_S)
161
+ if timed_out:
162
+ raise CheckToolTimeout(
163
+ f"{meta.check_id} exceeded {timeout_s:g} seconds",
164
+ {"tool": meta.check_id, "timeout_s": timeout_s},
165
+ )
166
+ if cancelled:
167
+ return ExternalResult(diagnostics=[], cancelled=True)
168
+ stdout = (out[0] if out else b"").decode("utf-8", errors="replace")
169
+ stderr = (err[0] if err else b"").decode("utf-8", errors="replace")
170
+ code = proc.returncode
171
+ if code not in (0, None) and module_missing(stderr, tool):
172
+ return ExternalResult(diagnostics=[], missing=True)
173
+ finding_codes = set(plugin.finding_exit_codes) # type: ignore[attr-defined]
174
+ if code != 0 and code not in finding_codes:
175
+ tail = (stderr or stdout).strip()[-_TAIL:]
176
+ raise CheckToolCrashed(
177
+ f"{meta.check_id}: exit code {code}: {tail or 'no output'}",
178
+ {"tool": meta.check_id, "exit_code": code, "reason": tail or "no output"},
179
+ )
180
+ found = plugin.parse_output(code, stdout, stderr) # type: ignore[attr-defined]
181
+ if found is None:
182
+ tail = (stderr or stdout).strip()[-_TAIL:]
183
+ raise CheckToolCrashed(
184
+ f"{meta.check_id}: exit code {code} with unusable output: {tail or 'no output'}",
185
+ {"tool": meta.check_id, "exit_code": code, "reason": "unusable output"},
186
+ )
187
+ if code != 0 and not found:
188
+ if code == 123:
189
+ raise CheckToolCrashed(
190
+ f"{meta.check_id}: exit code 123 without a parseable error: {(stderr or stdout).strip()[-_TAIL:]}",
191
+ {"tool": meta.check_id, "exit_code": code, "reason": "no parseable error"},
192
+ )
193
+ found = [finding(meta.check_id, stdout + stderr)]
194
+ fixed = [
195
+ dataclasses.replace(d, path=normalize_path(d.path, request.cwd) or request.path) for d in found
196
+ ]
197
+ return ExternalResult(diagnostics=fixed)
@@ -0,0 +1,110 @@
1
+ """Result model of the file checks: ``Severity``, ``Diagnostic`` and ``CheckOutcome``.
2
+
3
+ Author: Vasiliy Zdanovskiy
4
+ email: vasilyvz@gmail.com
5
+
6
+ ``Diagnostic`` has exactly eight fields; ``to_dict`` returns exactly the seven keys of the Code
7
+ Analysis Server diagnostic (``tool, path, line, column, code, severity, message``) without
8
+ ``blocking`` (decision D-BV). ``CheckOutcome`` has exactly five fields (decision D-BZ).
9
+ """
10
+
11
+ from __future__ import annotations
12
+
13
+ import enum
14
+ from dataclasses import dataclass, field
15
+ from typing import Any, Dict, List
16
+
17
+ __all__ = ["Severity", "Diagnostic", "CheckOutcome"]
18
+
19
+
20
+ class Severity(str, enum.Enum):
21
+ """Severity of a diagnostic (decision D-BW)."""
22
+
23
+ ERROR = "error"
24
+ WARNING = "warning"
25
+ INFO = "info"
26
+ HINT = "hint"
27
+
28
+
29
+ def _require_str(name: str, value: Any) -> None:
30
+ if not isinstance(value, str):
31
+ raise TypeError(f"{name} must be str, got {type(value).__name__}")
32
+
33
+
34
+ def _require_position(name: str, value: Any) -> None:
35
+ if isinstance(value, bool) or not isinstance(value, int):
36
+ raise TypeError(f"{name} must be int, got {type(value).__name__}")
37
+ if value < 1:
38
+ raise ValueError(f"{name} must be >= 1, got {value}")
39
+
40
+
41
+ @dataclass(frozen=True)
42
+ class Diagnostic:
43
+ """One finding of a checker. Immutable; equal and hashable by value.
44
+
45
+ ``severity`` is a :class:`Severity` or its string value. ``line`` and ``column`` are 1-based.
46
+ ``blocking`` is set by the chain runner from the chain element, never by a checker.
47
+ """
48
+
49
+ tool: str
50
+ code: str
51
+ severity: Severity
52
+ message: str
53
+ path: str
54
+ line: int = 1
55
+ column: int = 1
56
+ blocking: bool = False
57
+
58
+ def __post_init__(self) -> None:
59
+ for name in ("tool", "code", "message", "path"):
60
+ _require_str(name, getattr(self, name))
61
+ _require_position("line", self.line)
62
+ _require_position("column", self.column)
63
+ if not isinstance(self.blocking, bool):
64
+ raise TypeError(f"blocking must be bool, got {type(self.blocking).__name__}")
65
+ severity = self.severity
66
+ if not isinstance(severity, Severity):
67
+ if not isinstance(severity, str):
68
+ raise TypeError(f"severity must be Severity or str, got {type(severity).__name__}")
69
+ try:
70
+ severity = Severity(severity)
71
+ except ValueError:
72
+ raise ValueError(
73
+ f"severity {severity!r} is not one of {[member.value for member in Severity]}"
74
+ ) from None
75
+ object.__setattr__(self, "severity", severity)
76
+
77
+ def to_dict(self) -> Dict[str, Any]:
78
+ """The seven Code Analysis Server keys, in order; ``severity`` a plain ``str``; no ``blocking``."""
79
+ return {
80
+ "tool": self.tool,
81
+ "path": self.path,
82
+ "line": self.line,
83
+ "column": self.column,
84
+ "code": self.code,
85
+ "severity": self.severity.value,
86
+ "message": self.message,
87
+ }
88
+
89
+
90
+ @dataclass
91
+ class CheckOutcome:
92
+ """Result of a chain run: findings, the blocking verdict, tools that could not run, elapsed seconds."""
93
+
94
+ diagnostics: List[Diagnostic]
95
+ blocking_failed: bool
96
+ missing_blocking: List[str] = field(default_factory=list)
97
+ missing_nonblocking: List[str] = field(default_factory=list)
98
+ elapsed_s: float = 0.0
99
+
100
+ def __post_init__(self) -> None:
101
+ for name in ("diagnostics", "missing_blocking", "missing_nonblocking"):
102
+ if not isinstance(getattr(self, name), list):
103
+ raise TypeError(f"{name} must be list, got {type(getattr(self, name)).__name__}")
104
+ if not isinstance(self.blocking_failed, bool):
105
+ raise TypeError(f"blocking_failed must be bool, got {type(self.blocking_failed).__name__}")
106
+ if isinstance(self.elapsed_s, bool) or not isinstance(self.elapsed_s, (int, float)):
107
+ raise TypeError(f"elapsed_s must be float, got {type(self.elapsed_s).__name__}")
108
+ if self.elapsed_s < 0:
109
+ raise ValueError(f"elapsed_s must be >= 0, got {self.elapsed_s}")
110
+ self.elapsed_s = float(self.elapsed_s)
@@ -0,0 +1,73 @@
1
+ """``name=value`` option tokens carried in ``CheckRequest.args`` / ``ChainElement.args``.
2
+
3
+ Author: Vasiliy Zdanovskiy
4
+ email: vasilyvz@gmail.com
5
+
6
+ A builtin checker is configured through single tokens such as ``exempt_properties=true`` (decision
7
+ D-CG Q8). An unknown option name or a malformed value is ``CheckConfigInvalid`` so a typo never
8
+ silently disables a rule.
9
+ """
10
+
11
+ from __future__ import annotations
12
+
13
+ from typing import Any, Callable, Dict, Mapping, Sequence
14
+
15
+ from tree_engine.exceptions import CheckConfigInvalid
16
+
17
+ __all__ = ["parse_options", "as_bool", "as_positive_int", "as_str_list"]
18
+
19
+ _TRUE = ("true", "1", "yes", "on")
20
+ _FALSE = ("false", "0", "no", "off")
21
+
22
+
23
+ def as_bool(text: str) -> bool:
24
+ """``true``/``false`` (also 1/0, yes/no, on/off), case-insensitive."""
25
+ low = text.strip().lower()
26
+ if low in _TRUE:
27
+ return True
28
+ if low in _FALSE:
29
+ return False
30
+ raise ValueError(f"expected true or false, got {text!r}")
31
+
32
+
33
+ def as_positive_int(text: str) -> int:
34
+ """A decimal integer >= 1."""
35
+ value = int(text.strip())
36
+ if value < 1:
37
+ raise ValueError(f"expected an integer >= 1, got {text!r}")
38
+ return value
39
+
40
+
41
+ def as_str_list(text: str) -> list:
42
+ """A comma separated list of non-empty strings."""
43
+ items = [part.strip() for part in text.split(",") if part.strip()]
44
+ if not items:
45
+ raise ValueError("expected at least one comma separated value")
46
+ return items
47
+
48
+
49
+ def parse_options(
50
+ check_id: str, args: Sequence[str], spec: Mapping[str, Callable[[str], Any]]
51
+ ) -> Dict[str, Any]:
52
+ """Parse ``args`` (``name=value`` tokens) against ``spec`` (option name to converter).
53
+
54
+ Raises:
55
+ CheckConfigInvalid: a token without ``=``, an unknown option name or a value the converter refuses.
56
+ """
57
+ options: Dict[str, Any] = {}
58
+ for token in args:
59
+ name, sep, value = token.partition("=")
60
+ name = name.strip()
61
+ if not sep or name not in spec:
62
+ raise CheckConfigInvalid(
63
+ f"checker {check_id!r}: unknown option {token!r}; known options: {', '.join(sorted(spec)) or 'none'} (as name=value)",
64
+ {"check_id": check_id, "option": token, "reason": "unknown option"},
65
+ )
66
+ try:
67
+ options[name] = spec[name](value)
68
+ except ValueError as exc:
69
+ raise CheckConfigInvalid(
70
+ f"checker {check_id!r}: option {name!r}: {exc}",
71
+ {"check_id": check_id, "option": token, "reason": str(exc)},
72
+ ) from exc
73
+ return options