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.
Files changed (186) hide show
  1. jarbin_c_coding_style-2.0.0.dist-info/METADATA +150 -0
  2. jarbin_c_coding_style-2.0.0.dist-info/RECORD +186 -0
  3. jarbin_c_coding_style-2.0.0.dist-info/WHEEL +4 -0
  4. jarbin_c_coding_style-2.0.0.dist-info/entry_points.txt +2 -0
  5. jarbin_c_coding_style-2.0.0.dist-info/licenses/LICENSE +674 -0
  6. sources/__init__.py +0 -0
  7. sources/__main__.py +6 -0
  8. sources/analysis/__init__.py +0 -0
  9. sources/analysis/directives.py +258 -0
  10. sources/analysis/lexer.py +288 -0
  11. sources/analysis/parser.py +1754 -0
  12. sources/analysis/project.py +286 -0
  13. sources/analysis/source.py +326 -0
  14. sources/analysis/syntax.py +238 -0
  15. sources/analysis/tokens.py +116 -0
  16. sources/analysis/unit.py +700 -0
  17. sources/application.py +118 -0
  18. sources/build_info.json +6 -0
  19. sources/cli/__init__.py +0 -0
  20. sources/cli/arguments.py +507 -0
  21. sources/cli/completion.py +610 -0
  22. sources/cli/context.py +258 -0
  23. sources/cli/converters.py +204 -0
  24. sources/cli/help.py +162 -0
  25. sources/cli/parser.py +659 -0
  26. sources/configs/__init__.py +0 -0
  27. sources/configs/editor.py +207 -0
  28. sources/configs/ini.py +327 -0
  29. sources/configs/project.py +735 -0
  30. sources/configs/schema/__init__.py +0 -0
  31. sources/configs/schema/project.py +68 -0
  32. sources/constants.py +801 -0
  33. sources/diagnostics/__init__.py +0 -0
  34. sources/diagnostics/fingerprint.py +82 -0
  35. sources/diagnostics/model.py +146 -0
  36. sources/engine/__init__.py +0 -0
  37. sources/engine/api.py +355 -0
  38. sources/engine/examples.py +157 -0
  39. sources/engine/outcome.py +114 -0
  40. sources/engine/plan.py +440 -0
  41. sources/engine/runner.py +345 -0
  42. sources/engine/scanner.py +179 -0
  43. sources/enums.py +838 -0
  44. sources/errors/__init__.py +0 -0
  45. sources/errors/exceptions.py +727 -0
  46. sources/fixers/__init__.py +0 -0
  47. sources/fixers/base.py +209 -0
  48. sources/fixers/conflicts.py +129 -0
  49. sources/fixers/diff.py +73 -0
  50. sources/fixers/engine.py +434 -0
  51. sources/fixers/journal.py +290 -0
  52. sources/fixers/kinds.py +30 -0
  53. sources/fixers/layout.py +411 -0
  54. sources/fixers/model.py +151 -0
  55. sources/fixers/registry.py +54 -0
  56. sources/fixers/text.py +353 -0
  57. sources/fixers/verify.py +123 -0
  58. sources/fixers/writer.py +88 -0
  59. sources/integrations/__init__.py +0 -0
  60. sources/integrations/ci/__init__.py +0 -0
  61. sources/integrations/ci/github.py +183 -0
  62. sources/integrations/editors/__init__.py +0 -0
  63. sources/integrations/git/__init__.py +0 -0
  64. sources/integrations/git/repository.py +176 -0
  65. sources/integrations/update/__init__.py +0 -0
  66. sources/integrations/update/installers.py +529 -0
  67. sources/integrations/update/releases.py +397 -0
  68. sources/integrations/update/state.py +143 -0
  69. sources/outputs/__init__.py +0 -0
  70. sources/outputs/github/__init__.py +0 -0
  71. sources/outputs/github/renderer.py +135 -0
  72. sources/outputs/html/__init__.py +0 -0
  73. sources/outputs/html/renderer.py +694 -0
  74. sources/outputs/json/__init__.py +0 -0
  75. sources/outputs/json/renderer.py +154 -0
  76. sources/outputs/json/report.schema.json +121 -0
  77. sources/outputs/junit/__init__.py +0 -0
  78. sources/outputs/junit/renderer.py +151 -0
  79. sources/outputs/registry.py +135 -0
  80. sources/outputs/report.py +224 -0
  81. sources/outputs/sarif/__init__.py +0 -0
  82. sources/outputs/sarif/renderer.py +182 -0
  83. sources/outputs/terminal/__init__.py +0 -0
  84. sources/outputs/terminal/renderer.py +184 -0
  85. sources/outputs/terminal/style.py +159 -0
  86. sources/rules/__init__.py +0 -0
  87. sources/rules/arguments.py +362 -0
  88. sources/rules/catalog.py +227 -0
  89. sources/rules/categories/advanced/constant_pointers.ini +46 -0
  90. sources/rules/categories/advanced/line_break_at_end_of_file.ini +44 -0
  91. sources/rules/categories/advanced/static.ini +65 -0
  92. sources/rules/categories/advanced/typing.ini +47 -0
  93. sources/rules/categories/control_structures/conditional_branching.ini +89 -0
  94. sources/rules/categories/control_structures/goto.ini +45 -0
  95. sources/rules/categories/control_structures/ternary_operators.ini +57 -0
  96. sources/rules/categories/extensions/language_extensions.ini +71 -0
  97. sources/rules/categories/files_organization/contents_of_the_repository.ini +85 -0
  98. sources/rules/categories/files_organization/file_coherence.ini +166 -0
  99. sources/rules/categories/files_organization/file_extension.ini +68 -0
  100. sources/rules/categories/files_organization/fixtures/program +0 -0
  101. sources/rules/categories/files_organization/naming_files_and_folders.ini +74 -0
  102. sources/rules/categories/functions/coherence_of_functions.ini +45 -0
  103. sources/rules/categories/functions/comments_inside_a_function.ini +45 -0
  104. sources/rules/categories/functions/functions_without_parameters.ini +39 -0
  105. sources/rules/categories/functions/naming_functions.ini +79 -0
  106. sources/rules/categories/functions/number_of_columns.ini +61 -0
  107. sources/rules/categories/functions/number_of_lines.ini +70 -0
  108. sources/rules/categories/functions/number_of_parameters.ini +64 -0
  109. sources/rules/categories/functions/structures_as_parameters.ini +44 -0
  110. sources/rules/categories/global_scope/constant_values.ini +49 -0
  111. sources/rules/categories/global_scope/file_header.ini +92 -0
  112. sources/rules/categories/global_scope/global_variables.ini +53 -0
  113. sources/rules/categories/global_scope/include.ini +39 -0
  114. sources/rules/categories/global_scope/indentation_of_preprocessor.ini +62 -0
  115. sources/rules/categories/global_scope/inline_assembly.ini +43 -0
  116. sources/rules/categories/global_scope/leading_trailing_lines.ini +58 -0
  117. sources/rules/categories/global_scope/line_endings.ini +53 -0
  118. sources/rules/categories/global_scope/separation_of_functions.ini +61 -0
  119. sources/rules/categories/global_scope/trailing_spaces.ini +45 -0
  120. sources/rules/categories/header_files/content.ini +104 -0
  121. sources/rules/categories/header_files/include_guard.ini +47 -0
  122. sources/rules/categories/header_files/macros.ini +57 -0
  123. sources/rules/categories/layout_inside_a_function_scope/blank_lines.ini +71 -0
  124. sources/rules/categories/layout_inside_a_function_scope/code_line_content.ini +112 -0
  125. sources/rules/categories/layout_inside_a_function_scope/curly_brackets.ini +94 -0
  126. sources/rules/categories/layout_inside_a_function_scope/indentation.ini +96 -0
  127. sources/rules/categories/layout_inside_a_function_scope/spaces.ini +113 -0
  128. sources/rules/categories/layout_inside_a_function_scope/variable_declarations.ini +65 -0
  129. sources/rules/categories/variables_and_types/naming_identifiers.ini +74 -0
  130. sources/rules/categories/variables_and_types/pointers.ini +67 -0
  131. sources/rules/categories/variables_and_types/structures.ini +47 -0
  132. sources/rules/data/verbs.txt +182 -0
  133. sources/rules/definition.py +430 -0
  134. sources/rules/loader.py +925 -0
  135. sources/rules/paths.py +6 -0
  136. sources/rules/primitives/__init__.py +0 -0
  137. sources/rules/primitives/base.py +297 -0
  138. sources/rules/primitives/braces.py +211 -0
  139. sources/rules/primitives/directives.py +203 -0
  140. sources/rules/primitives/indentation.py +376 -0
  141. sources/rules/primitives/layout.py +199 -0
  142. sources/rules/primitives/naming.py +277 -0
  143. sources/rules/primitives/project.py +62 -0
  144. sources/rules/primitives/registry.py +49 -0
  145. sources/rules/primitives/repository.py +129 -0
  146. sources/rules/primitives/review.py +87 -0
  147. sources/rules/primitives/semantic.py +319 -0
  148. sources/rules/primitives/spacing.py +210 -0
  149. sources/rules/primitives/structure.py +586 -0
  150. sources/rules/primitives/syntax.py +200 -0
  151. sources/rules/primitives/text.py +408 -0
  152. sources/rules/primitives/tokens.py +84 -0
  153. sources/rules/template.py +138 -0
  154. sources/selftest/__init__.py +0 -0
  155. sources/selftest/cases.py +292 -0
  156. sources/services.py +90 -0
  157. sources/subcommands/__init__.py +0 -0
  158. sources/subcommands/base.py +45 -0
  159. sources/subcommands/check/__init__.py +0 -0
  160. sources/subcommands/check/command.py +45 -0
  161. sources/subcommands/check/fixing.py +224 -0
  162. sources/subcommands/check/handler.py +757 -0
  163. sources/subcommands/info/__init__.py +0 -0
  164. sources/subcommands/info/command.py +45 -0
  165. sources/subcommands/info/handler.py +527 -0
  166. sources/subcommands/registry.py +37 -0
  167. sources/subcommands/rule/__init__.py +0 -0
  168. sources/subcommands/rule/command.py +45 -0
  169. sources/subcommands/rule/handler.py +1067 -0
  170. sources/subcommands/rule/render.py +273 -0
  171. sources/subcommands/runner.py +124 -0
  172. sources/subcommands/test/__init__.py +0 -0
  173. sources/subcommands/test/command.py +45 -0
  174. sources/subcommands/test/handler.py +166 -0
  175. sources/subcommands/test/render.py +219 -0
  176. sources/subcommands/test/runner.py +430 -0
  177. sources/subcommands/update/__init__.py +0 -0
  178. sources/subcommands/update/command.py +45 -0
  179. sources/subcommands/update/handler.py +408 -0
  180. sources/utils/__init__.py +0 -0
  181. sources/utils/build_info.py +188 -0
  182. sources/utils/git.py +73 -0
  183. sources/utils/globs.py +98 -0
  184. sources/utils/logging.py +154 -0
  185. sources/utils/schema.py +77 -0
  186. sources/utils/versions.py +87 -0
