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
|
@@ -0,0 +1,1067 @@
|
|
|
1
|
+
import difflib
|
|
2
|
+
import json
|
|
3
|
+
import shutil
|
|
4
|
+
from dataclasses import dataclass
|
|
5
|
+
from pathlib import Path
|
|
6
|
+
from typing import Any
|
|
7
|
+
|
|
8
|
+
from sources.cli.context import CommandArguments, ParsedArguments
|
|
9
|
+
from sources.configs.editor import IniEditor
|
|
10
|
+
from sources.configs.ini import IniDocument, parse_ini
|
|
11
|
+
from sources.configs.project import (
|
|
12
|
+
CONFIG_FILE_NAME,
|
|
13
|
+
ProjectConfig,
|
|
14
|
+
RuleSettings,
|
|
15
|
+
ensure_project_directory,
|
|
16
|
+
find_project_root,
|
|
17
|
+
load_project_config,
|
|
18
|
+
)
|
|
19
|
+
from sources.configs.schema.project import CHECK_SETTING_KEYS, RULE_SETTING_KEYS
|
|
20
|
+
from sources.engine.examples import ExampleResult, run_rule_examples
|
|
21
|
+
from sources.engine.plan import build_plan
|
|
22
|
+
from sources.enums import ExitCode
|
|
23
|
+
from sources.errors.exceptions import (
|
|
24
|
+
IniSyntaxError,
|
|
25
|
+
JccsError,
|
|
26
|
+
ProjectEnvironmentError,
|
|
27
|
+
RuleDefinitionError,
|
|
28
|
+
UnknownRuleError,
|
|
29
|
+
UsageError,
|
|
30
|
+
ValueConversionError,
|
|
31
|
+
)
|
|
32
|
+
from sources.outputs.report import write_atomically
|
|
33
|
+
from sources.outputs.terminal.style import Style
|
|
34
|
+
from sources.rules.arguments import ArgumentSpec
|
|
35
|
+
from sources.rules.catalog import BUILTIN_RULES_DIRECTORY, RuleCatalog
|
|
36
|
+
from sources.rules.definition import RuleDefinition
|
|
37
|
+
from sources.rules.loader import IDENTIFIER_PATTERN, load_rule_text
|
|
38
|
+
from sources.rules.template import render_rule_skeleton
|
|
39
|
+
from sources.services import Services
|
|
40
|
+
from sources.subcommands.rule.render import (
|
|
41
|
+
RuleState,
|
|
42
|
+
argument_text,
|
|
43
|
+
render_rule_json,
|
|
44
|
+
render_rule_text,
|
|
45
|
+
render_rules_json,
|
|
46
|
+
render_rules_text,
|
|
47
|
+
)
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
# Action flags of `rule`, at most one per run; `list` is the default (plan 02, section 5).
|
|
51
|
+
ACTIONS: tuple[str, ...] = (
|
|
52
|
+
"list", "create", "show", "set", "enable", "disable", "delete", "validate", "reset", "duplicate", "export",
|
|
53
|
+
"import_rule", "search",
|
|
54
|
+
)
|
|
55
|
+
|
|
56
|
+
# Actions that accept `--category`.
|
|
57
|
+
CATEGORY_ACTIONS: frozenset[str] = frozenset({"list", "search"})
|
|
58
|
+
|
|
59
|
+
# Actions that accept `--json`.
|
|
60
|
+
JSON_ACTIONS: frozenset[str] = frozenset({"list", "show", "search", "validate"})
|
|
61
|
+
|
|
62
|
+
# Prefix of per-rule sections of the project config.
|
|
63
|
+
RULE_SECTION: str = "rule:"
|
|
64
|
+
|
|
65
|
+
|
|
66
|
+
@dataclass(frozen=True, slots=True)
|
|
67
|
+
class Workspace:
|
|
68
|
+
"""
|
|
69
|
+
The project the `rule` subcommand works on.
|
|
70
|
+
(dataclass)
|
|
71
|
+
|
|
72
|
+
Attributes
|
|
73
|
+
----------
|
|
74
|
+
root : Path
|
|
75
|
+
Project root.
|
|
76
|
+
config_file : Path
|
|
77
|
+
Project config file (`.JCCS/.jccs.ini`).
|
|
78
|
+
config : ProjectConfig
|
|
79
|
+
Loaded project config.
|
|
80
|
+
rules_directory : Path
|
|
81
|
+
Directory of the custom rules.
|
|
82
|
+
"""
|
|
83
|
+
|
|
84
|
+
root: Path
|
|
85
|
+
config_file: Path
|
|
86
|
+
config: ProjectConfig
|
|
87
|
+
rules_directory: Path
|
|
88
|
+
|
|
89
|
+
def custom_file(self, category: str, name: str) -> Path:
|
|
90
|
+
"""
|
|
91
|
+
Location of a custom rule file.
|
|
92
|
+
|
|
93
|
+
Parameters
|
|
94
|
+
----------
|
|
95
|
+
category : str
|
|
96
|
+
Category of the rule.
|
|
97
|
+
name : str
|
|
98
|
+
Name of the rule.
|
|
99
|
+
|
|
100
|
+
Returns
|
|
101
|
+
----------
|
|
102
|
+
Path
|
|
103
|
+
The file path.
|
|
104
|
+
"""
|
|
105
|
+
return self.rules_directory / category / f"{name}.ini"
|
|
106
|
+
|
|
107
|
+
|
|
108
|
+
def _open_workspace(services: Services) -> Workspace:
|
|
109
|
+
"""
|
|
110
|
+
Find the project of the working directory, create `.JCCS` when missing and load its config.
|
|
111
|
+
|
|
112
|
+
Parameters
|
|
113
|
+
----------
|
|
114
|
+
services : Services
|
|
115
|
+
Process seams.
|
|
116
|
+
|
|
117
|
+
Returns
|
|
118
|
+
----------
|
|
119
|
+
Workspace
|
|
120
|
+
The workspace.
|
|
121
|
+
|
|
122
|
+
Raises
|
|
123
|
+
----------
|
|
124
|
+
ProjectConfigError
|
|
125
|
+
The project config is invalid.
|
|
126
|
+
ProjectEnvironmentError
|
|
127
|
+
`.JCCS` cannot be created.
|
|
128
|
+
"""
|
|
129
|
+
root: Path = find_project_root(services.cwd)
|
|
130
|
+
builtin: RuleCatalog = RuleCatalog.load()
|
|
131
|
+
directory: Path = ensure_project_directory(root, builtin.rules.values())
|
|
132
|
+
config: ProjectConfig = load_project_config(directory)
|
|
133
|
+
rules_directory: Path = config.custom_rules_directory or directory / "rules"
|
|
134
|
+
return Workspace(root, directory / CONFIG_FILE_NAME, config, rules_directory)
|
|
135
|
+
|
|
136
|
+
|
|
137
|
+
def _catalog(workspace: Workspace) -> RuleCatalog:
|
|
138
|
+
"""
|
|
139
|
+
Built-in and custom rules of the project.
|
|
140
|
+
|
|
141
|
+
Parameters
|
|
142
|
+
----------
|
|
143
|
+
workspace : Workspace
|
|
144
|
+
The project.
|
|
145
|
+
|
|
146
|
+
Returns
|
|
147
|
+
----------
|
|
148
|
+
RuleCatalog
|
|
149
|
+
The catalog.
|
|
150
|
+
|
|
151
|
+
Raises
|
|
152
|
+
----------
|
|
153
|
+
RuleDefinitionError
|
|
154
|
+
A rule file is invalid.
|
|
155
|
+
IniSyntaxError
|
|
156
|
+
A rule file breaks the INI dialect.
|
|
157
|
+
"""
|
|
158
|
+
return RuleCatalog.load([workspace.rules_directory])
|
|
159
|
+
|
|
160
|
+
|
|
161
|
+
def _find(catalog: RuleCatalog, category: str, name: str) -> RuleDefinition:
|
|
162
|
+
"""
|
|
163
|
+
Rule named by a `<category> <rule>` pair.
|
|
164
|
+
|
|
165
|
+
Parameters
|
|
166
|
+
----------
|
|
167
|
+
catalog : RuleCatalog
|
|
168
|
+
Known rules.
|
|
169
|
+
category : str
|
|
170
|
+
Category.
|
|
171
|
+
name : str
|
|
172
|
+
Rule name.
|
|
173
|
+
|
|
174
|
+
Returns
|
|
175
|
+
----------
|
|
176
|
+
RuleDefinition
|
|
177
|
+
The rule.
|
|
178
|
+
|
|
179
|
+
Raises
|
|
180
|
+
----------
|
|
181
|
+
UnknownRuleError
|
|
182
|
+
No rule has this ID.
|
|
183
|
+
"""
|
|
184
|
+
rule_id: str = f"{category}/{name}"
|
|
185
|
+
rule: RuleDefinition | None = catalog.rules.get(rule_id)
|
|
186
|
+
if rule is None:
|
|
187
|
+
raise UnknownRuleError(rule_id, difflib.get_close_matches(rule_id, list(catalog.rules), n=2))
|
|
188
|
+
return rule
|
|
189
|
+
|
|
190
|
+
|
|
191
|
+
def _check_identifier(value: str, what: str) -> None:
|
|
192
|
+
"""
|
|
193
|
+
Require a snake_case category or rule name.
|
|
194
|
+
|
|
195
|
+
Parameters
|
|
196
|
+
----------
|
|
197
|
+
value : str
|
|
198
|
+
The name.
|
|
199
|
+
what : str
|
|
200
|
+
"category" or "rule name".
|
|
201
|
+
|
|
202
|
+
Returns
|
|
203
|
+
----------
|
|
204
|
+
None
|
|
205
|
+
Nothing.
|
|
206
|
+
|
|
207
|
+
Raises
|
|
208
|
+
----------
|
|
209
|
+
UsageError
|
|
210
|
+
The name is not snake_case.
|
|
211
|
+
"""
|
|
212
|
+
if not IDENTIFIER_PATTERN.fullmatch(value):
|
|
213
|
+
raise UsageError(f"Invalid {what} '{value}'.", "Use snake_case: lowercase letters, digits and underscores, starting with a letter.")
|
|
214
|
+
|
|
215
|
+
|
|
216
|
+
def _builtin_names() -> frozenset[str]:
|
|
217
|
+
"""
|
|
218
|
+
Names of the built-in rules (custom rules may not reuse them, RULE-10).
|
|
219
|
+
|
|
220
|
+
Returns
|
|
221
|
+
----------
|
|
222
|
+
frozenset[str]
|
|
223
|
+
The names.
|
|
224
|
+
"""
|
|
225
|
+
return frozenset(path.stem for path in BUILTIN_RULES_DIRECTORY.glob("*/*.ini"))
|
|
226
|
+
|
|
227
|
+
|
|
228
|
+
def _configured(config: ProjectConfig, rule: RuleDefinition) -> dict[str, str]:
|
|
229
|
+
"""
|
|
230
|
+
Raw values set for a rule in the project config, by key.
|
|
231
|
+
|
|
232
|
+
Parameters
|
|
233
|
+
----------
|
|
234
|
+
config : ProjectConfig
|
|
235
|
+
Project config.
|
|
236
|
+
rule : RuleDefinition
|
|
237
|
+
The rule.
|
|
238
|
+
|
|
239
|
+
Returns
|
|
240
|
+
----------
|
|
241
|
+
dict[str, str]
|
|
242
|
+
The values (arguments and universal keys).
|
|
243
|
+
"""
|
|
244
|
+
settings: RuleSettings | None = _settings(config, rule)
|
|
245
|
+
if settings is None:
|
|
246
|
+
return {}
|
|
247
|
+
values: dict[str, str] = dict(settings.arguments)
|
|
248
|
+
if settings.enabled is not None:
|
|
249
|
+
values["enabled"] = "true" if settings.enabled else "false"
|
|
250
|
+
if settings.severity is not None:
|
|
251
|
+
values["severity"] = settings.severity.value
|
|
252
|
+
if settings.include:
|
|
253
|
+
values["include"] = ", ".join(settings.include)
|
|
254
|
+
if settings.exclude:
|
|
255
|
+
values["exclude"] = ", ".join(settings.exclude)
|
|
256
|
+
for check_id, enabled in settings.check_enabled.items():
|
|
257
|
+
values[f"check.{check_id}.enabled"] = "true" if enabled else "false"
|
|
258
|
+
for check_id, severity in settings.check_severity.items():
|
|
259
|
+
values[f"check.{check_id}.severity"] = severity.value
|
|
260
|
+
return values
|
|
261
|
+
|
|
262
|
+
|
|
263
|
+
def _settings(config: ProjectConfig, rule: RuleDefinition) -> RuleSettings | None:
|
|
264
|
+
"""
|
|
265
|
+
`[rule:<id>]` section of a rule (written with its ID or one of its aliases).
|
|
266
|
+
|
|
267
|
+
Parameters
|
|
268
|
+
----------
|
|
269
|
+
config : ProjectConfig
|
|
270
|
+
Project config.
|
|
271
|
+
rule : RuleDefinition
|
|
272
|
+
The rule.
|
|
273
|
+
|
|
274
|
+
Returns
|
|
275
|
+
----------
|
|
276
|
+
RuleSettings | None
|
|
277
|
+
The settings, or None when the rule is not configured.
|
|
278
|
+
"""
|
|
279
|
+
for written, settings in config.rules.items():
|
|
280
|
+
if written in rule.selectors:
|
|
281
|
+
return settings
|
|
282
|
+
return None
|
|
283
|
+
|
|
284
|
+
|
|
285
|
+
def _section_name(config: ProjectConfig, rule: RuleDefinition) -> str:
|
|
286
|
+
"""
|
|
287
|
+
Name of the config section of a rule: the existing one, or `rule:<id>`.
|
|
288
|
+
|
|
289
|
+
Parameters
|
|
290
|
+
----------
|
|
291
|
+
config : ProjectConfig
|
|
292
|
+
Project config.
|
|
293
|
+
rule : RuleDefinition
|
|
294
|
+
The rule.
|
|
295
|
+
|
|
296
|
+
Returns
|
|
297
|
+
----------
|
|
298
|
+
str
|
|
299
|
+
The section name.
|
|
300
|
+
"""
|
|
301
|
+
for written in config.rules:
|
|
302
|
+
if written in rule.selectors:
|
|
303
|
+
return RULE_SECTION + written
|
|
304
|
+
return RULE_SECTION + rule.id
|
|
305
|
+
|
|
306
|
+
|
|
307
|
+
def _states(workspace: Workspace, catalog: RuleCatalog) -> list[RuleState]:
|
|
308
|
+
"""
|
|
309
|
+
Every rule with its state in the project.
|
|
310
|
+
|
|
311
|
+
Parameters
|
|
312
|
+
----------
|
|
313
|
+
workspace : Workspace
|
|
314
|
+
The project.
|
|
315
|
+
catalog : RuleCatalog
|
|
316
|
+
Known rules.
|
|
317
|
+
|
|
318
|
+
Returns
|
|
319
|
+
----------
|
|
320
|
+
list[RuleState]
|
|
321
|
+
The states, sorted by rule ID.
|
|
322
|
+
"""
|
|
323
|
+
active: set[str] = {bound.rule.id for bound in build_plan(catalog, workspace.config).rules}
|
|
324
|
+
return [RuleState(rule, rule.id in active, _configured(workspace.config, rule)) for rule in catalog.rules.values()]
|
|
325
|
+
|
|
326
|
+
|
|
327
|
+
def _edit_config(workspace: Workspace, change: Any) -> None:
|
|
328
|
+
"""
|
|
329
|
+
Apply a change to the project config with the line editor, then reload it; the file is restored when
|
|
330
|
+
the result is invalid.
|
|
331
|
+
|
|
332
|
+
Parameters
|
|
333
|
+
----------
|
|
334
|
+
workspace : Workspace
|
|
335
|
+
The project.
|
|
336
|
+
change : Any
|
|
337
|
+
Callable receiving the IniEditor.
|
|
338
|
+
|
|
339
|
+
Returns
|
|
340
|
+
----------
|
|
341
|
+
None
|
|
342
|
+
Nothing.
|
|
343
|
+
|
|
344
|
+
Raises
|
|
345
|
+
----------
|
|
346
|
+
ConfigError
|
|
347
|
+
The edited config is invalid (the file is left unchanged).
|
|
348
|
+
ProjectEnvironmentError
|
|
349
|
+
The config file cannot be read or written.
|
|
350
|
+
"""
|
|
351
|
+
try:
|
|
352
|
+
original: str = workspace.config_file.read_text(encoding="utf-8")
|
|
353
|
+
except OSError as error:
|
|
354
|
+
raise ProjectEnvironmentError(f"Cannot read '{workspace.config_file}': {error.strerror}.") from None
|
|
355
|
+
editor: IniEditor = IniEditor(original)
|
|
356
|
+
change(editor)
|
|
357
|
+
write_atomically(workspace.config_file, editor.text())
|
|
358
|
+
try:
|
|
359
|
+
load_project_config(workspace.config_file.parent)
|
|
360
|
+
except JccsError:
|
|
361
|
+
write_atomically(workspace.config_file, original)
|
|
362
|
+
raise
|
|
363
|
+
|
|
364
|
+
|
|
365
|
+
def _validate_setting(rule: RuleDefinition, key: str, value: str) -> None:
|
|
366
|
+
"""
|
|
367
|
+
Check that a key can be set for a rule and that its value is valid.
|
|
368
|
+
|
|
369
|
+
Parameters
|
|
370
|
+
----------
|
|
371
|
+
rule : RuleDefinition
|
|
372
|
+
The rule.
|
|
373
|
+
key : str
|
|
374
|
+
Argument name, universal key (enabled, severity, include, exclude) or check.<id>.<key>.
|
|
375
|
+
value : str
|
|
376
|
+
Raw value.
|
|
377
|
+
|
|
378
|
+
Returns
|
|
379
|
+
----------
|
|
380
|
+
None
|
|
381
|
+
Nothing.
|
|
382
|
+
|
|
383
|
+
Raises
|
|
384
|
+
----------
|
|
385
|
+
UsageError
|
|
386
|
+
Unknown key or invalid value.
|
|
387
|
+
"""
|
|
388
|
+
universal: dict[str, ArgumentSpec] = {spec.name: spec for spec in RULE_SETTING_KEYS}
|
|
389
|
+
spec: ArgumentSpec | None = rule.arguments.get(key) or universal.get(key)
|
|
390
|
+
if key.startswith("check."):
|
|
391
|
+
parts: list[str] = key.split(".")
|
|
392
|
+
check_specs: dict[str, ArgumentSpec] = {item.name: item for item in CHECK_SETTING_KEYS}
|
|
393
|
+
if len(parts) != 3 or parts[1] not in {check.id for check in rule.checks} or parts[2] not in check_specs:
|
|
394
|
+
checks: str = ", ".join(check.id for check in rule.checks)
|
|
395
|
+
raise UsageError(f"Invalid key '{key}' for rule '{rule.id}'.", f"Expected check.<check_id>.enabled or check.<check_id>.severity; checks: {checks}.")
|
|
396
|
+
spec = check_specs[parts[2]]
|
|
397
|
+
if spec is None:
|
|
398
|
+
known: list[str] = [*rule.arguments, *universal]
|
|
399
|
+
matches: list[str] = difflib.get_close_matches(key, known, n=1)
|
|
400
|
+
raise UsageError(f"Rule '{rule.id}' has no argument '{key}'.", f"Did you mean '{matches[0]}'?" if matches else f"Arguments: {', '.join(rule.arguments) or 'none'}.")
|
|
401
|
+
try:
|
|
402
|
+
spec.coerce(value)
|
|
403
|
+
except ValueConversionError as error:
|
|
404
|
+
raise UsageError(f"Invalid value '{error.raw}' for '{key}' of rule '{rule.id}': {error.reason}.") from None
|
|
405
|
+
|
|
406
|
+
|
|
407
|
+
def _fixture_paths(text: str, display: str) -> list[str]:
|
|
408
|
+
"""
|
|
409
|
+
Fixture files referenced by a rule file.
|
|
410
|
+
|
|
411
|
+
Parameters
|
|
412
|
+
----------
|
|
413
|
+
text : str
|
|
414
|
+
Rule file content.
|
|
415
|
+
display : str
|
|
416
|
+
File name for error messages.
|
|
417
|
+
|
|
418
|
+
Returns
|
|
419
|
+
----------
|
|
420
|
+
list[str]
|
|
421
|
+
Relative fixture paths.
|
|
422
|
+
|
|
423
|
+
Raises
|
|
424
|
+
----------
|
|
425
|
+
IniSyntaxError
|
|
426
|
+
The text breaks the INI dialect.
|
|
427
|
+
"""
|
|
428
|
+
document: IniDocument = parse_ini(text, display)
|
|
429
|
+
return [section.text("fixture") for section in document.sections.values() if section.text("fixture")] # type: ignore[misc]
|
|
430
|
+
|
|
431
|
+
|
|
432
|
+
def _install_rule(text: str, source_directory: Path, target: Path) -> None:
|
|
433
|
+
"""
|
|
434
|
+
Write a custom rule file and copy the fixtures it references.
|
|
435
|
+
|
|
436
|
+
Parameters
|
|
437
|
+
----------
|
|
438
|
+
text : str
|
|
439
|
+
Rule file content.
|
|
440
|
+
source_directory : Path
|
|
441
|
+
Directory the fixtures are read from.
|
|
442
|
+
target : Path
|
|
443
|
+
Destination rule file.
|
|
444
|
+
|
|
445
|
+
Returns
|
|
446
|
+
----------
|
|
447
|
+
None
|
|
448
|
+
Nothing.
|
|
449
|
+
|
|
450
|
+
Raises
|
|
451
|
+
----------
|
|
452
|
+
ProjectEnvironmentError
|
|
453
|
+
A file cannot be read or written.
|
|
454
|
+
"""
|
|
455
|
+
write_atomically(target, text)
|
|
456
|
+
for fixture in _fixture_paths(text, str(target)):
|
|
457
|
+
source: Path = source_directory / fixture
|
|
458
|
+
destination: Path = target.parent / fixture
|
|
459
|
+
if source.resolve() == destination.resolve():
|
|
460
|
+
continue
|
|
461
|
+
try:
|
|
462
|
+
destination.parent.mkdir(parents=True, exist_ok=True)
|
|
463
|
+
shutil.copyfile(source, destination)
|
|
464
|
+
except OSError as error:
|
|
465
|
+
raise ProjectEnvironmentError(f"Cannot copy fixture '{source}': {error.strerror}.") from None
|
|
466
|
+
|
|
467
|
+
|
|
468
|
+
def _require_new(path: Path) -> None:
|
|
469
|
+
"""
|
|
470
|
+
Refuse to overwrite an existing file (exit 4, plan 02 section 5).
|
|
471
|
+
|
|
472
|
+
Parameters
|
|
473
|
+
----------
|
|
474
|
+
path : Path
|
|
475
|
+
Destination.
|
|
476
|
+
|
|
477
|
+
Returns
|
|
478
|
+
----------
|
|
479
|
+
None
|
|
480
|
+
Nothing.
|
|
481
|
+
|
|
482
|
+
Raises
|
|
483
|
+
----------
|
|
484
|
+
ProjectEnvironmentError
|
|
485
|
+
The file exists.
|
|
486
|
+
"""
|
|
487
|
+
if path.exists():
|
|
488
|
+
raise ProjectEnvironmentError(f"'{path}' already exists.", "Delete it first, or choose another name.")
|
|
489
|
+
|
|
490
|
+
|
|
491
|
+
def _read_rule_file(path: Path) -> tuple[str, str, str]:
|
|
492
|
+
"""
|
|
493
|
+
Read a rule file and find its category and name from its `id`.
|
|
494
|
+
|
|
495
|
+
Parameters
|
|
496
|
+
----------
|
|
497
|
+
path : Path
|
|
498
|
+
The rule file.
|
|
499
|
+
|
|
500
|
+
Returns
|
|
501
|
+
----------
|
|
502
|
+
tuple[str, str, str]
|
|
503
|
+
(content, category, name).
|
|
504
|
+
|
|
505
|
+
Raises
|
|
506
|
+
----------
|
|
507
|
+
ProjectEnvironmentError
|
|
508
|
+
The file cannot be read.
|
|
509
|
+
RuleDefinitionError
|
|
510
|
+
The file has no valid `id`.
|
|
511
|
+
IniSyntaxError
|
|
512
|
+
The file breaks the INI dialect.
|
|
513
|
+
"""
|
|
514
|
+
try:
|
|
515
|
+
text: str = path.read_text(encoding="utf-8")
|
|
516
|
+
except (OSError, UnicodeDecodeError) as error:
|
|
517
|
+
raise ProjectEnvironmentError(f"Cannot read '{path}': {error}.") from None
|
|
518
|
+
document: IniDocument = parse_ini(text, str(path))
|
|
519
|
+
section = document.sections.get("rule")
|
|
520
|
+
rule_id: str = (section.text("id") if section is not None else None) or ""
|
|
521
|
+
category, _, name = rule_id.partition("/")
|
|
522
|
+
if not IDENTIFIER_PATTERN.fullmatch(category) or not IDENTIFIER_PATTERN.fullmatch(name):
|
|
523
|
+
raise RuleDefinitionError(f"Invalid or missing rule id '{rule_id}'.", "Expected 'id = <category>/<name>' in [rule].", path=str(path))
|
|
524
|
+
return text, category, name
|
|
525
|
+
|
|
526
|
+
|
|
527
|
+
def _section_names(editor: IniEditor) -> list[str]:
|
|
528
|
+
"""
|
|
529
|
+
Names of the sections of an edited document.
|
|
530
|
+
|
|
531
|
+
Parameters
|
|
532
|
+
----------
|
|
533
|
+
editor : IniEditor
|
|
534
|
+
The editor.
|
|
535
|
+
|
|
536
|
+
Returns
|
|
537
|
+
----------
|
|
538
|
+
list[str]
|
|
539
|
+
The section names, in order.
|
|
540
|
+
"""
|
|
541
|
+
return [line.strip()[1:-1].strip() for line in editor.lines if line.startswith("[") and line.strip().endswith("]")]
|
|
542
|
+
|
|
543
|
+
|
|
544
|
+
class RuleActions:
|
|
545
|
+
"""
|
|
546
|
+
Implementation of the actions of `jccs rule` (plan 02, section 5; plan 03, sections 11-13).
|
|
547
|
+
|
|
548
|
+
Attributes
|
|
549
|
+
----------
|
|
550
|
+
services : Services
|
|
551
|
+
Process seams.
|
|
552
|
+
flags : CommandArguments
|
|
553
|
+
Parsed `rule` flags.
|
|
554
|
+
style : Style
|
|
555
|
+
Colour adapter of stdout.
|
|
556
|
+
"""
|
|
557
|
+
|
|
558
|
+
def __init__(self, services: Services, flags: CommandArguments, style: Style) -> None:
|
|
559
|
+
"""
|
|
560
|
+
Prepare the actions.
|
|
561
|
+
|
|
562
|
+
Parameters
|
|
563
|
+
----------
|
|
564
|
+
services : Services
|
|
565
|
+
Process seams.
|
|
566
|
+
flags : CommandArguments
|
|
567
|
+
Parsed `rule` flags.
|
|
568
|
+
style : Style
|
|
569
|
+
Colour adapter of stdout.
|
|
570
|
+
|
|
571
|
+
Returns
|
|
572
|
+
----------
|
|
573
|
+
None
|
|
574
|
+
Nothing.
|
|
575
|
+
"""
|
|
576
|
+
self.services: Services = services
|
|
577
|
+
self.flags: CommandArguments = flags
|
|
578
|
+
self.style: Style = style
|
|
579
|
+
|
|
580
|
+
def _out(self, text: str) -> None:
|
|
581
|
+
"""
|
|
582
|
+
Print the result of the action on stdout.
|
|
583
|
+
|
|
584
|
+
Parameters
|
|
585
|
+
----------
|
|
586
|
+
text : str
|
|
587
|
+
The text.
|
|
588
|
+
|
|
589
|
+
Returns
|
|
590
|
+
----------
|
|
591
|
+
None
|
|
592
|
+
Nothing.
|
|
593
|
+
"""
|
|
594
|
+
self.services.stdout.write(text if text.endswith("\n") else text + "\n")
|
|
595
|
+
|
|
596
|
+
def _path(self, value: Any) -> Path:
|
|
597
|
+
"""
|
|
598
|
+
Path argument resolved against the working directory.
|
|
599
|
+
|
|
600
|
+
Parameters
|
|
601
|
+
----------
|
|
602
|
+
value : Any
|
|
603
|
+
Path value of a flag.
|
|
604
|
+
|
|
605
|
+
Returns
|
|
606
|
+
----------
|
|
607
|
+
Path
|
|
608
|
+
The resolved path.
|
|
609
|
+
"""
|
|
610
|
+
return self.services.cwd / Path(value)
|
|
611
|
+
|
|
612
|
+
def list(self, workspace: Workspace, keyword: str | None = None) -> ExitCode:
|
|
613
|
+
"""
|
|
614
|
+
`--list` / `--search`: rules of the project, optionally filtered by category and keyword.
|
|
615
|
+
|
|
616
|
+
Parameters
|
|
617
|
+
----------
|
|
618
|
+
workspace : Workspace
|
|
619
|
+
The project.
|
|
620
|
+
keyword : str | None
|
|
621
|
+
Search keyword (case-insensitive, in ID, code, aliases, title, summary and tags).
|
|
622
|
+
|
|
623
|
+
Returns
|
|
624
|
+
----------
|
|
625
|
+
ExitCode
|
|
626
|
+
Always OK.
|
|
627
|
+
"""
|
|
628
|
+
catalog: RuleCatalog = _catalog(workspace)
|
|
629
|
+
category: str | None = self.flags["category"].value
|
|
630
|
+
if category is not None and category not in catalog.categories:
|
|
631
|
+
raise UsageError(f"Unknown category '{category}'.", "Categories: " + ", ".join(catalog.categories) + ".")
|
|
632
|
+
states: list[RuleState] = []
|
|
633
|
+
for state in _states(workspace, catalog):
|
|
634
|
+
rule: RuleDefinition = state.rule
|
|
635
|
+
if category is not None and rule.category != category:
|
|
636
|
+
continue
|
|
637
|
+
if keyword is not None:
|
|
638
|
+
haystack: str = " ".join((*rule.selectors, rule.title, rule.summary, *rule.tags)).lower()
|
|
639
|
+
if keyword.lower() not in haystack:
|
|
640
|
+
continue
|
|
641
|
+
states.append(state)
|
|
642
|
+
if self.flags["json"].is_called:
|
|
643
|
+
self._out(render_rules_json(states))
|
|
644
|
+
else:
|
|
645
|
+
self._out(render_rules_text(states, self.style, with_arguments=keyword is None))
|
|
646
|
+
return ExitCode.OK
|
|
647
|
+
|
|
648
|
+
def show(self, workspace: Workspace, category: str, name: str) -> ExitCode:
|
|
649
|
+
"""
|
|
650
|
+
`--show`: everything about one rule.
|
|
651
|
+
|
|
652
|
+
Parameters
|
|
653
|
+
----------
|
|
654
|
+
workspace : Workspace
|
|
655
|
+
The project.
|
|
656
|
+
category : str
|
|
657
|
+
Category.
|
|
658
|
+
name : str
|
|
659
|
+
Rule name.
|
|
660
|
+
|
|
661
|
+
Returns
|
|
662
|
+
----------
|
|
663
|
+
ExitCode
|
|
664
|
+
Always OK.
|
|
665
|
+
"""
|
|
666
|
+
catalog: RuleCatalog = _catalog(workspace)
|
|
667
|
+
rule: RuleDefinition = _find(catalog, category, name)
|
|
668
|
+
state: RuleState = next(item for item in _states(workspace, catalog) if item.rule.id == rule.id)
|
|
669
|
+
self._out(render_rule_json(state) if self.flags["json"].is_called else render_rule_text(state, self.style))
|
|
670
|
+
return ExitCode.OK
|
|
671
|
+
|
|
672
|
+
def create(self, workspace: Workspace, category: str, name: str) -> ExitCode:
|
|
673
|
+
"""
|
|
674
|
+
`--create`: write a new custom rule skeleton (valid, in preview) and print its path.
|
|
675
|
+
|
|
676
|
+
Parameters
|
|
677
|
+
----------
|
|
678
|
+
workspace : Workspace
|
|
679
|
+
The project.
|
|
680
|
+
category : str
|
|
681
|
+
Category.
|
|
682
|
+
name : str
|
|
683
|
+
Rule name.
|
|
684
|
+
|
|
685
|
+
Returns
|
|
686
|
+
----------
|
|
687
|
+
ExitCode
|
|
688
|
+
Always OK.
|
|
689
|
+
"""
|
|
690
|
+
_check_identifier(category, "category")
|
|
691
|
+
_check_identifier(name, "rule name")
|
|
692
|
+
if name in _builtin_names():
|
|
693
|
+
raise UsageError(f"'{name}' is the name of a built-in rule.", "Custom rules cannot reuse built-in rule names; choose another name.")
|
|
694
|
+
target: Path = workspace.custom_file(category, name)
|
|
695
|
+
_require_new(target)
|
|
696
|
+
write_atomically(target, render_rule_skeleton(category, name))
|
|
697
|
+
self._out(str(target))
|
|
698
|
+
return ExitCode.OK
|
|
699
|
+
|
|
700
|
+
def set(self, workspace: Workspace, category: str, name: str, key: str, value: str) -> ExitCode:
|
|
701
|
+
"""
|
|
702
|
+
`--set`: persist a rule argument (or universal key) in the project config.
|
|
703
|
+
|
|
704
|
+
Parameters
|
|
705
|
+
----------
|
|
706
|
+
workspace : Workspace
|
|
707
|
+
The project.
|
|
708
|
+
category : str
|
|
709
|
+
Category.
|
|
710
|
+
name : str
|
|
711
|
+
Rule name.
|
|
712
|
+
key : str
|
|
713
|
+
Argument or key.
|
|
714
|
+
value : str
|
|
715
|
+
Raw value.
|
|
716
|
+
|
|
717
|
+
Returns
|
|
718
|
+
----------
|
|
719
|
+
ExitCode
|
|
720
|
+
Always OK.
|
|
721
|
+
"""
|
|
722
|
+
rule: RuleDefinition = _find(_catalog(workspace), category, name)
|
|
723
|
+
_validate_setting(rule, key, value)
|
|
724
|
+
section: str = _section_name(workspace.config, rule)
|
|
725
|
+
_edit_config(workspace, lambda editor: editor.set(section, key, value))
|
|
726
|
+
self._out(f"[{section}] {key} = {value} ({workspace.config_file})")
|
|
727
|
+
return ExitCode.OK
|
|
728
|
+
|
|
729
|
+
def toggle(self, workspace: Workspace, category: str, name: str, enabled: bool) -> ExitCode:
|
|
730
|
+
"""
|
|
731
|
+
`--enable` / `--disable`: turn a rule on or off for the project.
|
|
732
|
+
|
|
733
|
+
Parameters
|
|
734
|
+
----------
|
|
735
|
+
workspace : Workspace
|
|
736
|
+
The project.
|
|
737
|
+
category : str
|
|
738
|
+
Category.
|
|
739
|
+
name : str
|
|
740
|
+
Rule name.
|
|
741
|
+
enabled : bool
|
|
742
|
+
New state.
|
|
743
|
+
|
|
744
|
+
Returns
|
|
745
|
+
----------
|
|
746
|
+
ExitCode
|
|
747
|
+
Always OK.
|
|
748
|
+
"""
|
|
749
|
+
return self.set(workspace, category, name, "enabled", "true" if enabled else "false")
|
|
750
|
+
|
|
751
|
+
def delete(self, workspace: Workspace, category: str, name: str) -> ExitCode:
|
|
752
|
+
"""
|
|
753
|
+
`--delete`: remove a custom rule file and its project settings.
|
|
754
|
+
|
|
755
|
+
Parameters
|
|
756
|
+
----------
|
|
757
|
+
workspace : Workspace
|
|
758
|
+
The project.
|
|
759
|
+
category : str
|
|
760
|
+
Category.
|
|
761
|
+
name : str
|
|
762
|
+
Rule name.
|
|
763
|
+
|
|
764
|
+
Returns
|
|
765
|
+
----------
|
|
766
|
+
ExitCode
|
|
767
|
+
Always OK.
|
|
768
|
+
"""
|
|
769
|
+
target: Path = workspace.custom_file(category, name)
|
|
770
|
+
if not target.is_file():
|
|
771
|
+
if (BUILTIN_RULES_DIRECTORY / category / f"{name}.ini").is_file():
|
|
772
|
+
raise UsageError(f"'{category}/{name}' is a built-in rule and cannot be deleted.", f"Turn it off with: rule --disable {category} {name}")
|
|
773
|
+
raise UnknownRuleError(f"{category}/{name}")
|
|
774
|
+
try:
|
|
775
|
+
target.unlink()
|
|
776
|
+
except OSError as error:
|
|
777
|
+
raise ProjectEnvironmentError(f"Cannot delete '{target}': {error.strerror}.") from None
|
|
778
|
+
self._remove_settings(workspace, f"{category}/{name}")
|
|
779
|
+
self._out(f"deleted {target}")
|
|
780
|
+
return ExitCode.OK
|
|
781
|
+
|
|
782
|
+
def _remove_settings(self, workspace: Workspace, rule_id: str) -> None:
|
|
783
|
+
"""
|
|
784
|
+
Remove the config section of a rule (written with its ID).
|
|
785
|
+
|
|
786
|
+
Parameters
|
|
787
|
+
----------
|
|
788
|
+
workspace : Workspace
|
|
789
|
+
The project.
|
|
790
|
+
rule_id : str
|
|
791
|
+
Rule ID.
|
|
792
|
+
|
|
793
|
+
Returns
|
|
794
|
+
----------
|
|
795
|
+
None
|
|
796
|
+
Nothing.
|
|
797
|
+
"""
|
|
798
|
+
sections: list[str] = [RULE_SECTION + written for written in workspace.config.rules if written == rule_id]
|
|
799
|
+
if sections:
|
|
800
|
+
_edit_config(workspace, lambda editor: [editor.remove_section(section) for section in sections])
|
|
801
|
+
|
|
802
|
+
def reset(self, workspace: Workspace, category: str, name: str) -> ExitCode:
|
|
803
|
+
"""
|
|
804
|
+
`--reset`: bring a rule back to what `--create` produced (custom rule file re-rendered) and remove
|
|
805
|
+
every value set for it in the project config.
|
|
806
|
+
|
|
807
|
+
Parameters
|
|
808
|
+
----------
|
|
809
|
+
workspace : Workspace
|
|
810
|
+
The project.
|
|
811
|
+
category : str
|
|
812
|
+
Category.
|
|
813
|
+
name : str
|
|
814
|
+
Rule name.
|
|
815
|
+
|
|
816
|
+
Returns
|
|
817
|
+
----------
|
|
818
|
+
ExitCode
|
|
819
|
+
Always OK.
|
|
820
|
+
"""
|
|
821
|
+
target: Path = workspace.custom_file(category, name)
|
|
822
|
+
builtin: bool = (BUILTIN_RULES_DIRECTORY / category / f"{name}.ini").is_file()
|
|
823
|
+
if not target.is_file() and not builtin:
|
|
824
|
+
raise UnknownRuleError(f"{category}/{name}")
|
|
825
|
+
rule_id: str = f"{category}/{name}"
|
|
826
|
+
selectors: tuple[str, ...] = (rule_id,)
|
|
827
|
+
if builtin:
|
|
828
|
+
selectors = RuleCatalog.load().get(rule_id).selectors
|
|
829
|
+
if target.is_file():
|
|
830
|
+
write_atomically(target, render_rule_skeleton(category, name))
|
|
831
|
+
sections: list[str] = [RULE_SECTION + written for written in workspace.config.rules if written in selectors]
|
|
832
|
+
if sections:
|
|
833
|
+
_edit_config(workspace, lambda editor: [editor.remove_section(section) for section in sections])
|
|
834
|
+
self._out(f"reset {rule_id}" + (f" ({target} re-rendered)" if target.is_file() else ""))
|
|
835
|
+
return ExitCode.OK
|
|
836
|
+
|
|
837
|
+
def duplicate(self, workspace: Workspace, category: str, name: str, new_name: str) -> ExitCode:
|
|
838
|
+
"""
|
|
839
|
+
`--duplicate`: copy a rule under a new name in the same category, as a custom rule (its Epitech
|
|
840
|
+
reference, code and aliases are cleared so that selectors stay unique).
|
|
841
|
+
|
|
842
|
+
Parameters
|
|
843
|
+
----------
|
|
844
|
+
workspace : Workspace
|
|
845
|
+
The project.
|
|
846
|
+
category : str
|
|
847
|
+
Category.
|
|
848
|
+
name : str
|
|
849
|
+
Rule name.
|
|
850
|
+
new_name : str
|
|
851
|
+
Name of the copy.
|
|
852
|
+
|
|
853
|
+
Returns
|
|
854
|
+
----------
|
|
855
|
+
ExitCode
|
|
856
|
+
Always OK.
|
|
857
|
+
"""
|
|
858
|
+
_check_identifier(new_name, "rule name")
|
|
859
|
+
if new_name in _builtin_names():
|
|
860
|
+
raise UsageError(f"'{new_name}' is the name of a built-in rule.", "Choose another name.")
|
|
861
|
+
rule: RuleDefinition = _find(_catalog(workspace), category, name)
|
|
862
|
+
target: Path = workspace.custom_file(category, new_name)
|
|
863
|
+
_require_new(target)
|
|
864
|
+
source: Path = Path(rule.source)
|
|
865
|
+
editor: IniEditor = IniEditor(source.read_text(encoding="utf-8"))
|
|
866
|
+
editor.set("rule", "id", f"{category}/{new_name}")
|
|
867
|
+
editor.set("rule", "code", "")
|
|
868
|
+
editor.set("rule", "aliases", "")
|
|
869
|
+
if editor.has_section("epitech"):
|
|
870
|
+
editor.set("epitech", "ref", "")
|
|
871
|
+
text: str = editor.text()
|
|
872
|
+
load_rule_text(text, category, new_name, base_directory=source.parent.parent)
|
|
873
|
+
_install_rule(text, source.parent, target)
|
|
874
|
+
self._out(str(target))
|
|
875
|
+
return ExitCode.OK
|
|
876
|
+
|
|
877
|
+
def export(self, workspace: Workspace, category: str, name: str, destination: Any) -> ExitCode:
|
|
878
|
+
"""
|
|
879
|
+
`--export`: write the rule definition with its effective argument values (project config applied).
|
|
880
|
+
|
|
881
|
+
Parameters
|
|
882
|
+
----------
|
|
883
|
+
workspace : Workspace
|
|
884
|
+
The project.
|
|
885
|
+
category : str
|
|
886
|
+
Category.
|
|
887
|
+
name : str
|
|
888
|
+
Rule name.
|
|
889
|
+
destination : Any
|
|
890
|
+
Destination path.
|
|
891
|
+
|
|
892
|
+
Returns
|
|
893
|
+
----------
|
|
894
|
+
ExitCode
|
|
895
|
+
Always OK.
|
|
896
|
+
"""
|
|
897
|
+
rule: RuleDefinition = _find(_catalog(workspace), category, name)
|
|
898
|
+
target: Path = self._path(destination)
|
|
899
|
+
_require_new(target)
|
|
900
|
+
editor: IniEditor = IniEditor(Path(rule.source).read_text(encoding="utf-8"))
|
|
901
|
+
configured: dict[str, str] = _configured(workspace.config, rule)
|
|
902
|
+
for argument in rule.arguments:
|
|
903
|
+
if argument in configured:
|
|
904
|
+
editor.set(f"argument:{argument}", "default", configured[argument])
|
|
905
|
+
header: list[str] = [f"# Exported by jccs from {rule.source}", f"# with the argument values of {workspace.config_file}."]
|
|
906
|
+
exported: RuleDefinition = load_rule_text(editor.text(), category, name, base_directory=Path(rule.source).parent.parent)
|
|
907
|
+
failing: list[str] = [result.example_id for result in run_rule_examples(exported) if not result.passed]
|
|
908
|
+
for example_id in failing:
|
|
909
|
+
for section in [section for section in list(_section_names(editor)) if section == f"example:{example_id}" or section.startswith(f"example:{example_id}:")]:
|
|
910
|
+
editor.remove_section(section)
|
|
911
|
+
header.append(f"# Example '{example_id}' was removed: it does not match the exported values.")
|
|
912
|
+
kinds: set[str] = {example.kind.value for example in exported.examples if example.id not in failing}
|
|
913
|
+
if failing and exported.status.value == "stable" and kinds != {"good", "bad"}:
|
|
914
|
+
editor.set("rule", "status", "preview")
|
|
915
|
+
header.append("# Status set to preview: a stable rule needs a good and a bad example.")
|
|
916
|
+
editor.lines[0:0] = [*header, ""]
|
|
917
|
+
write_atomically(target, editor.text())
|
|
918
|
+
self._out(str(target))
|
|
919
|
+
return ExitCode.OK
|
|
920
|
+
|
|
921
|
+
def import_rule(self, workspace: Workspace, source_value: Any) -> ExitCode:
|
|
922
|
+
"""
|
|
923
|
+
`--import`: validate an external rule file and install it as a custom rule (with its fixtures).
|
|
924
|
+
|
|
925
|
+
Parameters
|
|
926
|
+
----------
|
|
927
|
+
workspace : Workspace
|
|
928
|
+
The project.
|
|
929
|
+
source_value : Any
|
|
930
|
+
Path of the rule file.
|
|
931
|
+
|
|
932
|
+
Returns
|
|
933
|
+
----------
|
|
934
|
+
ExitCode
|
|
935
|
+
Always OK.
|
|
936
|
+
"""
|
|
937
|
+
source: Path = self._path(source_value)
|
|
938
|
+
text, category, name = _read_rule_file(source)
|
|
939
|
+
if name in _builtin_names():
|
|
940
|
+
raise UsageError(f"'{name}' is the name of a built-in rule.", "Rename the rule (id) before importing it.")
|
|
941
|
+
imported: RuleDefinition = load_rule_text(text, category, name, base_directory=source.parent.parent)
|
|
942
|
+
target: Path = workspace.custom_file(category, name)
|
|
943
|
+
_require_new(target)
|
|
944
|
+
RuleCatalog([*_catalog(workspace).rules.values(), imported])
|
|
945
|
+
_install_rule(text, source.parent, target)
|
|
946
|
+
self._out(str(target))
|
|
947
|
+
return ExitCode.OK
|
|
948
|
+
|
|
949
|
+
def validate(self, path_value: Any) -> ExitCode:
|
|
950
|
+
"""
|
|
951
|
+
`--validate`: check a rule file (schema 2) and run its examples. Prints "path: valid", or one
|
|
952
|
+
"path:line: message" per problem.
|
|
953
|
+
|
|
954
|
+
Parameters
|
|
955
|
+
----------
|
|
956
|
+
path_value : Any
|
|
957
|
+
Path of the rule file.
|
|
958
|
+
|
|
959
|
+
Returns
|
|
960
|
+
----------
|
|
961
|
+
ExitCode
|
|
962
|
+
OK when valid, CONFIG when invalid.
|
|
963
|
+
"""
|
|
964
|
+
path: Path = self._path(path_value)
|
|
965
|
+
problems: list[dict[str, Any]] = []
|
|
966
|
+
try:
|
|
967
|
+
text, category, name = _read_rule_file(path)
|
|
968
|
+
if path.stem != name:
|
|
969
|
+
problems.append({"line": None, "message": f"the file must be named {name}.ini to match id {category}/{name}", "hint": None})
|
|
970
|
+
rule: RuleDefinition = load_rule_text(text, category, name, base_directory=path.parent.parent)
|
|
971
|
+
results: list[ExampleResult] = run_rule_examples(rule)
|
|
972
|
+
for result in results:
|
|
973
|
+
for problem in result.problems:
|
|
974
|
+
problems.append({"line": None, "message": f"example '{result.example_id}': {problem}", "hint": None})
|
|
975
|
+
except (RuleDefinitionError, IniSyntaxError) as error:
|
|
976
|
+
problems.append({"line": error.line, "message": str(error.args[0]) if error.args else "invalid rule", "hint": error.hint})
|
|
977
|
+
if self.flags["json"].is_called:
|
|
978
|
+
self._out(json.dumps({"schema_version": 1, "path": str(path), "valid": not problems, "problems": problems}, indent=2))
|
|
979
|
+
elif not problems:
|
|
980
|
+
self._out(f"{path}: valid")
|
|
981
|
+
else:
|
|
982
|
+
for problem in problems:
|
|
983
|
+
location: str = f"{path}:{problem['line']}" if problem["line"] else str(path)
|
|
984
|
+
self._out(f"{location}: {problem['message']}" + (f" ({problem['hint']})" if problem["hint"] else ""))
|
|
985
|
+
return ExitCode.OK if not problems else ExitCode.CONFIG
|
|
986
|
+
|
|
987
|
+
|
|
988
|
+
def _selected_action(flags: CommandArguments) -> str:
|
|
989
|
+
"""
|
|
990
|
+
The action of the command line (`list` when none is given), after checking the modifiers.
|
|
991
|
+
|
|
992
|
+
Parameters
|
|
993
|
+
----------
|
|
994
|
+
flags : CommandArguments
|
|
995
|
+
Parsed `rule` flags.
|
|
996
|
+
|
|
997
|
+
Returns
|
|
998
|
+
----------
|
|
999
|
+
str
|
|
1000
|
+
The action name.
|
|
1001
|
+
|
|
1002
|
+
Raises
|
|
1003
|
+
----------
|
|
1004
|
+
UsageError
|
|
1005
|
+
`--category` or `--json` used with an action that does not accept it.
|
|
1006
|
+
"""
|
|
1007
|
+
action: str = next((name for name in ACTIONS if flags[name].is_called), "list")
|
|
1008
|
+
if flags["category"].is_called and action not in CATEGORY_ACTIONS:
|
|
1009
|
+
raise UsageError("--category only applies to --list and --search.")
|
|
1010
|
+
if flags["json"].is_called and action not in JSON_ACTIONS:
|
|
1011
|
+
raise UsageError("--json only applies to --list, --show, --search and --validate.")
|
|
1012
|
+
return action
|
|
1013
|
+
|
|
1014
|
+
|
|
1015
|
+
def run_rule(arguments: ParsedArguments, services: Services) -> ExitCode:
|
|
1016
|
+
"""
|
|
1017
|
+
`jccs rule`: run the selected action on the project of the working directory.
|
|
1018
|
+
|
|
1019
|
+
Parameters
|
|
1020
|
+
----------
|
|
1021
|
+
arguments : ParsedArguments
|
|
1022
|
+
Parsed command line.
|
|
1023
|
+
services : Services
|
|
1024
|
+
Process seams.
|
|
1025
|
+
|
|
1026
|
+
Returns
|
|
1027
|
+
----------
|
|
1028
|
+
ExitCode
|
|
1029
|
+
The exit code.
|
|
1030
|
+
|
|
1031
|
+
Raises
|
|
1032
|
+
----------
|
|
1033
|
+
JccsError
|
|
1034
|
+
Usage, configuration or environment errors.
|
|
1035
|
+
"""
|
|
1036
|
+
flags: CommandArguments = arguments.command
|
|
1037
|
+
action: str = _selected_action(flags)
|
|
1038
|
+
style: Style = Style(services.color_enabled(services.stdout, disabled=bool(arguments.value("no_color"))))
|
|
1039
|
+
actions: RuleActions = RuleActions(services, flags, style)
|
|
1040
|
+
if action == "validate":
|
|
1041
|
+
return actions.validate(flags["validate"].value[0] if isinstance(flags["validate"].value, tuple) else flags["validate"].value)
|
|
1042
|
+
workspace: Workspace = _open_workspace(services)
|
|
1043
|
+
value: Any = flags[action].value
|
|
1044
|
+
match action:
|
|
1045
|
+
case "list":
|
|
1046
|
+
return actions.list(workspace)
|
|
1047
|
+
case "search":
|
|
1048
|
+
return actions.list(workspace, value)
|
|
1049
|
+
case "show":
|
|
1050
|
+
return actions.show(workspace, *value)
|
|
1051
|
+
case "create":
|
|
1052
|
+
return actions.create(workspace, *value)
|
|
1053
|
+
case "set":
|
|
1054
|
+
return actions.set(workspace, *value)
|
|
1055
|
+
case "enable" | "disable":
|
|
1056
|
+
return actions.toggle(workspace, *value, enabled=action == "enable")
|
|
1057
|
+
case "delete":
|
|
1058
|
+
return actions.delete(workspace, *value)
|
|
1059
|
+
case "reset":
|
|
1060
|
+
return actions.reset(workspace, *value)
|
|
1061
|
+
case "duplicate":
|
|
1062
|
+
return actions.duplicate(workspace, *value)
|
|
1063
|
+
case "export":
|
|
1064
|
+
return actions.export(workspace, *value)
|
|
1065
|
+
case "import_rule":
|
|
1066
|
+
return actions.import_rule(workspace, value[0] if isinstance(value, tuple) else value)
|
|
1067
|
+
raise UsageError(f"Unknown action '{action}'.")
|