jarbin-c-coding-style 2.0.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- jarbin_c_coding_style-2.0.0.dist-info/METADATA +150 -0
- jarbin_c_coding_style-2.0.0.dist-info/RECORD +186 -0
- jarbin_c_coding_style-2.0.0.dist-info/WHEEL +4 -0
- jarbin_c_coding_style-2.0.0.dist-info/entry_points.txt +2 -0
- jarbin_c_coding_style-2.0.0.dist-info/licenses/LICENSE +674 -0
- sources/__init__.py +0 -0
- sources/__main__.py +6 -0
- sources/analysis/__init__.py +0 -0
- sources/analysis/directives.py +258 -0
- sources/analysis/lexer.py +288 -0
- sources/analysis/parser.py +1754 -0
- sources/analysis/project.py +286 -0
- sources/analysis/source.py +326 -0
- sources/analysis/syntax.py +238 -0
- sources/analysis/tokens.py +116 -0
- sources/analysis/unit.py +700 -0
- sources/application.py +118 -0
- sources/build_info.json +6 -0
- sources/cli/__init__.py +0 -0
- sources/cli/arguments.py +507 -0
- sources/cli/completion.py +610 -0
- sources/cli/context.py +258 -0
- sources/cli/converters.py +204 -0
- sources/cli/help.py +162 -0
- sources/cli/parser.py +659 -0
- sources/configs/__init__.py +0 -0
- sources/configs/editor.py +207 -0
- sources/configs/ini.py +327 -0
- sources/configs/project.py +735 -0
- sources/configs/schema/__init__.py +0 -0
- sources/configs/schema/project.py +68 -0
- sources/constants.py +801 -0
- sources/diagnostics/__init__.py +0 -0
- sources/diagnostics/fingerprint.py +82 -0
- sources/diagnostics/model.py +146 -0
- sources/engine/__init__.py +0 -0
- sources/engine/api.py +355 -0
- sources/engine/examples.py +157 -0
- sources/engine/outcome.py +114 -0
- sources/engine/plan.py +440 -0
- sources/engine/runner.py +345 -0
- sources/engine/scanner.py +179 -0
- sources/enums.py +838 -0
- sources/errors/__init__.py +0 -0
- sources/errors/exceptions.py +727 -0
- sources/fixers/__init__.py +0 -0
- sources/fixers/base.py +209 -0
- sources/fixers/conflicts.py +129 -0
- sources/fixers/diff.py +73 -0
- sources/fixers/engine.py +434 -0
- sources/fixers/journal.py +290 -0
- sources/fixers/kinds.py +30 -0
- sources/fixers/layout.py +411 -0
- sources/fixers/model.py +151 -0
- sources/fixers/registry.py +54 -0
- sources/fixers/text.py +353 -0
- sources/fixers/verify.py +123 -0
- sources/fixers/writer.py +88 -0
- sources/integrations/__init__.py +0 -0
- sources/integrations/ci/__init__.py +0 -0
- sources/integrations/ci/github.py +183 -0
- sources/integrations/editors/__init__.py +0 -0
- sources/integrations/git/__init__.py +0 -0
- sources/integrations/git/repository.py +176 -0
- sources/integrations/update/__init__.py +0 -0
- sources/integrations/update/installers.py +529 -0
- sources/integrations/update/releases.py +397 -0
- sources/integrations/update/state.py +143 -0
- sources/outputs/__init__.py +0 -0
- sources/outputs/github/__init__.py +0 -0
- sources/outputs/github/renderer.py +135 -0
- sources/outputs/html/__init__.py +0 -0
- sources/outputs/html/renderer.py +694 -0
- sources/outputs/json/__init__.py +0 -0
- sources/outputs/json/renderer.py +154 -0
- sources/outputs/json/report.schema.json +121 -0
- sources/outputs/junit/__init__.py +0 -0
- sources/outputs/junit/renderer.py +151 -0
- sources/outputs/registry.py +135 -0
- sources/outputs/report.py +224 -0
- sources/outputs/sarif/__init__.py +0 -0
- sources/outputs/sarif/renderer.py +182 -0
- sources/outputs/terminal/__init__.py +0 -0
- sources/outputs/terminal/renderer.py +184 -0
- sources/outputs/terminal/style.py +159 -0
- sources/rules/__init__.py +0 -0
- sources/rules/arguments.py +362 -0
- sources/rules/catalog.py +227 -0
- sources/rules/categories/advanced/constant_pointers.ini +46 -0
- sources/rules/categories/advanced/line_break_at_end_of_file.ini +44 -0
- sources/rules/categories/advanced/static.ini +65 -0
- sources/rules/categories/advanced/typing.ini +47 -0
- sources/rules/categories/control_structures/conditional_branching.ini +89 -0
- sources/rules/categories/control_structures/goto.ini +45 -0
- sources/rules/categories/control_structures/ternary_operators.ini +57 -0
- sources/rules/categories/extensions/language_extensions.ini +71 -0
- sources/rules/categories/files_organization/contents_of_the_repository.ini +85 -0
- sources/rules/categories/files_organization/file_coherence.ini +166 -0
- sources/rules/categories/files_organization/file_extension.ini +68 -0
- sources/rules/categories/files_organization/fixtures/program +0 -0
- sources/rules/categories/files_organization/naming_files_and_folders.ini +74 -0
- sources/rules/categories/functions/coherence_of_functions.ini +45 -0
- sources/rules/categories/functions/comments_inside_a_function.ini +45 -0
- sources/rules/categories/functions/functions_without_parameters.ini +39 -0
- sources/rules/categories/functions/naming_functions.ini +79 -0
- sources/rules/categories/functions/number_of_columns.ini +61 -0
- sources/rules/categories/functions/number_of_lines.ini +70 -0
- sources/rules/categories/functions/number_of_parameters.ini +64 -0
- sources/rules/categories/functions/structures_as_parameters.ini +44 -0
- sources/rules/categories/global_scope/constant_values.ini +49 -0
- sources/rules/categories/global_scope/file_header.ini +92 -0
- sources/rules/categories/global_scope/global_variables.ini +53 -0
- sources/rules/categories/global_scope/include.ini +39 -0
- sources/rules/categories/global_scope/indentation_of_preprocessor.ini +62 -0
- sources/rules/categories/global_scope/inline_assembly.ini +43 -0
- sources/rules/categories/global_scope/leading_trailing_lines.ini +58 -0
- sources/rules/categories/global_scope/line_endings.ini +53 -0
- sources/rules/categories/global_scope/separation_of_functions.ini +61 -0
- sources/rules/categories/global_scope/trailing_spaces.ini +45 -0
- sources/rules/categories/header_files/content.ini +104 -0
- sources/rules/categories/header_files/include_guard.ini +47 -0
- sources/rules/categories/header_files/macros.ini +57 -0
- sources/rules/categories/layout_inside_a_function_scope/blank_lines.ini +71 -0
- sources/rules/categories/layout_inside_a_function_scope/code_line_content.ini +112 -0
- sources/rules/categories/layout_inside_a_function_scope/curly_brackets.ini +94 -0
- sources/rules/categories/layout_inside_a_function_scope/indentation.ini +96 -0
- sources/rules/categories/layout_inside_a_function_scope/spaces.ini +113 -0
- sources/rules/categories/layout_inside_a_function_scope/variable_declarations.ini +65 -0
- sources/rules/categories/variables_and_types/naming_identifiers.ini +74 -0
- sources/rules/categories/variables_and_types/pointers.ini +67 -0
- sources/rules/categories/variables_and_types/structures.ini +47 -0
- sources/rules/data/verbs.txt +182 -0
- sources/rules/definition.py +430 -0
- sources/rules/loader.py +925 -0
- sources/rules/paths.py +6 -0
- sources/rules/primitives/__init__.py +0 -0
- sources/rules/primitives/base.py +297 -0
- sources/rules/primitives/braces.py +211 -0
- sources/rules/primitives/directives.py +203 -0
- sources/rules/primitives/indentation.py +376 -0
- sources/rules/primitives/layout.py +199 -0
- sources/rules/primitives/naming.py +277 -0
- sources/rules/primitives/project.py +62 -0
- sources/rules/primitives/registry.py +49 -0
- sources/rules/primitives/repository.py +129 -0
- sources/rules/primitives/review.py +87 -0
- sources/rules/primitives/semantic.py +319 -0
- sources/rules/primitives/spacing.py +210 -0
- sources/rules/primitives/structure.py +586 -0
- sources/rules/primitives/syntax.py +200 -0
- sources/rules/primitives/text.py +408 -0
- sources/rules/primitives/tokens.py +84 -0
- sources/rules/template.py +138 -0
- sources/selftest/__init__.py +0 -0
- sources/selftest/cases.py +292 -0
- sources/services.py +90 -0
- sources/subcommands/__init__.py +0 -0
- sources/subcommands/base.py +45 -0
- sources/subcommands/check/__init__.py +0 -0
- sources/subcommands/check/command.py +45 -0
- sources/subcommands/check/fixing.py +224 -0
- sources/subcommands/check/handler.py +757 -0
- sources/subcommands/info/__init__.py +0 -0
- sources/subcommands/info/command.py +45 -0
- sources/subcommands/info/handler.py +527 -0
- sources/subcommands/registry.py +37 -0
- sources/subcommands/rule/__init__.py +0 -0
- sources/subcommands/rule/command.py +45 -0
- sources/subcommands/rule/handler.py +1067 -0
- sources/subcommands/rule/render.py +273 -0
- sources/subcommands/runner.py +124 -0
- sources/subcommands/test/__init__.py +0 -0
- sources/subcommands/test/command.py +45 -0
- sources/subcommands/test/handler.py +166 -0
- sources/subcommands/test/render.py +219 -0
- sources/subcommands/test/runner.py +430 -0
- sources/subcommands/update/__init__.py +0 -0
- sources/subcommands/update/command.py +45 -0
- sources/subcommands/update/handler.py +408 -0
- sources/utils/__init__.py +0 -0
- sources/utils/build_info.py +188 -0
- sources/utils/git.py +73 -0
- sources/utils/globs.py +98 -0
- sources/utils/logging.py +154 -0
- sources/utils/schema.py +77 -0
- sources/utils/versions.py +87 -0
sources/rules/loader.py
ADDED
|
@@ -0,0 +1,925 @@
|
|
|
1
|
+
import difflib
|
|
2
|
+
import re
|
|
3
|
+
import string
|
|
4
|
+
from collections.abc import Iterable, Mapping
|
|
5
|
+
from pathlib import Path, PurePosixPath
|
|
6
|
+
from types import MappingProxyType
|
|
7
|
+
from typing import Any
|
|
8
|
+
|
|
9
|
+
from sources.configs.ini import IniDocument, IniEntry, IniSection, parse_ini
|
|
10
|
+
from sources.enums import (
|
|
11
|
+
ArgumentType,
|
|
12
|
+
BananaSupport,
|
|
13
|
+
CodeContext,
|
|
14
|
+
Detection,
|
|
15
|
+
ExampleKind,
|
|
16
|
+
FileKind,
|
|
17
|
+
FixApplicability,
|
|
18
|
+
NodeKind,
|
|
19
|
+
ReportMode,
|
|
20
|
+
RuleStatus,
|
|
21
|
+
SeverityLevel,
|
|
22
|
+
StorageFilter,
|
|
23
|
+
)
|
|
24
|
+
from sources.errors.exceptions import RuleDefinitionError, ValueConversionError
|
|
25
|
+
from sources.fixers.kinds import FIX_KINDS
|
|
26
|
+
from sources.rules.arguments import ARGUMENT_NAME_PATTERN, ArgumentSpec, adapt_reference_value, types_compatible
|
|
27
|
+
from sources.rules.definition import (
|
|
28
|
+
CheckDefinition,
|
|
29
|
+
EpitechInfo,
|
|
30
|
+
ExampleDefinition,
|
|
31
|
+
ExampleFile,
|
|
32
|
+
ExpectedFinding,
|
|
33
|
+
ParameterValue,
|
|
34
|
+
RuleDefinition,
|
|
35
|
+
Selection,
|
|
36
|
+
)
|
|
37
|
+
from sources.rules.primitives.base import STANDARD_PLACEHOLDERS, Primitive
|
|
38
|
+
from sources.rules.primitives.registry import PRIMITIVES, RESERVED_KINDS
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
# Schema version of rule files understood by this JCCS.
|
|
42
|
+
RULE_SCHEMA_VERSION: str = "2"
|
|
43
|
+
|
|
44
|
+
# Valid category, rule name, check ID and example ID: snake_case.
|
|
45
|
+
IDENTIFIER_PATTERN: re.Pattern[str] = re.compile(r"[a-z][a-z0-9_]*")
|
|
46
|
+
|
|
47
|
+
# Value meaning "every file kind" in `applies_to`.
|
|
48
|
+
ANY_FILE_KIND: str = "any"
|
|
49
|
+
|
|
50
|
+
# Keys of the `[rule]` section.
|
|
51
|
+
RULE_KEYS: frozenset[str] = frozenset({
|
|
52
|
+
"schema", "id", "code", "title", "summary", "rationale", "applies_to", "severity", "detection", "status",
|
|
53
|
+
"since", "deprecated_by", "aliases", "tags", "docs_url", "suppressible", "requires_jccs", "supersedes",
|
|
54
|
+
"conflicts_with",
|
|
55
|
+
})
|
|
56
|
+
|
|
57
|
+
# Keys of the `[epitech]` section.
|
|
58
|
+
EPITECH_KEYS: frozenset[str] = frozenset({"ref", "version", "banana", "manual_part"})
|
|
59
|
+
|
|
60
|
+
# Keys of an `[argument:*]` section.
|
|
61
|
+
ARGUMENT_KEYS: frozenset[str] = frozenset({"type", "default", "min", "max", "choices", "item_type", "description"})
|
|
62
|
+
|
|
63
|
+
# Keys every `[check:*]` section accepts, whatever its primitive.
|
|
64
|
+
CHECK_GENERIC_KEYS: frozenset[str] = frozenset({
|
|
65
|
+
"kind", "entry", "description", "severity", "detection", "applies_to", "target", "report", "message", "fix", "fix.kind",
|
|
66
|
+
})
|
|
67
|
+
|
|
68
|
+
# Prefix of the selection keys of a check.
|
|
69
|
+
WHERE_PREFIX: str = "where."
|
|
70
|
+
|
|
71
|
+
# `where.*` keys known by the engine (each primitive accepts a subset).
|
|
72
|
+
WHERE_KEYS: frozenset[str] = frozenset({"file_kind", "context", "not_context", "node", "name", "storage"})
|
|
73
|
+
|
|
74
|
+
# Keys of an `[example:*]` section.
|
|
75
|
+
EXAMPLE_KEYS: frozenset[str] = frozenset({"kind", "description", "expect"})
|
|
76
|
+
|
|
77
|
+
# Keys of an `[example:*:file:*]` section.
|
|
78
|
+
EXAMPLE_FILE_KEYS: frozenset[str] = frozenset({"code", "fixture", "final_newline"})
|
|
79
|
+
|
|
80
|
+
# Argument types that may have an empty default (empty collection or empty text).
|
|
81
|
+
EMPTY_DEFAULT_TYPES: frozenset[ArgumentType] = frozenset({ArgumentType.LIST, ArgumentType.WORD_SET, ArgumentType.STR})
|
|
82
|
+
|
|
83
|
+
# Prefix of a parameter value that references an argument.
|
|
84
|
+
REFERENCE_PREFIX: str = "@"
|
|
85
|
+
|
|
86
|
+
|
|
87
|
+
def _suggest(word: str, candidates: Iterable[str]) -> str | None:
|
|
88
|
+
"""
|
|
89
|
+
"Did you mean" hint for an unknown key.
|
|
90
|
+
|
|
91
|
+
Parameters
|
|
92
|
+
----------
|
|
93
|
+
word : str
|
|
94
|
+
The unknown word.
|
|
95
|
+
candidates : Iterable[str]
|
|
96
|
+
Known words.
|
|
97
|
+
|
|
98
|
+
Returns
|
|
99
|
+
----------
|
|
100
|
+
str | None
|
|
101
|
+
The hint, or None.
|
|
102
|
+
"""
|
|
103
|
+
matches: list[str] = difflib.get_close_matches(word, sorted(candidates), n=1)
|
|
104
|
+
return f"Did you mean '{matches[0]}'?" if matches else None
|
|
105
|
+
|
|
106
|
+
|
|
107
|
+
def bind_parameters(primitive: Primitive, check: CheckDefinition, argument_values: Mapping[str, Any]) -> dict[str, Any]:
|
|
108
|
+
"""
|
|
109
|
+
Compute the parameter values a primitive receives: literals, `@argument` references resolved with the
|
|
110
|
+
effective argument values, and primitive defaults for missing keys.
|
|
111
|
+
|
|
112
|
+
Parameters
|
|
113
|
+
----------
|
|
114
|
+
primitive : Primitive
|
|
115
|
+
The primitive of the check.
|
|
116
|
+
check : CheckDefinition
|
|
117
|
+
The check.
|
|
118
|
+
argument_values : Mapping[str, Any]
|
|
119
|
+
Effective value of every argument of the rule.
|
|
120
|
+
|
|
121
|
+
Returns
|
|
122
|
+
----------
|
|
123
|
+
dict[str, Any]
|
|
124
|
+
Parameter values by key.
|
|
125
|
+
|
|
126
|
+
Raises
|
|
127
|
+
----------
|
|
128
|
+
ValueError
|
|
129
|
+
The primitive rejects the combination of values.
|
|
130
|
+
"""
|
|
131
|
+
values: dict[str, Any] = {}
|
|
132
|
+
for spec in primitive.parameters:
|
|
133
|
+
parameter: ParameterValue | None = check.parameters.get(spec.name)
|
|
134
|
+
if parameter is None:
|
|
135
|
+
values[spec.name] = spec.default
|
|
136
|
+
elif parameter.reference is not None:
|
|
137
|
+
values[spec.name] = adapt_reference_value(spec, argument_values[parameter.reference])
|
|
138
|
+
else:
|
|
139
|
+
values[spec.name] = parameter.value
|
|
140
|
+
primitive.validate(values, check)
|
|
141
|
+
return values
|
|
142
|
+
|
|
143
|
+
|
|
144
|
+
class RuleFileReader:
|
|
145
|
+
"""
|
|
146
|
+
Read and validate one rule file (schema 2) into a RuleDefinition.
|
|
147
|
+
|
|
148
|
+
Attributes
|
|
149
|
+
----------
|
|
150
|
+
path : Path
|
|
151
|
+
The rule file.
|
|
152
|
+
display : str
|
|
153
|
+
Path shown in error messages.
|
|
154
|
+
document : IniDocument
|
|
155
|
+
The parsed file.
|
|
156
|
+
"""
|
|
157
|
+
|
|
158
|
+
def __init__(self, path: Path, text: str, display: str) -> None:
|
|
159
|
+
"""
|
|
160
|
+
Parse the file.
|
|
161
|
+
|
|
162
|
+
Parameters
|
|
163
|
+
----------
|
|
164
|
+
path : Path
|
|
165
|
+
The rule file.
|
|
166
|
+
text : str
|
|
167
|
+
Its content.
|
|
168
|
+
display : str
|
|
169
|
+
Path shown in error messages.
|
|
170
|
+
|
|
171
|
+
Returns
|
|
172
|
+
----------
|
|
173
|
+
None
|
|
174
|
+
Nothing.
|
|
175
|
+
|
|
176
|
+
Raises
|
|
177
|
+
----------
|
|
178
|
+
IniSyntaxError
|
|
179
|
+
The file breaks the INI dialect.
|
|
180
|
+
"""
|
|
181
|
+
self.path: Path = path
|
|
182
|
+
self.display: str = display
|
|
183
|
+
self.document: IniDocument = parse_ini(text, display)
|
|
184
|
+
|
|
185
|
+
def _error(self, message: str, line: int | None, hint: str | None = None) -> RuleDefinitionError:
|
|
186
|
+
"""
|
|
187
|
+
Build a located rule error.
|
|
188
|
+
|
|
189
|
+
Parameters
|
|
190
|
+
----------
|
|
191
|
+
message : str
|
|
192
|
+
Description of the problem.
|
|
193
|
+
line : int | None
|
|
194
|
+
Line of the problem.
|
|
195
|
+
hint : str | None
|
|
196
|
+
Optional suggestion.
|
|
197
|
+
|
|
198
|
+
Returns
|
|
199
|
+
----------
|
|
200
|
+
RuleDefinitionError
|
|
201
|
+
The error (to raise).
|
|
202
|
+
"""
|
|
203
|
+
return RuleDefinitionError(message, hint, path=self.display, line=line)
|
|
204
|
+
|
|
205
|
+
def _check_keys(self, section: IniSection, allowed: Iterable[str]) -> None:
|
|
206
|
+
"""
|
|
207
|
+
Reject unknown keys of a section.
|
|
208
|
+
|
|
209
|
+
Parameters
|
|
210
|
+
----------
|
|
211
|
+
section : IniSection
|
|
212
|
+
The section.
|
|
213
|
+
allowed : Iterable[str]
|
|
214
|
+
Accepted keys.
|
|
215
|
+
|
|
216
|
+
Returns
|
|
217
|
+
----------
|
|
218
|
+
None
|
|
219
|
+
Nothing.
|
|
220
|
+
|
|
221
|
+
Raises
|
|
222
|
+
----------
|
|
223
|
+
RuleDefinitionError
|
|
224
|
+
A key is unknown.
|
|
225
|
+
"""
|
|
226
|
+
known: set[str] = set(allowed)
|
|
227
|
+
for key, entry in section.entries.items():
|
|
228
|
+
if key not in known:
|
|
229
|
+
raise self._error(f"Unknown key '{key}' in [{section.name}].", entry.line, _suggest(key, known))
|
|
230
|
+
|
|
231
|
+
def _enum[E](self, section: IniSection, key: str, enum: type[E], default: E | None) -> E | None:
|
|
232
|
+
"""
|
|
233
|
+
Read an enumerated value.
|
|
234
|
+
|
|
235
|
+
Parameters
|
|
236
|
+
----------
|
|
237
|
+
section : IniSection
|
|
238
|
+
The section.
|
|
239
|
+
key : str
|
|
240
|
+
The key.
|
|
241
|
+
enum : type[E]
|
|
242
|
+
Enumeration of accepted values.
|
|
243
|
+
default : E | None
|
|
244
|
+
Value when the key is absent or empty.
|
|
245
|
+
|
|
246
|
+
Returns
|
|
247
|
+
----------
|
|
248
|
+
E | None
|
|
249
|
+
The value.
|
|
250
|
+
|
|
251
|
+
Raises
|
|
252
|
+
----------
|
|
253
|
+
RuleDefinitionError
|
|
254
|
+
The value is not accepted.
|
|
255
|
+
"""
|
|
256
|
+
text: str | None = section.text(key)
|
|
257
|
+
if text is None:
|
|
258
|
+
return default
|
|
259
|
+
try:
|
|
260
|
+
return enum(text) # type: ignore[call-arg]
|
|
261
|
+
except ValueError:
|
|
262
|
+
choices: str = ", ".join(str(member.value) for member in enum) # type: ignore[attr-defined]
|
|
263
|
+
raise self._error(f"Invalid {key} '{text}'.", section.entries[key].line, f"Expected one of: {choices}.") from None
|
|
264
|
+
|
|
265
|
+
def _bool(self, section: IniSection, key: str, default: bool) -> bool:
|
|
266
|
+
"""
|
|
267
|
+
Read a boolean (`true` / `false`).
|
|
268
|
+
|
|
269
|
+
Parameters
|
|
270
|
+
----------
|
|
271
|
+
section : IniSection
|
|
272
|
+
The section.
|
|
273
|
+
key : str
|
|
274
|
+
The key.
|
|
275
|
+
default : bool
|
|
276
|
+
Value when the key is absent or empty.
|
|
277
|
+
|
|
278
|
+
Returns
|
|
279
|
+
----------
|
|
280
|
+
bool
|
|
281
|
+
The value.
|
|
282
|
+
|
|
283
|
+
Raises
|
|
284
|
+
----------
|
|
285
|
+
RuleDefinitionError
|
|
286
|
+
The value is not a boolean.
|
|
287
|
+
"""
|
|
288
|
+
text: str | None = section.text(key)
|
|
289
|
+
if text is None:
|
|
290
|
+
return default
|
|
291
|
+
if text not in ("true", "false"):
|
|
292
|
+
raise self._error(f"Invalid {key} '{text}'.", section.entries[key].line, "Expected 'true' or 'false'.")
|
|
293
|
+
return text == "true"
|
|
294
|
+
|
|
295
|
+
def _list(self, section: IniSection, key: str) -> tuple[str, ...]:
|
|
296
|
+
"""
|
|
297
|
+
Read a comma-separated or multi-line list of words.
|
|
298
|
+
|
|
299
|
+
Parameters
|
|
300
|
+
----------
|
|
301
|
+
section : IniSection
|
|
302
|
+
The section.
|
|
303
|
+
key : str
|
|
304
|
+
The key.
|
|
305
|
+
|
|
306
|
+
Returns
|
|
307
|
+
----------
|
|
308
|
+
tuple[str, ...]
|
|
309
|
+
The items.
|
|
310
|
+
"""
|
|
311
|
+
text: str | None = section.text(key)
|
|
312
|
+
if text is None:
|
|
313
|
+
return ()
|
|
314
|
+
separator: str = "\n" if "\n" in text else ","
|
|
315
|
+
return tuple(item.strip() for item in text.split(separator) if item.strip())
|
|
316
|
+
|
|
317
|
+
def _file_kinds(self, section: IniSection, key: str) -> frozenset[FileKind] | None:
|
|
318
|
+
"""
|
|
319
|
+
Read an `applies_to` / `where.file_kind` value.
|
|
320
|
+
|
|
321
|
+
Parameters
|
|
322
|
+
----------
|
|
323
|
+
section : IniSection
|
|
324
|
+
The section.
|
|
325
|
+
key : str
|
|
326
|
+
The key.
|
|
327
|
+
|
|
328
|
+
Returns
|
|
329
|
+
----------
|
|
330
|
+
frozenset[FileKind] | None
|
|
331
|
+
The kinds, or None when absent.
|
|
332
|
+
|
|
333
|
+
Raises
|
|
334
|
+
----------
|
|
335
|
+
RuleDefinitionError
|
|
336
|
+
A kind is unknown.
|
|
337
|
+
"""
|
|
338
|
+
items: tuple[str, ...] = self._list(section, key)
|
|
339
|
+
if not items:
|
|
340
|
+
return None
|
|
341
|
+
if ANY_FILE_KIND in items:
|
|
342
|
+
return frozenset(FileKind)
|
|
343
|
+
kinds: set[FileKind] = set()
|
|
344
|
+
for item in items:
|
|
345
|
+
try:
|
|
346
|
+
kinds.add(FileKind(item))
|
|
347
|
+
except ValueError:
|
|
348
|
+
raise self._error(f"Unknown file kind '{item}' in {key}.", section.entries[key].line, "Expected c, h, make, other or any.") from None
|
|
349
|
+
return frozenset(kinds)
|
|
350
|
+
|
|
351
|
+
# ------------------------------------------------------------------
|
|
352
|
+
# Sections
|
|
353
|
+
# ------------------------------------------------------------------
|
|
354
|
+
|
|
355
|
+
def _read_arguments(self) -> dict[str, ArgumentSpec]:
|
|
356
|
+
"""
|
|
357
|
+
Read every `[argument:<name>]` section.
|
|
358
|
+
|
|
359
|
+
Returns
|
|
360
|
+
----------
|
|
361
|
+
dict[str, ArgumentSpec]
|
|
362
|
+
Arguments by name.
|
|
363
|
+
|
|
364
|
+
Raises
|
|
365
|
+
----------
|
|
366
|
+
RuleDefinitionError
|
|
367
|
+
An argument is invalid.
|
|
368
|
+
"""
|
|
369
|
+
arguments: dict[str, ArgumentSpec] = {}
|
|
370
|
+
for name, section in self.document.sections.items():
|
|
371
|
+
if not name.startswith("argument:"):
|
|
372
|
+
continue
|
|
373
|
+
argument: str = name[len("argument:"):]
|
|
374
|
+
if not ARGUMENT_NAME_PATTERN.fullmatch(argument):
|
|
375
|
+
raise self._error(f"Invalid argument name '{argument}'.", section.line, "Use snake_case.")
|
|
376
|
+
self._check_keys(section, ARGUMENT_KEYS)
|
|
377
|
+
kind: ArgumentType | None = self._enum(section, "type", ArgumentType, None)
|
|
378
|
+
if kind is None:
|
|
379
|
+
raise self._error(f"Argument '{argument}' has no type.", section.line)
|
|
380
|
+
item_type: ArgumentType | None = self._enum(section, "item_type", ArgumentType, None)
|
|
381
|
+
bounds: dict[str, float | None] = {}
|
|
382
|
+
for bound in ("min", "max"):
|
|
383
|
+
text: str | None = section.text(bound)
|
|
384
|
+
try:
|
|
385
|
+
bounds[bound] = float(text) if text is not None else None
|
|
386
|
+
except ValueError:
|
|
387
|
+
raise self._error(f"Invalid {bound} '{text}' for argument '{argument}'.", section.entries[bound].line) from None
|
|
388
|
+
spec: ArgumentSpec = ArgumentSpec(
|
|
389
|
+
name=argument,
|
|
390
|
+
type=kind,
|
|
391
|
+
minimum=bounds["min"],
|
|
392
|
+
maximum=bounds["max"],
|
|
393
|
+
choices=self._list(section, "choices"),
|
|
394
|
+
item_type=item_type,
|
|
395
|
+
description=section.text("description") or "",
|
|
396
|
+
)
|
|
397
|
+
if kind is ArgumentType.ENUM and not spec.choices:
|
|
398
|
+
raise self._error(f"Enum argument '{argument}' has no choices.", section.line)
|
|
399
|
+
default_entry: IniEntry | None = section.get("default")
|
|
400
|
+
default: Any
|
|
401
|
+
if default_entry is None or default_entry.is_empty:
|
|
402
|
+
if kind not in EMPTY_DEFAULT_TYPES:
|
|
403
|
+
raise self._error(f"Argument '{argument}' has no default value.", section.line)
|
|
404
|
+
default = spec.coerce("", self.path.parent)
|
|
405
|
+
else:
|
|
406
|
+
try:
|
|
407
|
+
default = spec.coerce(default_entry.value, self.path.parent)
|
|
408
|
+
except ValueConversionError as error:
|
|
409
|
+
raise self._error(f"Invalid default '{error.raw}' for argument '{argument}': {error.reason}.", default_entry.line) from None
|
|
410
|
+
arguments[argument] = ArgumentSpec(
|
|
411
|
+
spec.name, spec.type, default, spec.minimum, spec.maximum, spec.choices, spec.item_type, spec.description,
|
|
412
|
+
)
|
|
413
|
+
return arguments
|
|
414
|
+
|
|
415
|
+
def _read_selection(self, section: IniSection, primitive: Primitive, check_id: str) -> Selection:
|
|
416
|
+
"""
|
|
417
|
+
Read the `target` and `where.*` keys of a check.
|
|
418
|
+
|
|
419
|
+
Parameters
|
|
420
|
+
----------
|
|
421
|
+
section : IniSection
|
|
422
|
+
The `[check:*]` section.
|
|
423
|
+
primitive : Primitive
|
|
424
|
+
Its primitive.
|
|
425
|
+
check_id : str
|
|
426
|
+
Check identifier.
|
|
427
|
+
|
|
428
|
+
Returns
|
|
429
|
+
----------
|
|
430
|
+
Selection
|
|
431
|
+
The selection.
|
|
432
|
+
|
|
433
|
+
Raises
|
|
434
|
+
----------
|
|
435
|
+
RuleDefinitionError
|
|
436
|
+
A key is not supported by the primitive or has an invalid value.
|
|
437
|
+
"""
|
|
438
|
+
target: str | None = section.text("target")
|
|
439
|
+
if target is not None and target not in primitive.targets:
|
|
440
|
+
hint: str = f"Expected one of: {', '.join(primitive.targets)}." if primitive.targets else f"{primitive.kind} takes no target."
|
|
441
|
+
raise self._error(f"Invalid target '{target}' for check '{check_id}'.", section.entries["target"].line, hint)
|
|
442
|
+
values: dict[str, Any] = {}
|
|
443
|
+
for key, entry in section.entries.items():
|
|
444
|
+
if not key.startswith(WHERE_PREFIX) or entry.is_empty:
|
|
445
|
+
continue
|
|
446
|
+
where: str = key[len(WHERE_PREFIX):]
|
|
447
|
+
if where not in WHERE_KEYS:
|
|
448
|
+
raise self._error(f"Unknown key '{key}' in [{section.name}].", entry.line, _suggest(where, WHERE_KEYS))
|
|
449
|
+
if where != "file_kind" and where not in primitive.where_keys:
|
|
450
|
+
raise self._error(f"'{key}' is not supported by {primitive.kind}.", entry.line)
|
|
451
|
+
try:
|
|
452
|
+
match where:
|
|
453
|
+
case "file_kind":
|
|
454
|
+
values["file_kinds"] = self._file_kinds(section, key)
|
|
455
|
+
case "context" | "not_context":
|
|
456
|
+
values["contexts" if where == "context" else "not_contexts"] = frozenset(CodeContext(item) for item in self._list(section, key))
|
|
457
|
+
case "node":
|
|
458
|
+
values["nodes"] = frozenset(NodeKind(item) for item in self._list(section, key))
|
|
459
|
+
case "name":
|
|
460
|
+
values["name"] = re.compile(entry.value)
|
|
461
|
+
case "storage":
|
|
462
|
+
values["storage"] = StorageFilter(entry.value)
|
|
463
|
+
except (ValueError, re.error) as error:
|
|
464
|
+
raise self._error(f"Invalid value for '{key}': {error}.", entry.line) from None
|
|
465
|
+
return Selection(target=target, **values)
|
|
466
|
+
|
|
467
|
+
def _read_parameters(self, section: IniSection, primitive: Primitive, arguments: Mapping[str, ArgumentSpec]) -> dict[str, ParameterValue]:
|
|
468
|
+
"""
|
|
469
|
+
Read the primitive-specific keys of a check, coercing literals and checking `@argument` references.
|
|
470
|
+
|
|
471
|
+
Parameters
|
|
472
|
+
----------
|
|
473
|
+
section : IniSection
|
|
474
|
+
The `[check:*]` section.
|
|
475
|
+
primitive : Primitive
|
|
476
|
+
Its primitive.
|
|
477
|
+
arguments : Mapping[str, ArgumentSpec]
|
|
478
|
+
Arguments of the rule.
|
|
479
|
+
|
|
480
|
+
Returns
|
|
481
|
+
----------
|
|
482
|
+
dict[str, ParameterValue]
|
|
483
|
+
Parameters by key.
|
|
484
|
+
|
|
485
|
+
Raises
|
|
486
|
+
----------
|
|
487
|
+
RuleDefinitionError
|
|
488
|
+
A key is unknown, a value is invalid, a reference is unknown or of an incompatible type, or a
|
|
489
|
+
required parameter is missing.
|
|
490
|
+
"""
|
|
491
|
+
parameters: dict[str, ParameterValue] = {}
|
|
492
|
+
known: set[str] = {spec.name for spec in primitive.parameters}
|
|
493
|
+
for key, entry in section.entries.items():
|
|
494
|
+
if key in CHECK_GENERIC_KEYS or key.startswith(WHERE_PREFIX):
|
|
495
|
+
continue
|
|
496
|
+
spec: ArgumentSpec | None = primitive.parameter(key)
|
|
497
|
+
if spec is None:
|
|
498
|
+
raise self._error(f"Unknown key '{key}' for {primitive.kind} in [{section.name}].", entry.line, _suggest(key, known | CHECK_GENERIC_KEYS))
|
|
499
|
+
if entry.is_empty:
|
|
500
|
+
continue
|
|
501
|
+
raw: str = entry.value
|
|
502
|
+
if raw.startswith(REFERENCE_PREFIX):
|
|
503
|
+
reference: str = raw[len(REFERENCE_PREFIX):]
|
|
504
|
+
if reference not in arguments:
|
|
505
|
+
raise self._error(f"'{raw}' references an unknown argument.", entry.line, _suggest(reference, arguments))
|
|
506
|
+
if not types_compatible(spec, arguments[reference]):
|
|
507
|
+
raise self._error(
|
|
508
|
+
f"Argument '{reference}' ({arguments[reference].type}) cannot feed '{key}' ({spec.type}).", entry.line,
|
|
509
|
+
)
|
|
510
|
+
parameters[key] = ParameterValue(key, raw, entry.line, reference, None)
|
|
511
|
+
continue
|
|
512
|
+
try:
|
|
513
|
+
value: Any = spec.coerce(raw, self.path.parent)
|
|
514
|
+
except ValueConversionError as error:
|
|
515
|
+
raise self._error(f"Invalid value '{error.raw}' for '{key}': {error.reason}.", entry.line) from None
|
|
516
|
+
parameters[key] = ParameterValue(key, raw, entry.line, None, value)
|
|
517
|
+
for spec in primitive.parameters:
|
|
518
|
+
if spec.required and spec.name not in parameters:
|
|
519
|
+
raise self._error(f"{primitive.kind} requires '{spec.name}' in [{section.name}].", section.line)
|
|
520
|
+
return parameters
|
|
521
|
+
|
|
522
|
+
def _check_message(self, message: str, primitive: Primitive, arguments: Mapping[str, ArgumentSpec], line: int) -> None:
|
|
523
|
+
"""
|
|
524
|
+
Reject message templates with unknown placeholders.
|
|
525
|
+
|
|
526
|
+
Parameters
|
|
527
|
+
----------
|
|
528
|
+
message : str
|
|
529
|
+
The template.
|
|
530
|
+
primitive : Primitive
|
|
531
|
+
The primitive of the check.
|
|
532
|
+
arguments : Mapping[str, ArgumentSpec]
|
|
533
|
+
Arguments of the rule.
|
|
534
|
+
line : int
|
|
535
|
+
Line of the message.
|
|
536
|
+
|
|
537
|
+
Returns
|
|
538
|
+
----------
|
|
539
|
+
None
|
|
540
|
+
Nothing.
|
|
541
|
+
|
|
542
|
+
Raises
|
|
543
|
+
----------
|
|
544
|
+
RuleDefinitionError
|
|
545
|
+
The template is malformed or uses an unknown placeholder.
|
|
546
|
+
"""
|
|
547
|
+
allowed: set[str] = set(STANDARD_PLACEHOLDERS) | set(primitive.data_keys) | set(arguments)
|
|
548
|
+
try:
|
|
549
|
+
fields: list[str | None] = [name for _, name, _, _ in string.Formatter().parse(message)]
|
|
550
|
+
except ValueError as error:
|
|
551
|
+
raise self._error(f"Malformed message template: {error}.", line, "Write literal braces as {{ and }}.") from None
|
|
552
|
+
for name in fields:
|
|
553
|
+
if name is not None and name.split(".")[0].split("[")[0] not in allowed:
|
|
554
|
+
raise self._error(f"Unknown placeholder '{{{name}}}' in message.", line, _suggest(name, allowed))
|
|
555
|
+
|
|
556
|
+
def _read_checks(self, rule: IniSection, arguments: Mapping[str, ArgumentSpec], rule_detection: Detection) -> list[CheckDefinition]:
|
|
557
|
+
"""
|
|
558
|
+
Read every `[check:<id>]` section.
|
|
559
|
+
|
|
560
|
+
Parameters
|
|
561
|
+
----------
|
|
562
|
+
rule : IniSection
|
|
563
|
+
The `[rule]` section.
|
|
564
|
+
arguments : Mapping[str, ArgumentSpec]
|
|
565
|
+
Arguments of the rule.
|
|
566
|
+
rule_detection : Detection
|
|
567
|
+
Default detection level of the rule.
|
|
568
|
+
|
|
569
|
+
Returns
|
|
570
|
+
----------
|
|
571
|
+
list[CheckDefinition]
|
|
572
|
+
The checks, in file order.
|
|
573
|
+
|
|
574
|
+
Raises
|
|
575
|
+
----------
|
|
576
|
+
RuleDefinitionError
|
|
577
|
+
A check is invalid.
|
|
578
|
+
"""
|
|
579
|
+
checks: list[CheckDefinition] = []
|
|
580
|
+
for name, section in self.document.sections.items():
|
|
581
|
+
if not name.startswith("check:"):
|
|
582
|
+
continue
|
|
583
|
+
check_id: str = name[len("check:"):]
|
|
584
|
+
if not IDENTIFIER_PATTERN.fullmatch(check_id):
|
|
585
|
+
raise self._error(f"Invalid check ID '{check_id}'.", section.line, "Use snake_case.")
|
|
586
|
+
kind: str | None = section.text("kind")
|
|
587
|
+
if kind is None:
|
|
588
|
+
raise self._error(f"Check '{check_id}' has no kind.", section.line)
|
|
589
|
+
if kind in RESERVED_KINDS:
|
|
590
|
+
raise self._error(f"kind = {kind} is not supported yet.", section.entries["kind"].line, "Use a primitive of the catalogue.")
|
|
591
|
+
if kind not in PRIMITIVES:
|
|
592
|
+
raise self._error(f"Unknown primitive '{kind}'.", section.entries["kind"].line, f"Available: {', '.join(sorted(PRIMITIVES))}.")
|
|
593
|
+
if section.text("entry") is not None:
|
|
594
|
+
raise self._error("'entry' is only used by kind = python or plugin.", section.entries["entry"].line)
|
|
595
|
+
primitive: Primitive = PRIMITIVES[kind]
|
|
596
|
+
detection: Detection | None = self._enum(section, "detection", Detection, None)
|
|
597
|
+
if (detection or rule_detection) is Detection.MANUAL and kind != "manual_review":
|
|
598
|
+
raise self._error(f"Check '{check_id}' is manual but its kind is '{kind}'.", section.line, "Manual checks use kind = manual_review.")
|
|
599
|
+
message: str = section.text("message") or ""
|
|
600
|
+
if message:
|
|
601
|
+
self._check_message(message, primitive, arguments, section.entries["message"].line)
|
|
602
|
+
fix: FixApplicability = self._enum(section, "fix", FixApplicability, FixApplicability.NONE) # type: ignore[assignment]
|
|
603
|
+
fix_kind: str | None = section.text("fix.kind")
|
|
604
|
+
if fix is not FixApplicability.NONE and fix_kind is None:
|
|
605
|
+
raise self._error(f"Check '{check_id}' has fix = {fix} but no fix.kind.", section.line)
|
|
606
|
+
if fix_kind is not None and fix_kind not in FIX_KINDS:
|
|
607
|
+
close: list[str] = difflib.get_close_matches(fix_kind, sorted(FIX_KINDS), n=1)
|
|
608
|
+
hint: str = f"Did you mean '{close[0]}'?" if close else "Known fix kinds: " + ", ".join(sorted(FIX_KINDS)) + "."
|
|
609
|
+
raise self._error(f"Check '{check_id}' has an unknown fix.kind '{fix_kind}'.", section.entries["fix.kind"].line, hint)
|
|
610
|
+
check: CheckDefinition = CheckDefinition(
|
|
611
|
+
id=check_id,
|
|
612
|
+
kind=kind,
|
|
613
|
+
description=section.text("description") or "",
|
|
614
|
+
severity=self._enum(section, "severity", SeverityLevel, None),
|
|
615
|
+
detection=detection,
|
|
616
|
+
applies_to=self._file_kinds(section, "applies_to"),
|
|
617
|
+
selection=self._read_selection(section, primitive, check_id),
|
|
618
|
+
parameters=MappingProxyType(self._read_parameters(section, primitive, arguments)),
|
|
619
|
+
report=self._enum(section, "report", ReportMode, ReportMode.EACH), # type: ignore[arg-type]
|
|
620
|
+
message=message,
|
|
621
|
+
fix=fix,
|
|
622
|
+
fix_kind=fix_kind,
|
|
623
|
+
line=section.line,
|
|
624
|
+
)
|
|
625
|
+
try:
|
|
626
|
+
bind_parameters(primitive, check, {name: spec.default for name, spec in arguments.items()})
|
|
627
|
+
except ValueError as error:
|
|
628
|
+
raise self._error(f"Invalid check '{check_id}': {error}.", section.line) from None
|
|
629
|
+
checks.append(check)
|
|
630
|
+
if not checks:
|
|
631
|
+
raise self._error("A rule needs at least one [check:<id>] section.", rule.line)
|
|
632
|
+
return checks
|
|
633
|
+
|
|
634
|
+
def _read_expect(self, section: IniSection, check_ids: set[str], single_file: str | None) -> tuple[ExpectedFinding, ...]:
|
|
635
|
+
"""
|
|
636
|
+
Read the `expect` list of an example.
|
|
637
|
+
|
|
638
|
+
Parameters
|
|
639
|
+
----------
|
|
640
|
+
section : IniSection
|
|
641
|
+
The `[example:*]` section.
|
|
642
|
+
check_ids : set[str]
|
|
643
|
+
Checks of the rule.
|
|
644
|
+
single_file : str | None
|
|
645
|
+
Path of the only file of the example (lets entries omit the path).
|
|
646
|
+
|
|
647
|
+
Returns
|
|
648
|
+
----------
|
|
649
|
+
tuple[ExpectedFinding, ...]
|
|
650
|
+
The expected findings.
|
|
651
|
+
|
|
652
|
+
Raises
|
|
653
|
+
----------
|
|
654
|
+
RuleDefinitionError
|
|
655
|
+
An entry is malformed or names an unknown check.
|
|
656
|
+
"""
|
|
657
|
+
entry: IniEntry | None = section.get("expect")
|
|
658
|
+
if entry is None or entry.is_empty:
|
|
659
|
+
return ()
|
|
660
|
+
expected: list[ExpectedFinding] = []
|
|
661
|
+
for item in (part.strip() for part in entry.value.split("\n") if part.strip()):
|
|
662
|
+
parts: list[str] = item.rsplit(":", 3)
|
|
663
|
+
if len(parts) == 3 and single_file is not None:
|
|
664
|
+
parts.insert(0, single_file)
|
|
665
|
+
if len(parts) != 4 or not parts[1].isdigit() or not parts[2].isdigit():
|
|
666
|
+
raise self._error(f"Invalid expect entry '{item}'.", entry.line, "Expected '<path>:<line>:<column>:<check_id>' (path optional with a single file).")
|
|
667
|
+
if parts[3] not in check_ids:
|
|
668
|
+
raise self._error(f"Expect entry '{item}' names an unknown check.", entry.line, _suggest(parts[3], check_ids))
|
|
669
|
+
expected.append(ExpectedFinding(parts[0], int(parts[1]), int(parts[2]), parts[3]))
|
|
670
|
+
return tuple(expected)
|
|
671
|
+
|
|
672
|
+
def _read_example_file(self, section: IniSection, file_path: str) -> ExampleFile:
|
|
673
|
+
"""
|
|
674
|
+
Read one `[example:<id>:file:<path>]` section.
|
|
675
|
+
|
|
676
|
+
Parameters
|
|
677
|
+
----------
|
|
678
|
+
section : IniSection
|
|
679
|
+
The section.
|
|
680
|
+
file_path : str
|
|
681
|
+
Path of the file inside the example project.
|
|
682
|
+
|
|
683
|
+
Returns
|
|
684
|
+
----------
|
|
685
|
+
ExampleFile
|
|
686
|
+
The file.
|
|
687
|
+
|
|
688
|
+
Raises
|
|
689
|
+
----------
|
|
690
|
+
RuleDefinitionError
|
|
691
|
+
The section has no content, both contents, or an unreadable fixture.
|
|
692
|
+
"""
|
|
693
|
+
self._check_keys(section, EXAMPLE_FILE_KEYS)
|
|
694
|
+
if PurePosixPath(file_path).is_absolute() or ".." in PurePosixPath(file_path).parts:
|
|
695
|
+
raise self._error(f"Example file path '{file_path}' must be relative and stay inside the example.", section.line)
|
|
696
|
+
code: IniEntry | None = section.get("code")
|
|
697
|
+
fixture: str | None = section.text("fixture")
|
|
698
|
+
has_code: bool = code is not None and not code.is_empty
|
|
699
|
+
if has_code == (fixture is not None):
|
|
700
|
+
raise self._error(f"[{section.name}] needs exactly one of 'code' and 'fixture'.", section.line)
|
|
701
|
+
if fixture is not None:
|
|
702
|
+
try:
|
|
703
|
+
return ExampleFile(file_path, (self.path.parent / fixture).read_bytes())
|
|
704
|
+
except OSError as error:
|
|
705
|
+
raise self._error(f"Cannot read fixture '{fixture}': {error.strerror}.", section.entries["fixture"].line) from None
|
|
706
|
+
assert code is not None
|
|
707
|
+
if not code.is_code:
|
|
708
|
+
raise self._error("Example code lines must start with '|'.", code.line)
|
|
709
|
+
text: str = code.value
|
|
710
|
+
if self._bool(section, "final_newline", True):
|
|
711
|
+
text += "\n"
|
|
712
|
+
return ExampleFile(file_path, text.encode("utf-8"))
|
|
713
|
+
|
|
714
|
+
def _read_examples(self, check_ids: set[str]) -> list[ExampleDefinition]:
|
|
715
|
+
"""
|
|
716
|
+
Read every `[example:<id>]` with its files.
|
|
717
|
+
|
|
718
|
+
Parameters
|
|
719
|
+
----------
|
|
720
|
+
check_ids : set[str]
|
|
721
|
+
Checks of the rule.
|
|
722
|
+
|
|
723
|
+
Returns
|
|
724
|
+
----------
|
|
725
|
+
list[ExampleDefinition]
|
|
726
|
+
The examples, in file order.
|
|
727
|
+
|
|
728
|
+
Raises
|
|
729
|
+
----------
|
|
730
|
+
RuleDefinitionError
|
|
731
|
+
An example is invalid.
|
|
732
|
+
"""
|
|
733
|
+
files: dict[str, list[ExampleFile]] = {}
|
|
734
|
+
headers: dict[str, IniSection] = {}
|
|
735
|
+
for name, section in self.document.sections.items():
|
|
736
|
+
if not name.startswith("example:"):
|
|
737
|
+
continue
|
|
738
|
+
parts: list[str] = name.split(":", 3)
|
|
739
|
+
if len(parts) == 2:
|
|
740
|
+
if not IDENTIFIER_PATTERN.fullmatch(parts[1]):
|
|
741
|
+
raise self._error(f"Invalid example ID '{parts[1]}'.", section.line, "Use snake_case.")
|
|
742
|
+
headers[parts[1]] = section
|
|
743
|
+
elif len(parts) == 4 and parts[2] == "file" and parts[3]:
|
|
744
|
+
files.setdefault(parts[1], []).append(self._read_example_file(section, parts[3]))
|
|
745
|
+
else:
|
|
746
|
+
raise self._error(f"Invalid section [{name}].", section.line, "Expected [example:<id>] or [example:<id>:file:<path>].")
|
|
747
|
+
for example_id in files:
|
|
748
|
+
if example_id not in headers:
|
|
749
|
+
raise self._error(f"Files given for example '{example_id}' without an [example:{example_id}] section.", None)
|
|
750
|
+
examples: list[ExampleDefinition] = []
|
|
751
|
+
for example_id, section in headers.items():
|
|
752
|
+
self._check_keys(section, EXAMPLE_KEYS)
|
|
753
|
+
kind: ExampleKind | None = self._enum(section, "kind", ExampleKind, None)
|
|
754
|
+
if kind is None:
|
|
755
|
+
raise self._error(f"Example '{example_id}' has no kind (good or bad).", section.line)
|
|
756
|
+
example_files: list[ExampleFile] = files.get(example_id, [])
|
|
757
|
+
if not example_files:
|
|
758
|
+
raise self._error(f"Example '{example_id}' has no [example:{example_id}:file:<path>] section.", section.line)
|
|
759
|
+
single: str | None = example_files[0].path if len(example_files) == 1 else None
|
|
760
|
+
expect: tuple[ExpectedFinding, ...] = self._read_expect(section, check_ids, single)
|
|
761
|
+
if kind is ExampleKind.BAD and not expect:
|
|
762
|
+
raise self._error(f"Bad example '{example_id}' expects no finding.", section.line)
|
|
763
|
+
examples.append(ExampleDefinition(example_id, kind, section.text("description") or "", expect, tuple(example_files)))
|
|
764
|
+
return examples
|
|
765
|
+
|
|
766
|
+
def read(self, category: str, name: str, builtin: bool) -> RuleDefinition:
|
|
767
|
+
"""
|
|
768
|
+
Validate the whole file and build the rule.
|
|
769
|
+
|
|
770
|
+
Parameters
|
|
771
|
+
----------
|
|
772
|
+
category : str
|
|
773
|
+
Category expected from the file location.
|
|
774
|
+
name : str
|
|
775
|
+
Rule name expected from the file location.
|
|
776
|
+
builtin : bool
|
|
777
|
+
Whether the rule ships with JCCS.
|
|
778
|
+
|
|
779
|
+
Returns
|
|
780
|
+
----------
|
|
781
|
+
RuleDefinition
|
|
782
|
+
The rule.
|
|
783
|
+
|
|
784
|
+
Raises
|
|
785
|
+
----------
|
|
786
|
+
RuleDefinitionError
|
|
787
|
+
The content is not a valid rule.
|
|
788
|
+
"""
|
|
789
|
+
for section_name, section in self.document.sections.items():
|
|
790
|
+
if section_name not in ("rule", "epitech") and not section_name.startswith(("argument:", "check:", "example:")):
|
|
791
|
+
raise self._error(f"Unknown section [{section_name}].", section.line)
|
|
792
|
+
rule: IniSection | None = self.document.sections.get("rule")
|
|
793
|
+
if rule is None:
|
|
794
|
+
raise self._error("Missing [rule] section.", None)
|
|
795
|
+
self._check_keys(rule, RULE_KEYS)
|
|
796
|
+
schema: str | None = rule.text("schema")
|
|
797
|
+
if schema != RULE_SCHEMA_VERSION:
|
|
798
|
+
raise self._error(f"Unsupported schema '{schema}'.", rule.entries["schema"].line if "schema" in rule.entries else rule.line, f"This JCCS reads schema {RULE_SCHEMA_VERSION}.")
|
|
799
|
+
rule_id: str | None = rule.text("id")
|
|
800
|
+
if rule_id != f"{category}/{name}":
|
|
801
|
+
raise self._error(f"Rule id '{rule_id}' does not match its location '{category}/{name}'.", rule.entries["id"].line if "id" in rule.entries else rule.line)
|
|
802
|
+
severity: SeverityLevel | None = self._enum(rule, "severity", SeverityLevel, None)
|
|
803
|
+
if severity is None:
|
|
804
|
+
raise self._error("The rule has no severity.", rule.line, "Expected one of: info, minor, major, fatal.")
|
|
805
|
+
detection: Detection = self._enum(rule, "detection", Detection, Detection.AUTOMATIC) # type: ignore[assignment]
|
|
806
|
+
status: RuleStatus = self._enum(rule, "status", RuleStatus, RuleStatus.PREVIEW) # type: ignore[assignment]
|
|
807
|
+
epitech: EpitechInfo = EpitechInfo()
|
|
808
|
+
epitech_section: IniSection | None = self.document.sections.get("epitech")
|
|
809
|
+
if epitech_section is not None:
|
|
810
|
+
self._check_keys(epitech_section, EPITECH_KEYS)
|
|
811
|
+
version_text: str | None = epitech_section.text("version")
|
|
812
|
+
if version_text is not None and not version_text.isdigit():
|
|
813
|
+
raise self._error(f"Invalid Epitech version '{version_text}'.", epitech_section.entries["version"].line)
|
|
814
|
+
epitech = EpitechInfo(
|
|
815
|
+
ref=epitech_section.text("ref"),
|
|
816
|
+
version=int(version_text) if version_text is not None else None,
|
|
817
|
+
banana=self._enum(epitech_section, "banana", BananaSupport, None),
|
|
818
|
+
manual_part=epitech_section.text("manual_part") or "",
|
|
819
|
+
)
|
|
820
|
+
arguments: dict[str, ArgumentSpec] = self._read_arguments()
|
|
821
|
+
checks: list[CheckDefinition] = self._read_checks(rule, arguments, detection)
|
|
822
|
+
examples: list[ExampleDefinition] = self._read_examples({check.id for check in checks})
|
|
823
|
+
if status is RuleStatus.STABLE:
|
|
824
|
+
kinds: set[ExampleKind] = {example.kind for example in examples}
|
|
825
|
+
if kinds != {ExampleKind.GOOD, ExampleKind.BAD}:
|
|
826
|
+
raise self._error("A stable rule needs at least one good and one bad example.", rule.line)
|
|
827
|
+
return RuleDefinition(
|
|
828
|
+
id=rule_id,
|
|
829
|
+
category=category,
|
|
830
|
+
name=name,
|
|
831
|
+
source=self.display,
|
|
832
|
+
builtin=builtin,
|
|
833
|
+
code=rule.text("code") or epitech.ref or rule_id,
|
|
834
|
+
title=rule.text("title") or name.replace("_", " ").capitalize(),
|
|
835
|
+
summary=rule.text("summary") or "",
|
|
836
|
+
rationale=rule.text("rationale") or "",
|
|
837
|
+
applies_to=self._file_kinds(rule, "applies_to") or frozenset({FileKind.C, FileKind.H}),
|
|
838
|
+
severity=severity,
|
|
839
|
+
detection=detection,
|
|
840
|
+
status=status,
|
|
841
|
+
since=rule.text("since") or "",
|
|
842
|
+
deprecated_by=rule.text("deprecated_by") or "",
|
|
843
|
+
aliases=self._list(rule, "aliases"),
|
|
844
|
+
tags=self._list(rule, "tags"),
|
|
845
|
+
docs_url=rule.text("docs_url") or "",
|
|
846
|
+
suppressible=self._bool(rule, "suppressible", True) and severity is not SeverityLevel.FATAL,
|
|
847
|
+
requires_jccs=rule.text("requires_jccs") or "",
|
|
848
|
+
supersedes=self._list(rule, "supersedes"),
|
|
849
|
+
conflicts_with=self._list(rule, "conflicts_with"),
|
|
850
|
+
epitech=epitech,
|
|
851
|
+
arguments=MappingProxyType(arguments),
|
|
852
|
+
checks=tuple(checks),
|
|
853
|
+
examples=tuple(examples),
|
|
854
|
+
)
|
|
855
|
+
|
|
856
|
+
|
|
857
|
+
def load_rule_file(path: Path, categories_root: Path, *, builtin: bool) -> RuleDefinition:
|
|
858
|
+
"""
|
|
859
|
+
Load one rule file located at `<categories_root>/<category>/<name>.ini`.
|
|
860
|
+
|
|
861
|
+
Parameters
|
|
862
|
+
----------
|
|
863
|
+
path : Path
|
|
864
|
+
The rule file.
|
|
865
|
+
categories_root : Path
|
|
866
|
+
Directory holding the category directories.
|
|
867
|
+
builtin : bool
|
|
868
|
+
Whether the rule ships with JCCS.
|
|
869
|
+
|
|
870
|
+
Returns
|
|
871
|
+
----------
|
|
872
|
+
RuleDefinition
|
|
873
|
+
The rule.
|
|
874
|
+
|
|
875
|
+
Raises
|
|
876
|
+
----------
|
|
877
|
+
RuleDefinitionError
|
|
878
|
+
The file is misplaced, unreadable or invalid.
|
|
879
|
+
IniSyntaxError
|
|
880
|
+
The file breaks the INI dialect.
|
|
881
|
+
"""
|
|
882
|
+
relative: PurePosixPath = PurePosixPath(path.relative_to(categories_root).as_posix())
|
|
883
|
+
display: str = str(path)
|
|
884
|
+
if len(relative.parts) != 2 or relative.suffix != ".ini":
|
|
885
|
+
raise RuleDefinitionError("Rule files must be stored as <category>/<name>.ini.", path=display)
|
|
886
|
+
category, name = relative.parts[0], relative.stem
|
|
887
|
+
for part in (category, name):
|
|
888
|
+
if not IDENTIFIER_PATTERN.fullmatch(part):
|
|
889
|
+
raise RuleDefinitionError(f"Invalid category or rule name '{part}'.", "Use snake_case.", path=display)
|
|
890
|
+
try:
|
|
891
|
+
text: str = path.read_text(encoding="utf-8")
|
|
892
|
+
except (OSError, UnicodeDecodeError) as error:
|
|
893
|
+
raise RuleDefinitionError(f"Cannot read the rule file: {error}.", path=display) from None
|
|
894
|
+
return RuleFileReader(path, text, display).read(category, name, builtin)
|
|
895
|
+
|
|
896
|
+
|
|
897
|
+
def load_rule_text(text: str, category: str, name: str, *, base_directory: Path | None = None) -> RuleDefinition:
|
|
898
|
+
"""
|
|
899
|
+
Load a rule from text (used by tests and by `rule --validate` on unsaved content).
|
|
900
|
+
|
|
901
|
+
Parameters
|
|
902
|
+
----------
|
|
903
|
+
text : str
|
|
904
|
+
Content of the rule file.
|
|
905
|
+
category : str
|
|
906
|
+
Category of the rule.
|
|
907
|
+
name : str
|
|
908
|
+
Name of the rule.
|
|
909
|
+
base_directory : Path | None
|
|
910
|
+
Directory used to resolve fixtures and word files.
|
|
911
|
+
|
|
912
|
+
Returns
|
|
913
|
+
----------
|
|
914
|
+
RuleDefinition
|
|
915
|
+
The rule.
|
|
916
|
+
|
|
917
|
+
Raises
|
|
918
|
+
----------
|
|
919
|
+
RuleDefinitionError
|
|
920
|
+
The content is not a valid rule.
|
|
921
|
+
IniSyntaxError
|
|
922
|
+
The text breaks the INI dialect.
|
|
923
|
+
"""
|
|
924
|
+
path: Path = (base_directory or Path(".")) / category / f"{name}.ini"
|
|
925
|
+
return RuleFileReader(path, text, f"{category}/{name}.ini").read(category, name, builtin=False)
|