@@ -0,0 +1,735 @@
1
+ import difflib
2
+ from collections.abc import Iterable, Mapping
3
+ from configparser import ConfigParser, Error as ConfigParserError
4
+ from dataclasses import dataclass, field
5
+ from pathlib import Path
6
+ from types import MappingProxyType
7
+ from typing import Any
8
+
9
+ from jarbin_toolkit_config import Config, ConfigFileNotFoundJError, ConfigRuntimeJError
10
+ from jarbin_toolkit_error import JException
11
+
12
+ from sources.configs.schema.project import (
13
+ CHECK_KEY_PREFIX,
14
+ CHECK_SETTING_KEYS,
15
+ FIXED_SECTIONS,
16
+ JCCS_KEYS,
17
+ OVERRIDE_KEYS,
18
+ OVERRIDE_SECTION_PREFIX,
19
+ PATHS_KEYS,
20
+ RULE_SECTION_PREFIX,
21
+ RULE_SETTING_KEYS,
22
+ RULES_KEYS,
23
+ )
24
+ from sources.constants import PROGRAM_VERSION
25
+ from sources.enums import SeverityLevel
26
+ from sources.errors.exceptions import ProjectConfigError, ProjectEnvironmentError, ValueConversionError
27
+ from sources.rules.arguments import ArgumentSpec
28
+ from sources.rules.paths import BUILTIN_RULES_DIRECTORY
29
+ from sources.utils.versions import check_constraint
30
+
31
+
32
+ # Name of the JCCS directory at the project root (config, custom rules, state).
33
+ PROJECT_DIRECTORY_NAME: str = ".JCCS"
34
+
35
+ # Name of the project config file inside the JCCS directory, without its `.ini` extension.
36
+ CONFIG_FILE_STEM: str = ".jccs"
37
+
38
+ # Full name of the project config file.
39
+ CONFIG_FILE_NAME: str = f"{CONFIG_FILE_STEM}.ini"
40
+
41
+ # Content of the `.gitignore` created in the JCCS directory (state that must not be committed).
42
+ PROJECT_GITIGNORE: str = "# Generated by JCCS: local state, never committed.\ncache/\nlogs/\nfix-journal/\n"
43
+
44
+ # First line of the generated .JCCS/.gitignore (a file starting with it is upgraded when entries are added).
45
+ PROJECT_GITIGNORE_HEADER: str = PROJECT_GITIGNORE.splitlines()[0]
46
+
47
+ # Directory or file marking the root of a git repository.
48
+ GIT_MARKER: str = ".git"
49
+
50
+
51
+ @dataclass(frozen=True, slots=True)
52
+ class RuleSettings:
53
+ """
54
+ Content of one `[rule:<id>]` section.
55
+ (dataclass)
56
+
57
+ Attributes
58
+ ----------
59
+ rule_id : str
60
+ Rule ID or alias as written.
61
+ enabled : bool | None
62
+ Forced state, or None.
63
+ severity : SeverityLevel | None
64
+ Severity override, or None.
65
+ include : tuple[str, ...]
66
+ Only check files matching these globs.
67
+ exclude : tuple[str, ...]
68
+ Never check files matching these globs.
69
+ check_enabled : Mapping[str, bool]
70
+ Per-check state overrides.
71
+ check_severity : Mapping[str, SeverityLevel]
72
+ Per-check severity overrides.
73
+ arguments : Mapping[str, str]
74
+ Raw argument values (typed later with the rule argument specs).
75
+ """
76
+
77
+ rule_id: str
78
+ enabled: bool | None = None
79
+ severity: SeverityLevel | None = None
80
+ include: tuple[str, ...] = ()
81
+ exclude: tuple[str, ...] = ()
82
+ check_enabled: Mapping[str, bool] = field(default_factory=lambda: MappingProxyType({}))
83
+ check_severity: Mapping[str, SeverityLevel] = field(default_factory=lambda: MappingProxyType({}))
84
+ arguments: Mapping[str, str] = field(default_factory=lambda: MappingProxyType({}))
85
+
86
+
87
+ @dataclass(frozen=True, slots=True)
88
+ class PathOverride:
89
+ """
90
+ Content of one `[override:<glob>]` section.
91
+ (dataclass)
92
+
93
+ Attributes
94
+ ----------
95
+ glob : str
96
+ Files the override applies to.
97
+ enable : tuple[str, ...]
98
+ Selectors enabled for those files.
99
+ disable : tuple[str, ...]
100
+ Selectors disabled for those files.
101
+ """
102
+
103
+ glob: str
104
+ enable: tuple[str, ...] = ()
105
+ disable: tuple[str, ...] = ()
106
+
107
+
108
+ @dataclass(frozen=True, slots=True)
109
+ class ProjectConfig:
110
+ """
111
+ The resolved project configuration (`.JCCS/.jccs.ini`, or the defaults).
112
+ (dataclass)
113
+
114
+ Attributes
115
+ ----------
116
+ source : str | None
117
+ Config file the values come from (None for the defaults).
118
+ directory : Path | None
119
+ JCCS directory (custom rules and relative paths are resolved against it).
120
+ version : int
121
+ Schema version of the file.
122
+ min_jccs_version : str
123
+ Oldest JCCS version able to check the project.
124
+ include : tuple[str, ...]
125
+ Only analyse files matching these globs.
126
+ exclude : tuple[str, ...]
127
+ Files removed from the project.
128
+ max_file_size : int
129
+ Size cap of loaded files, in bytes.
130
+ use_gitignore : bool
131
+ Whether git-ignored files are skipped.
132
+ fail_on : SeverityLevel
133
+ Lowest failing severity.
134
+ max_errors : int
135
+ Tolerated failing findings.
136
+ strict_heuristics : bool
137
+ Whether heuristic checks may fail the run.
138
+ rules_dir : str
139
+ Custom rules directory, relative to the JCCS directory.
140
+ enable : tuple[str, ...]
141
+ Selectors enabled on top of the stable rules.
142
+ disable : tuple[str, ...]
143
+ Selectors disabled.
144
+ rules : Mapping[str, RuleSettings]
145
+ Per-rule settings, by rule ID or alias as written.
146
+ overrides : tuple[PathOverride, ...]
147
+ Path-scoped overrides, in file order.
148
+ """
149
+
150
+ source: str | None = None
151
+ directory: Path | None = None
152
+ version: int = 1
153
+ min_jccs_version: str = ""
154
+ include: tuple[str, ...] = ()
155
+ exclude: tuple[str, ...] = ()
156
+ max_file_size: int = 1048576
157
+ use_gitignore: bool = True
158
+ fail_on: SeverityLevel = SeverityLevel.MINOR
159
+ max_errors: int = 0
160
+ strict_heuristics: bool = False
161
+ rules_dir: str = "rules"
162
+ enable: tuple[str, ...] = ()
163
+ disable: tuple[str, ...] = ()
164
+ rules: Mapping[str, RuleSettings] = field(default_factory=lambda: MappingProxyType({}))
165
+ overrides: tuple[PathOverride, ...] = ()
166
+
167
+ @property
168
+ def custom_rules_directory(self) -> Path | None:
169
+ """
170
+ Directory of the custom rules.
171
+
172
+ Returns
173
+ ----------
174
+ Path | None
175
+ The directory, or None without a JCCS directory.
176
+ """
177
+ return self.directory / self.rules_dir if self.directory is not None else None
178
+
179
+
180
+ def find_project_root(start: Path) -> Path:
181
+ """
182
+ Find the project root (plan 05, section 5): walking up from `start`, the first directory holding a `.JCCS`
183
+ directory; the search stops at the root of the enclosing git repository, which is the project root when
184
+ no `.JCCS` was found below it; without a repository, `start` itself.
185
+
186
+ Parameters
187
+ ----------
188
+ start : Path
189
+ Directory where the search starts.
190
+
191
+ Returns
192
+ ----------
193
+ Path
194
+ The project root (absolute).
195
+ """
196
+ start = start.resolve()
197
+ for directory in (start, *start.parents):
198
+ if (directory / PROJECT_DIRECTORY_NAME).is_dir() or (directory / GIT_MARKER).exists():
199
+ return directory
200
+ return start
201
+
202
+
203
+ def _comment_block(text: str) -> list[str]:
204
+ """
205
+ Turn a description into comment lines.
206
+
207
+ Parameters
208
+ ----------
209
+ text : str
210
+ The description.
211
+
212
+ Returns
213
+ ----------
214
+ list[str]
215
+ Lines starting with "# ".
216
+ """
217
+ return [f"# {line}" for line in text.split("\n")]
218
+
219
+
220
+ def _default_text(spec: ArgumentSpec) -> str:
221
+ """
222
+ Text of a default value as written in an INI file.
223
+
224
+ Parameters
225
+ ----------
226
+ spec : ArgumentSpec
227
+ The value specification.
228
+
229
+ Returns
230
+ ----------
231
+ str
232
+ The text ("" for no value).
233
+ """
234
+ value: Any = spec.default
235
+ if value is None:
236
+ return ""
237
+ if isinstance(value, bool):
238
+ return "true" if value else "false"
239
+ if isinstance(value, (tuple, frozenset)):
240
+ return ", ".join(sorted(str(item) for item in value)) if isinstance(value, frozenset) else ", ".join(str(item) for item in value)
241
+ if hasattr(value, "pattern"):
242
+ return value.pattern
243
+ if hasattr(value, "lines"):
244
+ return ""
245
+ return str(value)
246
+
247
+
248
+ def render_config_template(rules: Iterable[Any] = ()) -> str:
249
+ """
250
+ Text of a new `.jccs.ini`: every key with its documented default, and one commented `[rule:<id>]`
251
+ block per known rule listing its arguments and default values.
252
+
253
+ Parameters
254
+ ----------
255
+ rules : Iterable[Any]
256
+ Known rules (RuleDefinition), listed as commented examples.
257
+
258
+ Returns
259
+ ----------
260
+ str
261
+ The file content.
262
+ """
263
+ lines: list[str] = [
264
+ "# JCCS project configuration (read with jarbin-toolkit-config).",
265
+ "# Generated by JCCS when the .JCCS directory was created; edit it freely.",
266
+ "# An empty value means \"not set\": the documented default applies.",
267
+ "# Lists: one item per indented line, or comma-separated on one line.",
268
+ "# Write a literal % as %% (configparser syntax).",
269
+ "",
270
+ ]
271
+ for section, specs in FIXED_SECTIONS.items():
272
+ lines.append(f"[{section}]")
273
+ for spec in specs:
274
+ lines.extend(_comment_block(spec.description))
275
+ if spec.choices:
276
+ lines.append("# One of: " + ", ".join(spec.choices) + ".")
277
+ lines.append(f"{spec.name} = {_default_text(spec)}".rstrip() if _default_text(spec) else f"{spec.name} =")
278
+ lines.append("")
279
+ lines.extend([
280
+ "# Per-rule settings. Uncomment a block to change a rule. Universal keys:",
281
+ "# enabled = true|false, severity = info|minor|major|fatal, include = <globs>, exclude = <globs>,",
282
+ "# check.<check_id>.enabled = true|false, check.<check_id>.severity = <level>,",
283
+ "# plus the rule arguments listed with their default values.",
284
+ "",
285
+ ])
286
+ for rule in rules:
287
+ lines.append(f"# [rule:{rule.id}]")
288
+ lines.append(f"# ({rule.code}, {rule.severity}, {rule.status}) {rule.title}")
289
+ for name, spec in rule.arguments.items():
290
+ lines.append(f"# {name} = {_default_text(spec)}".rstrip())
291
+ lines.append("")
292
+ lines.extend([
293
+ "# Path-scoped overrides: [override:<glob>] with enable / disable selectors. Example:",
294
+ "# [override:tests/**]",
295
+ "# disable = functions",
296
+ "",
297
+ ])
298
+ return "\n".join(lines)
299
+
300
+
301
+ def _upgrade_gitignore(path: Path) -> None:
302
+ """
303
+ Add the entries of PROJECT_GITIGNORE missing from a `.JCCS/.gitignore` generated by an older JCCS. A file
304
+ that does not start with the generated header was written by the user and is left untouched.
305
+
306
+ Parameters
307
+ ----------
308
+ path : Path
309
+ The `.JCCS/.gitignore` file.
310
+
311
+ Returns
312
+ ----------
313
+ None
314
+ Nothing.
315
+
316
+ Raises
317
+ ----------
318
+ OSError
319
+ The file cannot be read or written.
320
+ """
321
+ text: str = path.read_text(encoding="utf-8")
322
+ if not text.startswith(PROJECT_GITIGNORE_HEADER):
323
+ return
324
+ present: set[str] = {line.strip() for line in text.splitlines()}
325
+ missing: list[str] = [line for line in PROJECT_GITIGNORE.splitlines()[1:] if line not in present]
326
+ if missing:
327
+ separator: str = "" if text.endswith("\n") else "\n"
328
+ path.write_text(text + separator + "".join(f"{line}\n" for line in missing), encoding="utf-8")
329
+
330
+
331
+ def ensure_project_directory(root: Path, rules: Iterable[Any] = ()) -> Path:
332
+ """
333
+ Create the `.JCCS` directory of a project when it does not exist yet: config file (with every key),
334
+ custom rules directory and `.gitignore`. An existing directory is used as is (missing parts are added,
335
+ nothing is overwritten).
336
+
337
+ Parameters
338
+ ----------
339
+ root : Path
340
+ Project root.
341
+ rules : Iterable[Any]
342
+ Known rules, listed as commented examples in a new config file.
343
+
344
+ Returns
345
+ ----------
346
+ Path
347
+ The JCCS directory.
348
+
349
+ Raises
350
+ ----------
351
+ ProjectEnvironmentError
352
+ The directory or its files cannot be created.
353
+ """
354
+ directory: Path = root / PROJECT_DIRECTORY_NAME
355
+ try:
356
+ directory.mkdir(exist_ok=True)
357
+ (directory / "rules").mkdir(exist_ok=True)
358
+ config_path: Path = directory / CONFIG_FILE_NAME
359
+ if not config_path.exists():
360
+ config_path.write_text(render_config_template(rules), encoding="utf-8")
361
+ gitignore: Path = directory / ".gitignore"
362
+ if not gitignore.exists():
363
+ gitignore.write_text(PROJECT_GITIGNORE, encoding="utf-8")
364
+ else:
365
+ _upgrade_gitignore(gitignore)
366
+ except OSError as error:
367
+ raise ProjectEnvironmentError(f"Cannot create the JCCS directory '{directory}': {error.strerror}.") from None
368
+ return directory
369
+
370
+
371
+ class _ConfigReader:
372
+ """
373
+ Typed access to a `.jccs.ini` opened with jarbin-toolkit-config.
374
+
375
+ Attributes
376
+ ----------
377
+ path : str
378
+ Config file, for messages.
379
+ parser : ConfigParser
380
+ Parser holding the file content.
381
+ """
382
+
383
+ def __init__(self, path: str, parser: ConfigParser) -> None:
384
+ """
385
+ Wrap a parsed config.
386
+
387
+ Parameters
388
+ ----------
389
+ path : str
390
+ Config file, for messages.
391
+ parser : ConfigParser
392
+ Parser holding the file content.
393
+
394
+ Returns
395
+ ----------
396
+ None
397
+ Nothing.
398
+ """
399
+ self.path: str = path
400
+ self.parser: ConfigParser = parser
401
+
402
+ def raw(self, section: str, key: str) -> str | None:
403
+ """
404
+ Raw value of a key (no interpolation), None when absent or empty.
405
+
406
+ Parameters
407
+ ----------
408
+ section : str
409
+ Section name.
410
+ key : str
411
+ Key.
412
+
413
+ Returns
414
+ ----------
415
+ str | None
416
+ The value.
417
+ """
418
+ if not self.parser.has_option(section, key):
419
+ return None
420
+ value: str = self.parser.get(section, key, raw=True).strip()
421
+ return value or None
422
+
423
+ def typed(self, section: str, spec: ArgumentSpec, key: str | None = None) -> Any:
424
+ """
425
+ Typed value of a key, or the spec default when absent or empty.
426
+
427
+ Parameters
428
+ ----------
429
+ section : str
430
+ Section name.
431
+ spec : ArgumentSpec
432
+ Type of the value.
433
+ key : str | None
434
+ Key (default: the spec name).
435
+
436
+ Returns
437
+ ----------
438
+ Any
439
+ The value.
440
+
441
+ Raises
442
+ ----------
443
+ ProjectConfigError
444
+ The value does not match the type.
445
+ """
446
+ name: str = key or spec.name
447
+ raw: str | None = self.raw(section, name)
448
+ if raw is None:
449
+ return spec.default
450
+ try:
451
+ return spec.coerce(raw)
452
+ except ValueConversionError as error:
453
+ raise ProjectConfigError(f"Invalid value '{error.raw}' for '{name}' in [{section}]: {error.reason}.", path=self.path) from None
454
+
455
+ def check_keys(self, section: str, allowed: Iterable[str]) -> None:
456
+ """
457
+ Reject unknown keys of a section (CFG-05).
458
+
459
+ Parameters
460
+ ----------
461
+ section : str
462
+ Section name.
463
+ allowed : Iterable[str]
464
+ Accepted keys.
465
+
466
+ Returns
467
+ ----------
468
+ None
469
+ Nothing.
470
+
471
+ Raises
472
+ ----------
473
+ ProjectConfigError
474
+ A key is unknown.
475
+ """
476
+ known: list[str] = sorted(allowed)
477
+ for key in self.parser.options(section):
478
+ if key not in known:
479
+ matches: list[str] = difflib.get_close_matches(key, known, n=1)
480
+ raise ProjectConfigError(
481
+ f"Unknown key '{key}' in [{section}].",
482
+ f"Did you mean '{matches[0]}'?" if matches else None,
483
+ path=self.path,
484
+ )
485
+
486
+
487
+ def _read_rule_settings(reader: _ConfigReader, section: str) -> RuleSettings:
488
+ """
489
+ Read one `[rule:<id>]` section. Arguments stay raw: their types are known only from the rule.
490
+
491
+ Parameters
492
+ ----------
493
+ reader : _ConfigReader
494
+ The config.
495
+ section : str
496
+ Section name.
497
+
498
+ Returns
499
+ ----------
500
+ RuleSettings
501
+ The settings.
502
+
503
+ Raises
504
+ ----------
505
+ ProjectConfigError
506
+ A universal key has an invalid value, or a `check.*` key is malformed.
507
+ """
508
+ universal: dict[str, ArgumentSpec] = {spec.name: spec for spec in RULE_SETTING_KEYS}
509
+ check_specs: dict[str, ArgumentSpec] = {spec.name: spec for spec in CHECK_SETTING_KEYS}
510
+ check_enabled: dict[str, bool] = {}
511
+ check_severity: dict[str, SeverityLevel] = {}
512
+ arguments: dict[str, str] = {}
513
+ for key in reader.parser.options(section):
514
+ if key in universal:
515
+ continue
516
+ if key.startswith(CHECK_KEY_PREFIX):
517
+ parts: list[str] = key.split(".")
518
+ if len(parts) != 3 or parts[2] not in check_specs:
519
+ raise ProjectConfigError(
520
+ f"Invalid key '{key}' in [{section}].", "Expected check.<check_id>.enabled or check.<check_id>.severity.", path=reader.path,
521
+ )
522
+ value: Any = reader.typed(section, check_specs[parts[2]], key)
523
+ if value is None:
524
+ continue
525
+ if parts[2] == "enabled":
526
+ check_enabled[parts[1]] = value
527
+ else:
528
+ check_severity[parts[1]] = SeverityLevel(value)
529
+ continue
530
+ raw: str | None = reader.raw(section, key)
531
+ if raw is not None:
532
+ arguments[key] = raw
533
+ severity: str | None = reader.typed(section, universal["severity"])
534
+ return RuleSettings(
535
+ rule_id=section[len(RULE_SECTION_PREFIX):],
536
+ enabled=reader.typed(section, universal["enabled"]),
537
+ severity=SeverityLevel(severity) if severity else None,
538
+ include=reader.typed(section, universal["include"]),
539
+ exclude=reader.typed(section, universal["exclude"]),
540
+ check_enabled=MappingProxyType(check_enabled),
541
+ check_severity=MappingProxyType(check_severity),
542
+ arguments=MappingProxyType(arguments),
543
+ )
544
+
545
+
546
+ def _open_config(path: Path) -> ConfigParser:
547
+ """
548
+ Open a project config file with jarbin-toolkit-config and return the underlying parser (the toolkit has
549
+ no public way to list sections and keys, which unknown-key detection needs).
550
+
551
+ Parameters
552
+ ----------
553
+ path : Path
554
+ The config file (`.ini` extension optional).
555
+
556
+ Returns
557
+ ----------
558
+ ConfigParser
559
+ The parsed file.
560
+
561
+ Raises
562
+ ----------
563
+ ProjectConfigError
564
+ The file is not valid INI.
565
+ ProjectEnvironmentError
566
+ The file cannot be read.
567
+ """
568
+ has_extension: bool = path.suffix == ".ini"
569
+ try:
570
+ config: Config = Config.open(path.parent, path.stem if has_extension else path.name, has_extension=has_extension)
571
+ except ConfigParserError as error:
572
+ raise ProjectConfigError(f"Invalid INI syntax: {error}", path=str(path)) from None
573
+ except (ConfigFileNotFoundJError, ConfigRuntimeJError, OSError) as error:
574
+ raise ProjectEnvironmentError(f"Cannot read '{path}': {error}") from None
575
+ except JException as error:
576
+ raise ProjectEnvironmentError(f"Cannot read '{path}': {error}") from None
577
+ return config._config
578
+
579
+
580
+ def load_project_config(directory: Path | None) -> ProjectConfig:
581
+ """
582
+ Load `.JCCS/.jccs.ini`. Without directory or file, the defaults apply.
583
+
584
+ Parameters
585
+ ----------
586
+ directory : Path | None
587
+ JCCS directory.
588
+
589
+ Returns
590
+ ----------
591
+ ProjectConfig
592
+ The configuration.
593
+
594
+ Raises
595
+ ----------
596
+ ProjectConfigError
597
+ The file has an unknown section or key, or an invalid value.
598
+ ProjectEnvironmentError
599
+ The file cannot be read.
600
+ """
601
+ if directory is None or not (directory / CONFIG_FILE_NAME).is_file():
602
+ return ProjectConfig(directory=directory)
603
+ return load_project_config_file(directory / CONFIG_FILE_NAME)
604
+
605
+
606
+ def resolve_config_argument(argument: Path) -> Path:
607
+ """
608
+ Config file named by `--config`: the file itself, or `.jccs.ini` inside a directory (a `.JCCS` directory,
609
+ or a project root holding one).
610
+
611
+ Parameters
612
+ ----------
613
+ argument : Path
614
+ Value of `--config`.
615
+
616
+ Returns
617
+ ----------
618
+ Path
619
+ The config file.
620
+
621
+ Raises
622
+ ----------
623
+ ProjectEnvironmentError
624
+ No config file exists there.
625
+ """
626
+ candidates: list[Path] = [argument] if not argument.is_dir() else [argument / CONFIG_FILE_NAME, argument / PROJECT_DIRECTORY_NAME / CONFIG_FILE_NAME]
627
+ for candidate in candidates:
628
+ if candidate.is_file():
629
+ return candidate
630
+ raise ProjectEnvironmentError(f"No config file at '{argument}'.")
631
+
632
+
633
+ def load_project_config_file(config_file: Path) -> ProjectConfig:
634
+ """
635
+ Load a project config file. Relative paths it holds (custom rules directory) are resolved against the
636
+ directory of the file.
637
+
638
+ Parameters
639
+ ----------
640
+ config_file : Path
641
+ The config file.
642
+
643
+ Returns
644
+ ----------
645
+ ProjectConfig
646
+ The configuration.
647
+
648
+ Raises
649
+ ----------
650
+ ProjectConfigError
651
+ The file has an unknown section or key, or an invalid value.
652
+ ProjectEnvironmentError
653
+ The file cannot be read.
654
+ """
655
+ directory: Path = config_file.parent
656
+ path: str = str(config_file)
657
+ reader: _ConfigReader = _ConfigReader(path, _open_config(config_file))
658
+ rules: dict[str, RuleSettings] = {}
659
+ overrides: list[PathOverride] = []
660
+ for section in reader.parser.sections():
661
+ if section in FIXED_SECTIONS:
662
+ reader.check_keys(section, (spec.name for spec in FIXED_SECTIONS[section]))
663
+ elif section.startswith(RULE_SECTION_PREFIX) and len(section) > len(RULE_SECTION_PREFIX):
664
+ rules[section[len(RULE_SECTION_PREFIX):]] = _read_rule_settings(reader, section)
665
+ elif section.startswith(OVERRIDE_SECTION_PREFIX) and len(section) > len(OVERRIDE_SECTION_PREFIX):
666
+ reader.check_keys(section, (spec.name for spec in OVERRIDE_KEYS))
667
+ overrides.append(PathOverride(
668
+ glob=section[len(OVERRIDE_SECTION_PREFIX):],
669
+ enable=reader.typed(section, OVERRIDE_KEYS[0]),
670
+ disable=reader.typed(section, OVERRIDE_KEYS[1]),
671
+ ))
672
+ else:
673
+ known: list[str] = [*FIXED_SECTIONS, "rule:<id>", "override:<glob>"]
674
+ raise ProjectConfigError(f"Unknown section [{section}].", "Expected one of: " + ", ".join(f"[{name}]" for name in known) + ".", path=path)
675
+ values: dict[str, Any] = {spec.name: reader.typed("jccs", spec) for spec in JCCS_KEYS}
676
+ min_version: str = values["min_jccs_version"]
677
+ if min_version:
678
+ try:
679
+ compatible: bool = check_constraint(f">={min_version}", PROGRAM_VERSION)
680
+ except ValueError as error:
681
+ raise ProjectConfigError(f"Invalid min_jccs_version: {error}.", path=path) from None
682
+ if not compatible:
683
+ raise ProjectConfigError(f"This project needs JCCS {min_version} or newer (running {PROGRAM_VERSION}).", "Update JCCS.", path=path)
684
+ return ProjectConfig(
685
+ source=path,
686
+ directory=directory,
687
+ version=values["version"],
688
+ min_jccs_version=min_version,
689
+ include=values["include"],
690
+ exclude=values["exclude"],
691
+ max_file_size=values["max_file_size"],
692
+ use_gitignore=values["use_gitignore"],
693
+ fail_on=SeverityLevel(values["fail_on"]),
694
+ max_errors=values["max_errors"],
695
+ strict_heuristics=values["strict_heuristics"],
696
+ rules_dir=reader.typed("paths", PATHS_KEYS[0]),
697
+ enable=reader.typed("rules", RULES_KEYS[0]),
698
+ disable=reader.typed("rules", RULES_KEYS[1]),
699
+ rules=MappingProxyType(rules),
700
+ overrides=tuple(overrides),
701
+ )
702
+
703
+
704
+ def project_paths(cwd: Path) -> list[tuple[str, Path]]:
705
+ """
706
+ Directories and files JCCS uses for the project of a directory (`--paths`, `info --config-path`).
707
+
708
+ Parameters
709
+ ----------
710
+ cwd : Path
711
+ Directory inside the project.
712
+
713
+ Returns
714
+ ----------
715
+ list[tuple[str, Path]]
716
+ (name, path) entries.
717
+
718
+ Raises
719
+ ----------
720
+ ProjectConfigError
721
+ The project config is invalid.
722
+ """
723
+ root: Path = find_project_root(cwd)
724
+ directory: Path = root / PROJECT_DIRECTORY_NAME
725
+ config = load_project_config(directory if directory.is_dir() else None)
726
+ custom: Path = config.custom_rules_directory or directory / "rules"
727
+ return [
728
+ ("root", root),
729
+ ("jccs_directory", directory),
730
+ ("config", directory / CONFIG_FILE_NAME),
731
+ ("custom_rules", custom),
732
+ ("builtin_rules", BUILTIN_RULES_DIRECTORY),
733
+ ("logs", directory / "logs"),
734
+ ("fix_journal", directory / "fix-journal"),
735
+ ]