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
File without changes
@@ -0,0 +1,45 @@
1
+ from sources.cli.arguments import CommandSpec
2
+ from sources.cli.context import ParsedArguments
3
+ from sources.constants import INFO_COMMAND
4
+ from sources.enums import ExitCode
5
+ from sources.services import Services
6
+ from sources.subcommands.base import Command
7
+
8
+
9
+ class InfoCommand(Command):
10
+ """
11
+ `jccs info`: program and environment information (plan 02, section 6).
12
+ (ABC -> Command)
13
+
14
+ Attributes
15
+ ----------
16
+ spec : CommandSpec
17
+ INFO_COMMAND.
18
+ """
19
+
20
+ spec: CommandSpec = INFO_COMMAND
21
+
22
+ def run(self, arguments: ParsedArguments, services: Services) -> ExitCode:
23
+ """
24
+ Run the command (see sources.subcommands.info.handler).
25
+
26
+ Parameters
27
+ ----------
28
+ arguments : ParsedArguments
29
+ Parsed command line.
30
+ services : Services
31
+ Process seams.
32
+
33
+ Returns
34
+ ----------
35
+ ExitCode
36
+ The exit code.
37
+
38
+ Raises
39
+ ----------
40
+ JccsError
41
+ Any error to report to the user.
42
+ """
43
+ from sources.subcommands.info.handler import run_info
44
+
45
+ return run_info(arguments, services)
@@ -0,0 +1,527 @@
1
+ import json
2
+ import shutil
3
+ import sys
4
+ from collections.abc import Callable
5
+ from dataclasses import dataclass
6
+ from importlib import metadata
7
+ from pathlib import Path
8
+ from typing import Any
9
+
10
+ from sources.cli.context import CommandArguments, ParsedArguments
11
+ from sources.constants import (
12
+ MINIMUM_PYTHON,
13
+ PROGRAM_AUTHOR,
14
+ PROGRAM_CONTACT,
15
+ PROGRAM_LICENSE,
16
+ PROGRAM_LICENSE_URL,
17
+ PROGRAM_NAME,
18
+ PROGRAM_URL,
19
+ PROGRAM_VERSION,
20
+ RUNTIME_DEPENDENCIES,
21
+ )
22
+ from sources.enums import ExitCode
23
+ from sources.errors.exceptions import JccsError
24
+ from sources.services import Services
25
+ from sources.utils.build_info import INSTALL_ROOT, collect_build_info
26
+
27
+
28
+ # Version of the `info --json` / `--plain` output contract (plan 02, section 6).
29
+ INFO_SCHEMA_VERSION: int = 1
30
+
31
+ # Versions of the `check --format json` report contract this program writes (plan 08, section 8).
32
+ REPORT_SCHEMA_VERSIONS: tuple[int, ...] = (1,)
33
+
34
+ # JSON Schema of the `check --format json` report (plan 08, section 4).
35
+ REPORT_SCHEMA_FILE: Path = INSTALL_ROOT / "sources" / "outputs" / "json" / "report.schema.json"
36
+
37
+ # License file of the installation.
38
+ LICENSE_FILE: Path = INSTALL_ROOT / "LICENSE"
39
+
40
+ # Query flags of `info`, in display order (mutually exclusive).
41
+ QUERY_FLAGS: tuple[str, ...] = ("version", "author", "contact", "build", "rules_count", "schema", "config_path", "check_env", "license")
42
+
43
+ # Keys of the full `info --json` object, in order.
44
+ SUMMARY_KEYS: tuple[str, ...] = ("version", "author", "contact", "build", "rules_count", "config_path", "license")
45
+
46
+ # Status of an environment check.
47
+ STATUS_OK: str = "ok"
48
+ STATUS_WARN: str = "warn"
49
+ STATUS_FAIL: str = "fail"
50
+
51
+ # License notice printed by `info --license`.
52
+ LICENSE_NOTICE: str = (
53
+ "This program is free software: you can redistribute it and/or modify it under the terms of the GNU General "
54
+ "Public License as published by the Free Software Foundation, either version 3 of the License, or (at your "
55
+ "option) any later version. It comes with ABSOLUTELY NO WARRANTY."
56
+ )
57
+
58
+
59
+ @dataclass(frozen=True, slots=True)
60
+ class EnvironmentCheck:
61
+ """
62
+ One line of `info --check-env`.
63
+ (dataclass)
64
+
65
+ Attributes
66
+ ----------
67
+ name : str
68
+ What is checked.
69
+ status : str
70
+ "ok", "warn" (does not change the exit code) or "fail" (exit 4).
71
+ detail : str
72
+ What was found.
73
+ """
74
+
75
+ name: str
76
+ status: str
77
+ detail: str
78
+
79
+
80
+ def _rules_count(services: Services) -> dict[str, int]:
81
+ """
82
+ Counts of the rule catalog of the project (built-in rules plus its custom rules).
83
+
84
+ Parameters
85
+ ----------
86
+ services : Services
87
+ Process seams (working directory).
88
+
89
+ Returns
90
+ ----------
91
+ dict[str, int]
92
+ categories, rules, builtin, custom, checks, fixable_checks.
93
+
94
+ Raises
95
+ ----------
96
+ JccsError
97
+ Invalid project config or custom rule.
98
+ """
99
+ from sources.configs.project import PROJECT_DIRECTORY_NAME, find_project_root, load_project_config
100
+ from sources.rules.catalog import RuleCatalog
101
+
102
+ directory: Path = find_project_root(services.cwd) / PROJECT_DIRECTORY_NAME
103
+ config = load_project_config(directory if directory.is_dir() else None)
104
+ custom: Path | None = config.custom_rules_directory
105
+ catalog = RuleCatalog.load([custom]) if custom is not None and custom.is_dir() else RuleCatalog.load()
106
+ rules = list(catalog.rules.values())
107
+ return {
108
+ "categories": len({rule.category for rule in rules}),
109
+ "rules": len(rules),
110
+ "builtin": sum(1 for rule in rules if rule.builtin),
111
+ "custom": sum(1 for rule in rules if not rule.builtin),
112
+ "checks": sum(len(rule.checks) for rule in rules),
113
+ "fixable_checks": sum(1 for rule in rules for check in rule.checks if check.fix_kind),
114
+ }
115
+
116
+
117
+ def _config_path(services: Services) -> dict[str, str]:
118
+ """
119
+ Paths JCCS uses for the project of the working directory (same entries as `jccs --paths`).
120
+
121
+ Parameters
122
+ ----------
123
+ services : Services
124
+ Process seams.
125
+
126
+ Returns
127
+ ----------
128
+ dict[str, str]
129
+ Path by name.
130
+
131
+ Raises
132
+ ----------
133
+ JccsError
134
+ Invalid project config.
135
+ """
136
+ from sources.configs.project import project_paths
137
+
138
+ return {name: str(path) for name, path in project_paths(services.cwd)}
139
+
140
+
141
+ def _license() -> dict[str, str | None]:
142
+ """
143
+ License information.
144
+
145
+ Returns
146
+ ----------
147
+ dict[str, str | None]
148
+ SPDX identifier, URL of the text, local license file.
149
+ """
150
+ return {"spdx": PROGRAM_LICENSE, "url": PROGRAM_LICENSE_URL, "file": str(LICENSE_FILE) if LICENSE_FILE.is_file() else None}
151
+
152
+
153
+ def _value(name: str, services: Services) -> Any:
154
+ """
155
+ Value of one `info` key.
156
+
157
+ Parameters
158
+ ----------
159
+ name : str
160
+ Key (a query flag name).
161
+ services : Services
162
+ Process seams.
163
+
164
+ Returns
165
+ ----------
166
+ Any
167
+ The value (JSON-compatible).
168
+ """
169
+ getters: dict[str, Callable[[], Any]] = {
170
+ "version": lambda: PROGRAM_VERSION,
171
+ "author": lambda: PROGRAM_AUTHOR,
172
+ "contact": lambda: PROGRAM_CONTACT,
173
+ "build": lambda: collect_build_info().as_dict(),
174
+ "rules_count": lambda: _rules_count(services),
175
+ "config_path": lambda: _config_path(services),
176
+ "license": _license,
177
+ }
178
+ return getters[name]()
179
+
180
+
181
+ def _summary(services: Services) -> dict[str, Any]:
182
+ """
183
+ Full `info` object. Keys that depend on the project (rules, paths) are null when the project config or
184
+ a custom rule is invalid, so the summary always works.
185
+
186
+ Parameters
187
+ ----------
188
+ services : Services
189
+ Process seams.
190
+
191
+ Returns
192
+ ----------
193
+ dict[str, Any]
194
+ The object (fixed key order).
195
+ """
196
+ data: dict[str, Any] = {"schema_version": INFO_SCHEMA_VERSION, "name": PROGRAM_NAME, "url": PROGRAM_URL}
197
+ for key in SUMMARY_KEYS:
198
+ try:
199
+ data[key] = _value(key, services)
200
+ except JccsError:
201
+ data[key] = None
202
+ data["report_schema_versions"] = list(REPORT_SCHEMA_VERSIONS)
203
+ return data
204
+
205
+
206
+ def environment_checks(services: Services, *, dependencies: dict[str, str] = RUNTIME_DEPENDENCIES) -> list[EnvironmentCheck]:
207
+ """
208
+ Preflight checks of `info --check-env` (plan 08, section 8): Python version, pinned dependencies and the
209
+ built-in rule catalog must be right (fail); git and the project config only warn.
210
+
211
+ Parameters
212
+ ----------
213
+ services : Services
214
+ Process seams.
215
+ dependencies : dict[str, str]
216
+ Distribution name -> required version.
217
+
218
+ Returns
219
+ ----------
220
+ list[EnvironmentCheck]
221
+ One entry per check, in a fixed order.
222
+ """
223
+ checks: list[EnvironmentCheck] = []
224
+ current: str = ".".join(str(part) for part in sys.version_info[:3])
225
+ minimum: str = ".".join(str(part) for part in MINIMUM_PYTHON)
226
+ checks.append(EnvironmentCheck("python", STATUS_OK if sys.version_info[:2] >= MINIMUM_PYTHON else STATUS_FAIL, f"{current} (>= {minimum} required)"))
227
+ for name, required in dependencies.items():
228
+ try:
229
+ installed: str = metadata.version(name)
230
+ except metadata.PackageNotFoundError:
231
+ checks.append(EnvironmentCheck(name, STATUS_FAIL, f"not installed ({required} required)"))
232
+ continue
233
+ status: str = STATUS_OK if installed == required else STATUS_FAIL
234
+ checks.append(EnvironmentCheck(name, status, installed if status == STATUS_OK else f"{installed} installed, {required} required"))
235
+ try:
236
+ from sources.rules.catalog import RuleCatalog
237
+
238
+ catalog = RuleCatalog.load()
239
+ checks.append(EnvironmentCheck("builtin_rules", STATUS_OK, f"{len(catalog.rules)} rules load"))
240
+ except Exception as error: # noqa: BLE001 - any failure to load the built-in rules is the finding
241
+ checks.append(EnvironmentCheck("builtin_rules", STATUS_FAIL, str(error).splitlines()[0] if str(error) else type(error).__name__))
242
+ git: str | None = shutil.which("git", path=services.env.get("PATH"))
243
+ checks.append(EnvironmentCheck("git", STATUS_OK, git) if git else EnvironmentCheck("git", STATUS_WARN, "not found (.gitignore support and git build info disabled)"))
244
+ try:
245
+ counts: dict[str, int] = _rules_count(services)
246
+ paths: dict[str, str] = _config_path(services)
247
+ checks.append(EnvironmentCheck("project", STATUS_OK, f"{paths['root']} ({counts['custom']} custom rule(s))"))
248
+ except JccsError as error:
249
+ checks.append(EnvironmentCheck("project", STATUS_WARN, str(error.args[0]).splitlines()[0] if error.args else type(error).__name__))
250
+ return checks
251
+
252
+
253
+ def _flatten(prefix: str, value: Any) -> list[tuple[str, str]]:
254
+ """
255
+ `key=value` records of a value, nested keys joined with dots.
256
+
257
+ Parameters
258
+ ----------
259
+ prefix : str
260
+ Key of the value.
261
+ value : Any
262
+ The value.
263
+
264
+ Returns
265
+ ----------
266
+ list[tuple[str, str]]
267
+ (key, text) records.
268
+ """
269
+ if isinstance(value, dict):
270
+ records: list[tuple[str, str]] = []
271
+ for key, item in value.items():
272
+ records.extend(_flatten(f"{prefix}.{key}" if prefix else str(key), item))
273
+ return records
274
+ if isinstance(value, (list, tuple)):
275
+ return [(prefix, ",".join(str(item) for item in value))]
276
+ if isinstance(value, bool):
277
+ return [(prefix, "true" if value else "false")]
278
+ return [(prefix, "" if value is None else str(value).replace("\n", " "))]
279
+
280
+
281
+ def render_plain(data: dict[str, Any]) -> str:
282
+ """
283
+ `--plain`: one uncoloured `key=value` record per line.
284
+
285
+ Parameters
286
+ ----------
287
+ data : dict[str, Any]
288
+ The values.
289
+
290
+ Returns
291
+ ----------
292
+ str
293
+ The records.
294
+ """
295
+ return "\n".join(f"{key}={text}" for key, text in _flatten("", data)) + "\n"
296
+
297
+
298
+ def _build_line(build: dict[str, Any]) -> str:
299
+ """
300
+ One-line description of the build.
301
+
302
+ Parameters
303
+ ----------
304
+ build : dict[str, Any]
305
+ `build` value.
306
+
307
+ Returns
308
+ ----------
309
+ str
310
+ e.g. "git 1a2b3c4 (2026-12-02T10:00:00+01:00, dirty) - CPython 3.12.3 on Linux x86_64".
311
+ """
312
+ runtime: dict[str, str] = build["runtime"]
313
+ commit: str = build["commit"][:7] if build["commit"] != "unknown" else build["commit"]
314
+ details: list[str] = [build["date"]] + (["dirty"] if build["dirty"] else [])
315
+ origin: str = f"{build['source']} {build['version']}" if build["source"] != "git" else f"git {commit}"
316
+ return f"{origin} ({', '.join(details)}) - {runtime['implementation']} {runtime['python']} on {runtime['platform']}"
317
+
318
+
319
+ def _rules_line(counts: dict[str, int] | None) -> str:
320
+ """
321
+ One-line description of the rule catalog.
322
+
323
+ Parameters
324
+ ----------
325
+ counts : dict[str, int] | None
326
+ `rules_count` value.
327
+
328
+ Returns
329
+ ----------
330
+ str
331
+ The line.
332
+ """
333
+ if counts is None:
334
+ return "unavailable (invalid project config or custom rule)"
335
+ return (
336
+ f"{counts['rules']} rules in {counts['categories']} categories ({counts['builtin']} built-in, {counts['custom']} custom); "
337
+ f"{counts['checks']} checks, {counts['fixable_checks']} fixable"
338
+ )
339
+
340
+
341
+ class _Painter:
342
+ """
343
+ Optional colours of the human output (the styling library is imported only when colours are on).
344
+
345
+ Attributes
346
+ ----------
347
+ style : Any
348
+ Style adapter, or None.
349
+ """
350
+
351
+ def __init__(self, enabled: bool) -> None:
352
+ """
353
+ Create the painter.
354
+
355
+ Parameters
356
+ ----------
357
+ enabled : bool
358
+ Whether colours are used.
359
+
360
+ Returns
361
+ ----------
362
+ None
363
+ Nothing.
364
+ """
365
+ self.style: Any = None
366
+ if enabled:
367
+ from sources.outputs.terminal.style import Style
368
+
369
+ self.style = Style(True)
370
+
371
+ def paint(self, kind: str, text: str) -> str:
372
+ """
373
+ Colour a text.
374
+
375
+ Parameters
376
+ ----------
377
+ kind : str
378
+ Style method name (bold, success, failure, notice...).
379
+ text : str
380
+ The text.
381
+
382
+ Returns
383
+ ----------
384
+ str
385
+ The text, coloured when enabled.
386
+ """
387
+ return getattr(self.style, kind)(text) if self.style is not None else text
388
+
389
+
390
+ def render_human(query: str | None, value: Any, painter: _Painter) -> str:
391
+ """
392
+ Human output of `info` (no --json/--plain).
393
+
394
+ Parameters
395
+ ----------
396
+ query : str | None
397
+ Query flag, or None for the summary.
398
+ value : Any
399
+ Its value (the full object for the summary).
400
+ painter : _Painter
401
+ Colours.
402
+
403
+ Returns
404
+ ----------
405
+ str
406
+ The text, with a final newline.
407
+ """
408
+ if query in ("version", "author", "contact"):
409
+ return f"{value}\n"
410
+ if query == "build":
411
+ runtime: dict[str, str] = value["runtime"]
412
+ dirty: str = "unknown" if value["dirty"] is None else "yes" if value["dirty"] else "no"
413
+ rows: list[tuple[str, str]] = [
414
+ ("source", value["source"]), ("version", value["version"]), ("date", value["date"]), ("commit", value["commit"]),
415
+ ("dirty", dirty), ("runtime", f"{runtime['implementation']} {runtime['python']} on {runtime['platform']}"),
416
+ ]
417
+ return "".join(f"{painter.paint('bold', key + ':')} {text}\n" for key, text in rows)
418
+ if query == "rules_count":
419
+ return (
420
+ f"categories: {value['categories']}\nrules: {value['rules']} ({value['builtin']} built-in, {value['custom']} custom)\n"
421
+ f"checks: {value['checks']} ({value['fixable_checks']} fixable)\n"
422
+ )
423
+ if query == "config_path":
424
+ return "".join(f"{name}: {path}\n" for name, path in value.items())
425
+ if query == "license":
426
+ local: str = f"\nLicense file: {value['file']}" if value["file"] else ""
427
+ return f"{value['spdx']}\n{LICENSE_NOTICE}\nFull text: {value['url']}{local}\n"
428
+ build: str = _build_line(value["build"]) if value.get("build") else "unknown"
429
+ rows = [
430
+ ("Author", f"{value['author']} <{value['contact']}>"),
431
+ ("Home", value["url"]),
432
+ ("License", value["license"]["spdx"] if value.get("license") else PROGRAM_LICENSE),
433
+ ("Build", build),
434
+ ("Rules", _rules_line(value.get("rules_count"))),
435
+ ]
436
+ width: int = max(len(key) for key, _ in rows) + 1
437
+ lines: list[str] = [painter.paint("bold", f"{value['name']} {value['version']}")]
438
+ lines.extend(painter.paint("bold", (key + ":").ljust(width)) + f" {text}" for key, text in rows)
439
+ return "\n".join(lines) + "\n"
440
+
441
+
442
+ def _render_checks(checks: list[EnvironmentCheck], mode: str, painter: _Painter) -> str:
443
+ """
444
+ Output of `info --check-env`.
445
+
446
+ Parameters
447
+ ----------
448
+ checks : list[EnvironmentCheck]
449
+ The checks.
450
+ mode : str
451
+ "human", "plain" or "json".
452
+ painter : _Painter
453
+ Colours.
454
+
455
+ Returns
456
+ ----------
457
+ str
458
+ The text.
459
+ """
460
+ healthy: bool = all(check.status != STATUS_FAIL for check in checks)
461
+ if mode == "json":
462
+ payload: dict[str, Any] = {
463
+ "schema_version": INFO_SCHEMA_VERSION,
464
+ "check_env": {"healthy": healthy, "checks": [{"name": check.name, "status": check.status, "detail": check.detail} for check in checks]},
465
+ }
466
+ return json.dumps(payload, indent=2, ensure_ascii=False) + "\n"
467
+ if mode == "plain":
468
+ records: list[str] = [f"check_env.{check.name}={check.status} {check.detail}" for check in checks]
469
+ return "\n".join(records + [f"check_env.healthy={'true' if healthy else 'false'}"]) + "\n"
470
+ colours: dict[str, str] = {STATUS_OK: "success", STATUS_WARN: "notice", STATUS_FAIL: "failure"}
471
+ width: int = max(len(check.name) for check in checks)
472
+ lines: list[str] = [f" {painter.paint(colours[check.status], f'{check.status:<4}')} {check.name:<{width}} {check.detail}" for check in checks]
473
+ problems: int = sum(1 for check in checks if check.status == STATUS_FAIL)
474
+ verdict: str = painter.paint("success", "healthy") if healthy else painter.paint("failure", f"broken ({problems} problem(s))")
475
+ return "\n".join(lines + [f"Environment: {verdict}"]) + "\n"
476
+
477
+
478
+ def run_info(arguments: ParsedArguments, services: Services) -> ExitCode:
479
+ """
480
+ `jccs info` (plan 02, section 6): one query flag at most (`--version`, `--author`, `--contact`, `--build`,
481
+ `--rules-count`, `--schema`, `--config-path`, `--check-env`, `--license`), or a summary; `--json` for a
482
+ JSON object (`schema_version` included), `--plain` for `key=value` records. Never imports the engine.
483
+
484
+ Parameters
485
+ ----------
486
+ arguments : ParsedArguments
487
+ Parsed command line.
488
+ services : Services
489
+ Process seams.
490
+
491
+ Returns
492
+ ----------
493
+ ExitCode
494
+ OK, or ENVIRONMENT when `--check-env` finds a problem.
495
+
496
+ Raises
497
+ ----------
498
+ JccsError
499
+ Invalid project config (`--rules-count`, `--config-path`).
500
+ """
501
+ flags: CommandArguments = arguments.command
502
+ query: str | None = next((name for name in QUERY_FLAGS if flags[name].is_called), None)
503
+ mode: str = "json" if flags["json"].is_called else "plain" if flags["plain"].is_called else "human"
504
+ painter: _Painter = _Painter(mode == "human" and services.color_enabled(services.stdout, disabled=bool(arguments.value("no_color"))))
505
+ if query == "schema":
506
+ schema: Any = json.loads(REPORT_SCHEMA_FILE.read_text(encoding="utf-8"))
507
+ services.stdout.write(json.dumps(schema, ensure_ascii=False, separators=(",", ":")) + "\n" if mode == "plain" else json.dumps(schema, indent=2, ensure_ascii=False) + "\n")
508
+ return ExitCode.OK
509
+ if query == "check_env":
510
+ checks: list[EnvironmentCheck] = environment_checks(services)
511
+ services.stdout.write(_render_checks(checks, mode, painter))
512
+ return ExitCode.ENVIRONMENT if any(check.status == STATUS_FAIL for check in checks) else ExitCode.OK
513
+ data: dict[str, Any]
514
+ if query is None:
515
+ data = _summary(services)
516
+ value: Any = data
517
+ else:
518
+ value = _value(query, services)
519
+ data = {"schema_version": INFO_SCHEMA_VERSION, query: value}
520
+ if mode == "json":
521
+ services.stdout.write(json.dumps(data, indent=2, ensure_ascii=False) + "\n")
522
+ elif mode == "plain":
523
+ services.stdout.write(render_plain(data if query is None else {query: value}))
524
+ else:
525
+ services.stdout.write(render_human(query, value, painter))
526
+ return ExitCode.OK
527
+
@@ -0,0 +1,37 @@
1
+ from importlib import import_module
2
+ from types import MappingProxyType
3
+
4
+ from sources.subcommands.base import Command
5
+
6
+
7
+ # Implementation of each available subcommand, as "module:Class"; modules are imported only when the
8
+ # subcommand runs, so `--help` and `--version` never load the engine (plan 01, P8).
9
+ COMMANDS: MappingProxyType[str, str] = MappingProxyType({
10
+ "check": "sources.subcommands.check.command:CheckCommand",
11
+ "rule": "sources.subcommands.rule.command:RuleCommand",
12
+ "info": "sources.subcommands.info.command:InfoCommand",
13
+ "test": "sources.subcommands.test.command:TestCommand",
14
+ "update": "sources.subcommands.update.command:UpdateCommand",
15
+ })
16
+
17
+
18
+ def load_command(name: str) -> Command | None:
19
+ """
20
+ Instantiate the implementation of a subcommand.
21
+
22
+ Parameters
23
+ ----------
24
+ name : str
25
+ Subcommand name.
26
+
27
+ Returns
28
+ ----------
29
+ Command | None
30
+ The command, or None when the subcommand is not implemented yet.
31
+ """
32
+ target: str | None = COMMANDS.get(name)
33
+ if target is None:
34
+ return None
35
+ module_name, _, class_name = target.partition(":")
36
+ command_class: type[Command] = getattr(import_module(module_name), class_name)
37
+ return command_class()
File without changes
@@ -0,0 +1,45 @@
1
+ from sources.cli.arguments import CommandSpec
2
+ from sources.cli.context import ParsedArguments
3
+ from sources.constants import RULE_COMMAND
4
+ from sources.enums import ExitCode
5
+ from sources.services import Services
6
+ from sources.subcommands.base import Command
7
+
8
+
9
+ class RuleCommand(Command):
10
+ """
11
+ `jccs rule`: manage and inspect rules.
12
+ (ABC -> Command)
13
+
14
+ Attributes
15
+ ----------
16
+ spec : CommandSpec
17
+ RULE_COMMAND.
18
+ """
19
+
20
+ spec: CommandSpec = RULE_COMMAND
21
+
22
+ def run(self, arguments: ParsedArguments, services: Services) -> ExitCode:
23
+ """
24
+ Run the selected action (see sources.subcommands.rule.handler).
25
+
26
+ Parameters
27
+ ----------
28
+ arguments : ParsedArguments
29
+ Parsed command line.
30
+ services : Services
31
+ Process seams.
32
+
33
+ Returns
34
+ ----------
35
+ ExitCode
36
+ The exit code.
37
+
38
+ Raises
39
+ ----------
40
+ JccsError
41
+ Any error to report to the user.
42
+ """
43
+ from sources.subcommands.rule.handler import run_rule
44
+
45
+ return run_rule(arguments, services)