-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy path_cli_config.py
More file actions
303 lines (262 loc) · 9.16 KB
/
_cli_config.py
File metadata and controls
303 lines (262 loc) · 9.16 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
# This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this
# file, You can obtain one at https://mozilla.org/MPL/2.0/.
# SPDX-License-Identifier: MPL-2.0
# Copyright (c) 2026 Den Rozhnovskiy
from __future__ import annotations
import importlib
import sys
from dataclasses import dataclass
from pathlib import Path
from typing import TYPE_CHECKING, Final
from .golden_fixtures import (
GoldenFixturePatternError,
normalize_golden_fixture_patterns,
)
if TYPE_CHECKING:
import argparse
from collections.abc import Mapping, Sequence
class ConfigValidationError(ValueError):
"""Raised when pyproject.toml contains invalid CodeClone configuration."""
@dataclass(frozen=True, slots=True)
class _ConfigKeySpec:
expected_type: type[object]
allow_none: bool = False
expected_name: str | None = None
_CONFIG_KEY_SPECS: Final[dict[str, _ConfigKeySpec]] = {
"min_loc": _ConfigKeySpec(int),
"min_stmt": _ConfigKeySpec(int),
"block_min_loc": _ConfigKeySpec(int),
"block_min_stmt": _ConfigKeySpec(int),
"segment_min_loc": _ConfigKeySpec(int),
"segment_min_stmt": _ConfigKeySpec(int),
"processes": _ConfigKeySpec(int),
"cache_path": _ConfigKeySpec(str, allow_none=True),
"max_cache_size_mb": _ConfigKeySpec(int),
"baseline": _ConfigKeySpec(str),
"max_baseline_size_mb": _ConfigKeySpec(int),
"update_baseline": _ConfigKeySpec(bool),
"fail_on_new": _ConfigKeySpec(bool),
"fail_threshold": _ConfigKeySpec(int),
"ci": _ConfigKeySpec(bool),
"fail_complexity": _ConfigKeySpec(int),
"fail_coupling": _ConfigKeySpec(int),
"fail_cohesion": _ConfigKeySpec(int),
"fail_cycles": _ConfigKeySpec(bool),
"fail_dead_code": _ConfigKeySpec(bool),
"fail_health": _ConfigKeySpec(int),
"fail_on_new_metrics": _ConfigKeySpec(bool),
"api_surface": _ConfigKeySpec(bool),
"coverage_xml": _ConfigKeySpec(str, allow_none=True),
"fail_on_typing_regression": _ConfigKeySpec(bool),
"fail_on_docstring_regression": _ConfigKeySpec(bool),
"fail_on_api_break": _ConfigKeySpec(bool),
"fail_on_untested_hotspots": _ConfigKeySpec(bool),
"min_typing_coverage": _ConfigKeySpec(int),
"min_docstring_coverage": _ConfigKeySpec(int),
"coverage_min": _ConfigKeySpec(int),
"update_metrics_baseline": _ConfigKeySpec(bool),
"metrics_baseline": _ConfigKeySpec(str),
"skip_metrics": _ConfigKeySpec(bool),
"skip_dead_code": _ConfigKeySpec(bool),
"skip_dependencies": _ConfigKeySpec(bool),
"golden_fixture_paths": _ConfigKeySpec(list, expected_name="list[str]"),
"html_out": _ConfigKeySpec(str, allow_none=True),
"json_out": _ConfigKeySpec(str, allow_none=True),
"md_out": _ConfigKeySpec(str, allow_none=True),
"sarif_out": _ConfigKeySpec(str, allow_none=True),
"text_out": _ConfigKeySpec(str, allow_none=True),
"no_progress": _ConfigKeySpec(bool),
"no_color": _ConfigKeySpec(bool),
"quiet": _ConfigKeySpec(bool),
"verbose": _ConfigKeySpec(bool),
"debug": _ConfigKeySpec(bool),
}
_PATH_CONFIG_KEYS: Final[frozenset[str]] = frozenset(
{
"cache_path",
"baseline",
"metrics_baseline",
"coverage_xml",
"html_out",
"json_out",
"md_out",
"sarif_out",
"text_out",
}
)
def collect_explicit_cli_dests(
parser: argparse.ArgumentParser,
*,
argv: Sequence[str],
) -> set[str]:
option_to_dest: dict[str, str] = {}
for action in parser._actions:
for option in action.option_strings:
option_to_dest[option] = action.dest
explicit: set[str] = set()
for token in argv:
if token == "--":
break
if not token.startswith("-"):
continue
option = token.split("=", maxsplit=1)[0]
dest = option_to_dest.get(option)
if dest is not None:
explicit.add(dest)
return explicit
def load_pyproject_config(root_path: Path) -> dict[str, object]:
config_path = root_path / "pyproject.toml"
if not config_path.exists():
return {}
payload: object
try:
payload = _load_toml(config_path)
except OSError as exc:
raise ConfigValidationError(
f"Cannot read pyproject.toml at {config_path}: {exc}"
) from exc
except ValueError as exc:
raise ConfigValidationError(f"Invalid TOML in {config_path}: {exc}") from exc
if not isinstance(payload, dict):
raise ConfigValidationError(
f"Invalid pyproject payload at {config_path}: root must be object"
)
tool_obj = payload.get("tool")
if tool_obj is None:
return {}
if not isinstance(tool_obj, dict):
raise ConfigValidationError(
f"Invalid pyproject payload at {config_path}: 'tool' must be object"
)
codeclone_obj = tool_obj.get("codeclone")
if codeclone_obj is None:
return {}
if not isinstance(codeclone_obj, dict):
raise ConfigValidationError(
"Invalid pyproject payload at "
f"{config_path}: 'tool.codeclone' must be object"
)
unknown = sorted(set(codeclone_obj.keys()) - set(_CONFIG_KEY_SPECS))
if unknown:
raise ConfigValidationError(
"Unknown key(s) in tool.codeclone: " + ", ".join(unknown)
)
validated: dict[str, object] = {}
for key in sorted(codeclone_obj.keys()):
value = _validate_config_value(
key=key,
value=codeclone_obj[key],
)
validated[key] = _normalize_path_config_value(
key=key,
value=value,
root_path=root_path,
)
return validated
def apply_pyproject_config_overrides(
*,
args: argparse.Namespace,
config_values: Mapping[str, object],
explicit_cli_dests: set[str],
) -> None:
for key, value in config_values.items():
if key in explicit_cli_dests:
continue
setattr(args, key, value)
def _validate_config_value(*, key: str, value: object) -> object:
spec = _CONFIG_KEY_SPECS[key]
if value is None:
if spec.allow_none:
return None
raise ConfigValidationError(
"Invalid value type for tool.codeclone."
f"{key}: expected {spec.expected_name or spec.expected_type.__name__}"
)
expected_type = spec.expected_type
if expected_type is bool:
return _validated_config_instance(
key=key,
value=value,
expected_type=bool,
expected_name="bool",
)
if expected_type is int:
return _validated_config_instance(
key=key,
value=value,
expected_type=int,
expected_name="int",
reject_bool=True,
)
if expected_type is str:
return _validated_config_instance(
key=key,
value=value,
expected_type=str,
expected_name="str",
)
if expected_type is list:
return _validated_string_list(key=key, value=value)
raise ConfigValidationError(f"Unsupported config key spec for tool.codeclone.{key}")
def _validated_config_instance(
*,
key: str,
value: object,
expected_type: type[object],
expected_name: str,
reject_bool: bool = False,
) -> object:
if isinstance(value, expected_type) and (
not reject_bool or not isinstance(value, bool)
):
return value
raise ConfigValidationError(
f"Invalid value type for tool.codeclone.{key}: expected {expected_name}"
)
def _validated_string_list(*, key: str, value: object) -> tuple[str, ...]:
if not isinstance(value, list):
raise ConfigValidationError(
f"Invalid value type for tool.codeclone.{key}: expected list[str]"
)
if not all(isinstance(item, str) for item in value):
raise ConfigValidationError(
f"Invalid value type for tool.codeclone.{key}: expected list[str]"
)
try:
return normalize_golden_fixture_patterns(value)
except GoldenFixturePatternError as exc:
raise ConfigValidationError(str(exc)) from exc
def _load_toml(path: Path) -> object:
if sys.version_info >= (3, 11):
import tomllib
with path.open("rb") as config_file:
return tomllib.load(config_file)
else:
try:
tomli_module = importlib.import_module("tomli")
except ModuleNotFoundError as exc:
raise ConfigValidationError(
"Python 3.10 requires dependency 'tomli' to read pyproject.toml."
) from exc
load_fn = getattr(tomli_module, "load", None)
if not callable(load_fn):
raise ConfigValidationError(
"Invalid 'tomli' module: missing callable 'load'."
)
with path.open("rb") as config_file:
return load_fn(config_file)
def _normalize_path_config_value(
*,
key: str,
value: object,
root_path: Path,
) -> object:
if key not in _PATH_CONFIG_KEYS:
return value
if not isinstance(value, str):
return value
path = Path(value).expanduser()
if path.is_absolute():
return str(path)
return str(root_path / path)