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,224 @@
1
+ import os
2
+ import tempfile
3
+ from collections import Counter
4
+ from dataclasses import dataclass
5
+ from pathlib import Path
6
+
7
+ from sources.diagnostics.model import Diagnostic
8
+ from sources.engine.api import CheckReport
9
+ from sources.engine.outcome import counts_toward_failure
10
+ from sources.enums import SeverityLevel
11
+ from sources.errors.exceptions import ProjectEnvironmentError
12
+
13
+
14
+ # Severity names, from the most to the least severe (report order of the totals).
15
+ SEVERITY_ORDER: tuple[SeverityLevel, ...] = (SeverityLevel.FATAL, SeverityLevel.MAJOR, SeverityLevel.MINOR, SeverityLevel.INFO)
16
+
17
+
18
+ @dataclass(frozen=True, slots=True)
19
+ class ReportView:
20
+ """
21
+ Read-only view of a check report shared by every renderer: findings split from review items, display
22
+ codes and totals.
23
+ (dataclass)
24
+
25
+ Attributes
26
+ ----------
27
+ report : CheckReport
28
+ The report.
29
+ findings : tuple[Diagnostic, ...]
30
+ Diagnostics that are not review items, sorted.
31
+ review_items : tuple[Diagnostic, ...]
32
+ Heuristic findings and manual review items, sorted.
33
+ multi_check_rules : frozenset[str]
34
+ Rules that have several checks (their display code includes the check ID).
35
+ """
36
+
37
+ report: CheckReport
38
+ findings: tuple[Diagnostic, ...]
39
+ review_items: tuple[Diagnostic, ...]
40
+ multi_check_rules: frozenset[str]
41
+
42
+ @classmethod
43
+ def build(cls, report: CheckReport) -> "ReportView":
44
+ """
45
+ Build the view of a report.
46
+
47
+ Parameters
48
+ ----------
49
+ report : CheckReport
50
+ The report.
51
+
52
+ Returns
53
+ ----------
54
+ ReportView
55
+ The view.
56
+ """
57
+ diagnostics: tuple[Diagnostic, ...] = report.result.diagnostics
58
+ return cls(
59
+ report=report,
60
+ findings=tuple(item for item in diagnostics if not item.review),
61
+ review_items=tuple(item for item in diagnostics if item.review),
62
+ multi_check_rules=frozenset(rule.id for rule in report.catalog.rules.values() if len(rule.checks) > 1),
63
+ )
64
+
65
+ def code(self, diagnostic: Diagnostic) -> str:
66
+ """
67
+ Code shown for a diagnostic: the rule code, plus the check ID when the rule has several checks
68
+ (plan 03, section 3.1).
69
+
70
+ Parameters
71
+ ----------
72
+ diagnostic : Diagnostic
73
+ The diagnostic.
74
+
75
+ Returns
76
+ ----------
77
+ str
78
+ e.g. "C-F4" or "C-L1:assignment_in_condition".
79
+ """
80
+ if diagnostic.rule_id in self.multi_check_rules and diagnostic.check_id:
81
+ return f"{diagnostic.code}:{diagnostic.check_id}"
82
+ return diagnostic.code
83
+
84
+ @staticmethod
85
+ def message(diagnostic: Diagnostic) -> str:
86
+ """
87
+ Message of a diagnostic without the leading "<code>: " most rule templates start with.
88
+
89
+ Parameters
90
+ ----------
91
+ diagnostic : Diagnostic
92
+ The diagnostic.
93
+
94
+ Returns
95
+ ----------
96
+ str
97
+ The message.
98
+ """
99
+ prefix: str = f"{diagnostic.code}: "
100
+ return diagnostic.message[len(prefix):] if diagnostic.message.startswith(prefix) else diagnostic.message
101
+
102
+ def counted(self, diagnostic: Diagnostic) -> bool:
103
+ """
104
+ Whether a diagnostic counts toward failure with the thresholds of this run.
105
+
106
+ Parameters
107
+ ----------
108
+ diagnostic : Diagnostic
109
+ The diagnostic.
110
+
111
+ Returns
112
+ ----------
113
+ bool
114
+ True when it counts.
115
+ """
116
+ return counts_toward_failure(diagnostic, self.report.fail_on, self.report.strict_heuristics)
117
+
118
+ def line_text(self, path: str, number: int) -> str | None:
119
+ """
120
+ Text of a source line, for excerpts.
121
+
122
+ Parameters
123
+ ----------
124
+ path : str
125
+ File, relative POSIX path.
126
+ number : int
127
+ 1-based line number.
128
+
129
+ Returns
130
+ ----------
131
+ str | None
132
+ The line, or None when the file or the line is not loaded.
133
+ """
134
+ source = self.report.project.files.get(path)
135
+ if source is None or source.skipped is not None or not 1 <= number <= len(source.lines):
136
+ return None
137
+ return source.line(number).text
138
+
139
+ def fixed_line(self) -> str | None:
140
+ """
141
+ Summary of the fixes of a `--fix` run.
142
+
143
+ Returns
144
+ ----------
145
+ str | None
146
+ e.g. "Fixed: 12 fix(es) in 3 file(s)", or None when the run did not fix.
147
+ """
148
+ if not self.report.fixing:
149
+ return None
150
+ files: int = len({record.path for record in self.report.fixes})
151
+ return f"Fixed: {len(self.report.fixes)} fix(es) in {files} file(s)"
152
+
153
+ def severity_totals(self, diagnostics: tuple[Diagnostic, ...]) -> dict[str, int]:
154
+ """
155
+ Number of diagnostics per severity, most severe first.
156
+
157
+ Parameters
158
+ ----------
159
+ diagnostics : tuple[Diagnostic, ...]
160
+ The diagnostics.
161
+
162
+ Returns
163
+ ----------
164
+ dict[str, int]
165
+ Counts by severity name.
166
+ """
167
+ counts: Counter[SeverityLevel] = Counter(item.severity for item in diagnostics)
168
+ return {level.value: counts.get(level, 0) for level in SEVERITY_ORDER}
169
+
170
+ def rule_totals(self) -> list[tuple[str, str, SeverityLevel, int]]:
171
+ """
172
+ Number of findings per rule, rules with the most findings first.
173
+
174
+ Returns
175
+ ----------
176
+ list[tuple[str, str, SeverityLevel, int]]
177
+ (code, title, highest severity, count) for every rule with at least one finding.
178
+ """
179
+ counts: Counter[str] = Counter(item.rule_id for item in self.findings)
180
+ rows: list[tuple[str, str, SeverityLevel, int]] = []
181
+ order: dict[SeverityLevel, int] = {level: rank for rank, level in enumerate(SEVERITY_ORDER)}
182
+ for rule_id, count in counts.items():
183
+ items: list[Diagnostic] = [item for item in self.findings if item.rule_id == rule_id]
184
+ worst: SeverityLevel = min((item.severity for item in items), key=lambda level: order[level])
185
+ rule = self.report.catalog.rules.get(rule_id)
186
+ rows.append((items[0].code, rule.title if rule is not None else rule_id, worst, count))
187
+ rows.sort(key=lambda row: (-row[3], row[0]))
188
+ return rows
189
+
190
+
191
+ def write_atomically(path: Path, content: str) -> None:
192
+ """
193
+ Write a text file atomically (temporary file in the same directory, then replace), creating the parent
194
+ directories (plan 08, section 9).
195
+
196
+ Parameters
197
+ ----------
198
+ path : Path
199
+ Destination.
200
+ content : str
201
+ Text to write.
202
+
203
+ Returns
204
+ ----------
205
+ None
206
+ Nothing.
207
+
208
+ Raises
209
+ ----------
210
+ ProjectEnvironmentError
211
+ The file cannot be written.
212
+ """
213
+ try:
214
+ path.parent.mkdir(parents=True, exist_ok=True)
215
+ descriptor, temporary = tempfile.mkstemp(dir=path.parent, prefix=f".{path.name}.", suffix=".tmp")
216
+ try:
217
+ with os.fdopen(descriptor, "w", encoding="utf-8") as stream:
218
+ stream.write(content)
219
+ os.replace(temporary, path)
220
+ except BaseException:
221
+ Path(temporary).unlink(missing_ok=True)
222
+ raise
223
+ except OSError as error:
224
+ raise ProjectEnvironmentError(f"Cannot write '{path}': {error.strerror}.") from None
File without changes
@@ -0,0 +1,182 @@
1
+ import json
2
+ from typing import Any
3
+ from urllib.parse import quote
4
+
5
+ from sources.constants import PROGRAM_NAME, PROGRAM_URL, PROGRAM_VERSION
6
+ from sources.diagnostics.model import ENCODING_CODE, FILE_SKIPPED_CODE, INTERNAL_ERROR_CODE, SYNTAX_ERROR_CODE, Diagnostic
7
+ from sources.enums import ExitCode, SeverityLevel
8
+ from sources.outputs.json.renderer import json_data
9
+ from sources.outputs.report import ReportView
10
+ from sources.rules.definition import RuleDefinition
11
+
12
+
13
+ # SARIF version produced (plan 08, OUT-05).
14
+ SARIF_VERSION: str = "2.1.0"
15
+
16
+ # Schema of the SARIF 2.1.0 format.
17
+ SARIF_SCHEMA: str = "https://json.schemastore.org/sarif-2.1.0.json"
18
+
19
+ # Base URI identifier of the project root.
20
+ SOURCE_ROOT: str = "%SRCROOT%"
21
+
22
+ # Key of the JCCS fingerprint in `partialFingerprints`.
23
+ FINGERPRINT_KEY: str = "jccs/v1"
24
+
25
+ # SARIF level of each severity (plan 06, section 3).
26
+ LEVEL_BY_SEVERITY: dict[SeverityLevel, str] = {
27
+ SeverityLevel.INFO: "note",
28
+ SeverityLevel.MINOR: "warning",
29
+ SeverityLevel.MAJOR: "error",
30
+ SeverityLevel.FATAL: "error",
31
+ }
32
+
33
+ # Description of the internal `jccs/*` codes (plan 06, section 4), for `tool.driver.rules`.
34
+ INTERNAL_RULES: dict[str, str] = {
35
+ INTERNAL_ERROR_CODE: "A rule or analysis step crashed",
36
+ SYNTAX_ERROR_CODE: "File only partially parsed",
37
+ ENCODING_CODE: "File is not valid UTF-8",
38
+ FILE_SKIPPED_CODE: "File not analysed",
39
+ }
40
+
41
+
42
+ def _rule_descriptor(rule: RuleDefinition) -> dict[str, Any]:
43
+ """
44
+ SARIF reporting descriptor of a rule.
45
+
46
+ Parameters
47
+ ----------
48
+ rule : RuleDefinition
49
+ The rule.
50
+
51
+ Returns
52
+ ----------
53
+ dict[str, Any]
54
+ The descriptor.
55
+ """
56
+ descriptor: dict[str, Any] = {
57
+ "id": rule.id,
58
+ "name": rule.code,
59
+ "shortDescription": {"text": rule.title},
60
+ "fullDescription": {"text": rule.summary or rule.title},
61
+ }
62
+ if rule.rationale:
63
+ descriptor["help"] = {"text": rule.rationale}
64
+ if rule.docs_url:
65
+ descriptor["helpUri"] = rule.docs_url
66
+ descriptor["defaultConfiguration"] = {"level": LEVEL_BY_SEVERITY[rule.severity]}
67
+ descriptor["properties"] = {"tags": list(rule.tags), "category": rule.category, "detection": rule.detection.value}
68
+ return descriptor
69
+
70
+
71
+ def _internal_descriptor(code: str) -> dict[str, Any]:
72
+ """
73
+ SARIF reporting descriptor of an internal `jccs/*` code.
74
+
75
+ Parameters
76
+ ----------
77
+ code : str
78
+ The code.
79
+
80
+ Returns
81
+ ----------
82
+ dict[str, Any]
83
+ The descriptor.
84
+ """
85
+ text: str = INTERNAL_RULES.get(code, code)
86
+ return {"id": code, "name": code, "shortDescription": {"text": text}, "fullDescription": {"text": text}}
87
+
88
+
89
+ def _result(view: ReportView, item: Diagnostic, index: int) -> dict[str, Any]:
90
+ """
91
+ SARIF result of one diagnostic. Review items get `kind: review` (SARIF then requires `level: none`).
92
+
93
+ Parameters
94
+ ----------
95
+ view : ReportView
96
+ The report.
97
+ item : Diagnostic
98
+ The diagnostic.
99
+ index : int
100
+ Index of its rule in `tool.driver.rules`.
101
+
102
+ Returns
103
+ ----------
104
+ dict[str, Any]
105
+ The result.
106
+ """
107
+ location = item.location
108
+ region: dict[str, int] = {"startLine": location.line, "startColumn": location.column}
109
+ if location.end_line is not None:
110
+ region["endLine"] = location.end_line
111
+ if location.end_column is not None:
112
+ region["endColumn"] = location.end_column
113
+ result: dict[str, Any] = {
114
+ "ruleId": item.rule_id,
115
+ "ruleIndex": index,
116
+ "kind": "review" if item.review else "fail",
117
+ "level": "none" if item.review else LEVEL_BY_SEVERITY[item.severity],
118
+ "message": {"text": f"{view.code(item)}: {view.message(item)}"},
119
+ "locations": [{
120
+ "physicalLocation": {
121
+ "artifactLocation": {"uri": quote(location.path), "uriBaseId": SOURCE_ROOT},
122
+ "region": region,
123
+ },
124
+ }],
125
+ "partialFingerprints": {FINGERPRINT_KEY: item.fingerprint},
126
+ "properties": {
127
+ "severity": item.severity.value,
128
+ "code": view.code(item),
129
+ "detection": item.detection.value,
130
+ "counted": view.counted(item),
131
+ "data": json_data(item.data),
132
+ },
133
+ }
134
+ return result
135
+
136
+
137
+ def render_sarif(view: ReportView, *, summary_only: bool) -> str:
138
+ """
139
+ Render the SARIF 2.1.0 report (plan 08, section 5). Deterministic: no timestamp, rules sorted by ID.
140
+
141
+ Parameters
142
+ ----------
143
+ view : ReportView
144
+ The report.
145
+ summary_only : bool
146
+ Whether `results` is left empty (totals stay in `run.properties`).
147
+
148
+ Returns
149
+ ----------
150
+ str
151
+ The SARIF document, with a final newline.
152
+ """
153
+ report = view.report
154
+ diagnostics: tuple[Diagnostic, ...] = report.result.diagnostics
155
+ rule_ids: set[str] = {bound.rule.id for bound in report.plan.rules} | {item.rule_id for item in diagnostics}
156
+ ordered: list[str] = sorted(rule_ids)
157
+ index: dict[str, int] = {rule_id: position for position, rule_id in enumerate(ordered)}
158
+ descriptors: list[dict[str, Any]] = []
159
+ for rule_id in ordered:
160
+ rule: RuleDefinition | None = report.catalog.rules.get(rule_id)
161
+ descriptors.append(_rule_descriptor(rule) if rule is not None else _internal_descriptor(rule_id))
162
+ root_uri: str = report.root.as_uri().rstrip("/") + "/"
163
+ run: dict[str, Any] = {
164
+ "tool": {"driver": {"name": PROGRAM_NAME, "version": PROGRAM_VERSION, "informationUri": PROGRAM_URL, "rules": descriptors}},
165
+ "originalUriBaseIds": {SOURCE_ROOT: {"uri": root_uri}},
166
+ "invocations": [{
167
+ "executionSuccessful": report.exit_code is not ExitCode.INTERNAL,
168
+ "exitCode": int(report.exit_code),
169
+ "exitCodeDescription": report.outcome.reason,
170
+ }],
171
+ "columnKind": "unicodeCodePoints",
172
+ "results": [] if summary_only else [_result(view, item, index[item.rule_id]) for item in diagnostics],
173
+ "properties": {
174
+ "findings": len(view.findings),
175
+ "review": len(view.review_items),
176
+ "counted": report.outcome.counted,
177
+ "fixed": len(report.fixes),
178
+ "severities": view.severity_totals(view.findings),
179
+ },
180
+ }
181
+ document: dict[str, Any] = {"$schema": SARIF_SCHEMA, "version": SARIF_VERSION, "runs": [run]}
182
+ return json.dumps(document, indent=2, ensure_ascii=False) + "\n"
File without changes
@@ -0,0 +1,184 @@
1
+ from dataclasses import dataclass
2
+ from itertools import groupby
3
+
4
+ from sources.analysis.source import SourceFile
5
+ from sources.diagnostics.model import Diagnostic
6
+ from sources.enums import ExitCode
7
+ from sources.outputs.report import ReportView
8
+ from sources.outputs.terminal.style import Style
9
+
10
+
11
+ # Console level: per-file findings, review items, per-rule summary and result.
12
+ LEVEL_NORMAL: int = 0
13
+
14
+ # Console level (`-s`): per-rule summary and result.
15
+ LEVEL_SILENT: int = 1
16
+
17
+ # Console level (`--super-silent`): result line only.
18
+ LEVEL_SUPER_SILENT: int = 2
19
+
20
+ # Console level (`--extreme-silent`): nothing.
21
+ LEVEL_EXTREME_SILENT: int = 3
22
+
23
+
24
+ @dataclass(frozen=True, slots=True)
25
+ class TextOptions:
26
+ """
27
+ How the text report is laid out (plan 08, sections 2-3).
28
+ (dataclass)
29
+
30
+ Attributes
31
+ ----------
32
+ level : int
33
+ Console level (LEVEL_* constants).
34
+ grouped : bool
35
+ Group findings by file with source excerpts (terminals); flat lines otherwise.
36
+ summary_only : bool
37
+ Report totals only, no individual findings.
38
+ style : Style
39
+ Colour adapter.
40
+ """
41
+
42
+ level: int
43
+ grouped: bool
44
+ summary_only: bool
45
+ style: Style
46
+
47
+
48
+ def _flat_line(view: ReportView, item: Diagnostic, review: bool) -> str:
49
+ """
50
+ Stable one-line form: `<path>:<line>:<column>: <severity> [<code>] <message>`.
51
+
52
+ Parameters
53
+ ----------
54
+ view : ReportView
55
+ The report.
56
+ item : Diagnostic
57
+ The diagnostic.
58
+ review : bool
59
+ Whether the item is to review (suffix " (to review)").
60
+
61
+ Returns
62
+ ----------
63
+ str
64
+ The line.
65
+ """
66
+ location = item.location
67
+ suffix: str = " (to review)" if review else ""
68
+ return f"{location.path}:{location.line}:{location.column}: {item.severity.value} [{view.code(item)}] {view.message(item)}{suffix}"
69
+
70
+
71
+ def _excerpt(source: SourceFile | None, item: Diagnostic, style: Style) -> list[str]:
72
+ """
73
+ Source line of a diagnostic with a caret under its column.
74
+
75
+ Parameters
76
+ ----------
77
+ source : SourceFile | None
78
+ File of the diagnostic.
79
+ item : Diagnostic
80
+ The diagnostic.
81
+ style : Style
82
+ Colour adapter.
83
+
84
+ Returns
85
+ ----------
86
+ list[str]
87
+ The excerpt lines (empty when the line is not available).
88
+ """
89
+ if source is None or not 1 <= item.location.line <= len(source.lines):
90
+ return []
91
+ text: str = source.lines[item.location.line - 1].text.replace("\t", " ")
92
+ width: int = max((item.location.end_column or item.location.column + 1) - item.location.column, 1) if item.location.end_line in (None, item.location.line) else 1
93
+ return [f" {style.dim(text)}", " " + " " * (item.location.column - 1) + style.severity("^" * width, item.severity)]
94
+
95
+
96
+ def _grouped(view: ReportView, items: tuple[Diagnostic, ...], style: Style, excerpts: bool) -> list[str]:
97
+ """
98
+ Diagnostics grouped by file, with a header per file.
99
+
100
+ Parameters
101
+ ----------
102
+ view : ReportView
103
+ The report.
104
+ items : tuple[Diagnostic, ...]
105
+ Diagnostics, sorted by path.
106
+ style : Style
107
+ Colour adapter.
108
+ excerpts : bool
109
+ Whether source excerpts are shown.
110
+
111
+ Returns
112
+ ----------
113
+ list[str]
114
+ The lines.
115
+ """
116
+ lines: list[str] = []
117
+ files = view.report.project.files
118
+ for path, group in groupby(items, key=lambda entry: entry.location.path):
119
+ lines.append(style.bold(path))
120
+ for item in group:
121
+ position: str = f"{item.location.line}:{item.location.column}"
122
+ severity: str = style.severity(f"{item.severity.value:<5}", item.severity)
123
+ lines.append(f" {position:<8} {severity} {style.bold(view.code(item))} {view.message(item)}")
124
+ if excerpts:
125
+ lines.extend(_excerpt(files.get(path), item, style))
126
+ lines.append("")
127
+ return lines
128
+
129
+
130
+ def render_text(view: ReportView, options: TextOptions) -> str:
131
+ """
132
+ Render the text report.
133
+
134
+ Parameters
135
+ ----------
136
+ view : ReportView
137
+ The report.
138
+ options : TextOptions
139
+ Layout options.
140
+
141
+ Returns
142
+ ----------
143
+ str
144
+ The report ("" at the extreme silent level).
145
+ """
146
+ if options.level >= LEVEL_EXTREME_SILENT:
147
+ return ""
148
+ style: Style = options.style
149
+ report = view.report
150
+ lines: list[str] = []
151
+ if options.level == LEVEL_NORMAL and not options.summary_only:
152
+ if options.grouped:
153
+ lines.extend(_grouped(view, view.findings, style, excerpts=True))
154
+ if view.review_items:
155
+ lines.append(style.notice(f"To review ({len(view.review_items)}):"))
156
+ lines.extend(_grouped(view, view.review_items, style, excerpts=False))
157
+ else:
158
+ lines.extend(_flat_line(view, item, False) for item in view.findings)
159
+ lines.extend(_flat_line(view, item, True) for item in view.review_items)
160
+ if view.findings or view.review_items:
161
+ lines.append("")
162
+ if options.level <= LEVEL_SILENT:
163
+ rows = view.rule_totals()
164
+ if rows:
165
+ lines.append(style.bold("Findings by rule:"))
166
+ width: int = max(len(row[0]) for row in rows)
167
+ for code, title, worst, count in rows:
168
+ lines.append(f" {code:<{width}} {style.severity(f'{count:>4}', worst)} {title}")
169
+ lines.append("")
170
+ totals: dict[str, int] = view.severity_totals(view.findings)
171
+ summary: str = ", ".join(f"{count} {name}" for name, count in totals.items())
172
+ lines.append(f"Files analysed: {len(report.result.files_analyzed)} | Findings: {len(view.findings)} ({summary}) | To review: {len(view.review_items)}")
173
+ fixed: str | None = view.fixed_line()
174
+ if fixed is not None:
175
+ lines.append(fixed)
176
+ exit_code: ExitCode = report.exit_code
177
+ if exit_code is ExitCode.OK:
178
+ verdict: str = style.success("PASSED")
179
+ elif exit_code is ExitCode.FINDINGS:
180
+ verdict = style.failure("FAILED")
181
+ else:
182
+ verdict = style.error("ERROR")
183
+ lines.append(f"Result: {verdict} ({report.outcome.reason})")
184
+ return "\n".join(lines) + "\n"