jarbin-c-coding-style 2.0.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- jarbin_c_coding_style-2.0.0.dist-info/METADATA +150 -0
- jarbin_c_coding_style-2.0.0.dist-info/RECORD +186 -0
- jarbin_c_coding_style-2.0.0.dist-info/WHEEL +4 -0
- jarbin_c_coding_style-2.0.0.dist-info/entry_points.txt +2 -0
- jarbin_c_coding_style-2.0.0.dist-info/licenses/LICENSE +674 -0
- sources/__init__.py +0 -0
- sources/__main__.py +6 -0
- sources/analysis/__init__.py +0 -0
- sources/analysis/directives.py +258 -0
- sources/analysis/lexer.py +288 -0
- sources/analysis/parser.py +1754 -0
- sources/analysis/project.py +286 -0
- sources/analysis/source.py +326 -0
- sources/analysis/syntax.py +238 -0
- sources/analysis/tokens.py +116 -0
- sources/analysis/unit.py +700 -0
- sources/application.py +118 -0
- sources/build_info.json +6 -0
- sources/cli/__init__.py +0 -0
- sources/cli/arguments.py +507 -0
- sources/cli/completion.py +610 -0
- sources/cli/context.py +258 -0
- sources/cli/converters.py +204 -0
- sources/cli/help.py +162 -0
- sources/cli/parser.py +659 -0
- sources/configs/__init__.py +0 -0
- sources/configs/editor.py +207 -0
- sources/configs/ini.py +327 -0
- sources/configs/project.py +735 -0
- sources/configs/schema/__init__.py +0 -0
- sources/configs/schema/project.py +68 -0
- sources/constants.py +801 -0
- sources/diagnostics/__init__.py +0 -0
- sources/diagnostics/fingerprint.py +82 -0
- sources/diagnostics/model.py +146 -0
- sources/engine/__init__.py +0 -0
- sources/engine/api.py +355 -0
- sources/engine/examples.py +157 -0
- sources/engine/outcome.py +114 -0
- sources/engine/plan.py +440 -0
- sources/engine/runner.py +345 -0
- sources/engine/scanner.py +179 -0
- sources/enums.py +838 -0
- sources/errors/__init__.py +0 -0
- sources/errors/exceptions.py +727 -0
- sources/fixers/__init__.py +0 -0
- sources/fixers/base.py +209 -0
- sources/fixers/conflicts.py +129 -0
- sources/fixers/diff.py +73 -0
- sources/fixers/engine.py +434 -0
- sources/fixers/journal.py +290 -0
- sources/fixers/kinds.py +30 -0
- sources/fixers/layout.py +411 -0
- sources/fixers/model.py +151 -0
- sources/fixers/registry.py +54 -0
- sources/fixers/text.py +353 -0
- sources/fixers/verify.py +123 -0
- sources/fixers/writer.py +88 -0
- sources/integrations/__init__.py +0 -0
- sources/integrations/ci/__init__.py +0 -0
- sources/integrations/ci/github.py +183 -0
- sources/integrations/editors/__init__.py +0 -0
- sources/integrations/git/__init__.py +0 -0
- sources/integrations/git/repository.py +176 -0
- sources/integrations/update/__init__.py +0 -0
- sources/integrations/update/installers.py +529 -0
- sources/integrations/update/releases.py +397 -0
- sources/integrations/update/state.py +143 -0
- sources/outputs/__init__.py +0 -0
- sources/outputs/github/__init__.py +0 -0
- sources/outputs/github/renderer.py +135 -0
- sources/outputs/html/__init__.py +0 -0
- sources/outputs/html/renderer.py +694 -0
- sources/outputs/json/__init__.py +0 -0
- sources/outputs/json/renderer.py +154 -0
- sources/outputs/json/report.schema.json +121 -0
- sources/outputs/junit/__init__.py +0 -0
- sources/outputs/junit/renderer.py +151 -0
- sources/outputs/registry.py +135 -0
- sources/outputs/report.py +224 -0
- sources/outputs/sarif/__init__.py +0 -0
- sources/outputs/sarif/renderer.py +182 -0
- sources/outputs/terminal/__init__.py +0 -0
- sources/outputs/terminal/renderer.py +184 -0
- sources/outputs/terminal/style.py +159 -0
- sources/rules/__init__.py +0 -0
- sources/rules/arguments.py +362 -0
- sources/rules/catalog.py +227 -0
- sources/rules/categories/advanced/constant_pointers.ini +46 -0
- sources/rules/categories/advanced/line_break_at_end_of_file.ini +44 -0
- sources/rules/categories/advanced/static.ini +65 -0
- sources/rules/categories/advanced/typing.ini +47 -0
- sources/rules/categories/control_structures/conditional_branching.ini +89 -0
- sources/rules/categories/control_structures/goto.ini +45 -0
- sources/rules/categories/control_structures/ternary_operators.ini +57 -0
- sources/rules/categories/extensions/language_extensions.ini +71 -0
- sources/rules/categories/files_organization/contents_of_the_repository.ini +85 -0
- sources/rules/categories/files_organization/file_coherence.ini +166 -0
- sources/rules/categories/files_organization/file_extension.ini +68 -0
- sources/rules/categories/files_organization/fixtures/program +0 -0
- sources/rules/categories/files_organization/naming_files_and_folders.ini +74 -0
- sources/rules/categories/functions/coherence_of_functions.ini +45 -0
- sources/rules/categories/functions/comments_inside_a_function.ini +45 -0
- sources/rules/categories/functions/functions_without_parameters.ini +39 -0
- sources/rules/categories/functions/naming_functions.ini +79 -0
- sources/rules/categories/functions/number_of_columns.ini +61 -0
- sources/rules/categories/functions/number_of_lines.ini +70 -0
- sources/rules/categories/functions/number_of_parameters.ini +64 -0
- sources/rules/categories/functions/structures_as_parameters.ini +44 -0
- sources/rules/categories/global_scope/constant_values.ini +49 -0
- sources/rules/categories/global_scope/file_header.ini +92 -0
- sources/rules/categories/global_scope/global_variables.ini +53 -0
- sources/rules/categories/global_scope/include.ini +39 -0
- sources/rules/categories/global_scope/indentation_of_preprocessor.ini +62 -0
- sources/rules/categories/global_scope/inline_assembly.ini +43 -0
- sources/rules/categories/global_scope/leading_trailing_lines.ini +58 -0
- sources/rules/categories/global_scope/line_endings.ini +53 -0
- sources/rules/categories/global_scope/separation_of_functions.ini +61 -0
- sources/rules/categories/global_scope/trailing_spaces.ini +45 -0
- sources/rules/categories/header_files/content.ini +104 -0
- sources/rules/categories/header_files/include_guard.ini +47 -0
- sources/rules/categories/header_files/macros.ini +57 -0
- sources/rules/categories/layout_inside_a_function_scope/blank_lines.ini +71 -0
- sources/rules/categories/layout_inside_a_function_scope/code_line_content.ini +112 -0
- sources/rules/categories/layout_inside_a_function_scope/curly_brackets.ini +94 -0
- sources/rules/categories/layout_inside_a_function_scope/indentation.ini +96 -0
- sources/rules/categories/layout_inside_a_function_scope/spaces.ini +113 -0
- sources/rules/categories/layout_inside_a_function_scope/variable_declarations.ini +65 -0
- sources/rules/categories/variables_and_types/naming_identifiers.ini +74 -0
- sources/rules/categories/variables_and_types/pointers.ini +67 -0
- sources/rules/categories/variables_and_types/structures.ini +47 -0
- sources/rules/data/verbs.txt +182 -0
- sources/rules/definition.py +430 -0
- sources/rules/loader.py +925 -0
- sources/rules/paths.py +6 -0
- sources/rules/primitives/__init__.py +0 -0
- sources/rules/primitives/base.py +297 -0
- sources/rules/primitives/braces.py +211 -0
- sources/rules/primitives/directives.py +203 -0
- sources/rules/primitives/indentation.py +376 -0
- sources/rules/primitives/layout.py +199 -0
- sources/rules/primitives/naming.py +277 -0
- sources/rules/primitives/project.py +62 -0
- sources/rules/primitives/registry.py +49 -0
- sources/rules/primitives/repository.py +129 -0
- sources/rules/primitives/review.py +87 -0
- sources/rules/primitives/semantic.py +319 -0
- sources/rules/primitives/spacing.py +210 -0
- sources/rules/primitives/structure.py +586 -0
- sources/rules/primitives/syntax.py +200 -0
- sources/rules/primitives/text.py +408 -0
- sources/rules/primitives/tokens.py +84 -0
- sources/rules/template.py +138 -0
- sources/selftest/__init__.py +0 -0
- sources/selftest/cases.py +292 -0
- sources/services.py +90 -0
- sources/subcommands/__init__.py +0 -0
- sources/subcommands/base.py +45 -0
- sources/subcommands/check/__init__.py +0 -0
- sources/subcommands/check/command.py +45 -0
- sources/subcommands/check/fixing.py +224 -0
- sources/subcommands/check/handler.py +757 -0
- sources/subcommands/info/__init__.py +0 -0
- sources/subcommands/info/command.py +45 -0
- sources/subcommands/info/handler.py +527 -0
- sources/subcommands/registry.py +37 -0
- sources/subcommands/rule/__init__.py +0 -0
- sources/subcommands/rule/command.py +45 -0
- sources/subcommands/rule/handler.py +1067 -0
- sources/subcommands/rule/render.py +273 -0
- sources/subcommands/runner.py +124 -0
- sources/subcommands/test/__init__.py +0 -0
- sources/subcommands/test/command.py +45 -0
- sources/subcommands/test/handler.py +166 -0
- sources/subcommands/test/render.py +219 -0
- sources/subcommands/test/runner.py +430 -0
- sources/subcommands/update/__init__.py +0 -0
- sources/subcommands/update/command.py +45 -0
- sources/subcommands/update/handler.py +408 -0
- sources/utils/__init__.py +0 -0
- sources/utils/build_info.py +188 -0
- sources/utils/git.py +73 -0
- sources/utils/globs.py +98 -0
- sources/utils/logging.py +154 -0
- sources/utils/schema.py +77 -0
- sources/utils/versions.py +87 -0
|
@@ -0,0 +1,397 @@
|
|
|
1
|
+
import json
|
|
2
|
+
import re
|
|
3
|
+
import urllib.error
|
|
4
|
+
import urllib.request
|
|
5
|
+
from collections.abc import Callable, Mapping
|
|
6
|
+
from dataclasses import dataclass, field
|
|
7
|
+
from typing import Any
|
|
8
|
+
|
|
9
|
+
from sources.constants import PROGRAM_NAME, PROGRAM_VERSION
|
|
10
|
+
from sources.errors.exceptions import ProjectEnvironmentError
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
# PyPI distribution of JCCS (plan 12, DIST-02).
|
|
14
|
+
DISTRIBUTION_NAME: str = "jarbin-c-coding-style"
|
|
15
|
+
|
|
16
|
+
# GitHub repository of JCCS (owner/name).
|
|
17
|
+
GITHUB_REPOSITORY: str = "Jarjarbin06/Jarbin-C-Coding-Style"
|
|
18
|
+
|
|
19
|
+
# Default service URLs; each can be replaced by an environment variable (mirrors, offline tests with file://).
|
|
20
|
+
PYPI_URL_VARIABLE: str = "JCCS_PYPI_URL"
|
|
21
|
+
GITHUB_API_URL_VARIABLE: str = "JCCS_GITHUB_API_URL"
|
|
22
|
+
GITHUB_RAW_URL_VARIABLE: str = "JCCS_GITHUB_RAW_URL"
|
|
23
|
+
DEFAULT_PYPI_URL: str = "https://pypi.org/pypi"
|
|
24
|
+
DEFAULT_GITHUB_API_URL: str = "https://api.github.com"
|
|
25
|
+
DEFAULT_GITHUB_RAW_URL: str = "https://raw.githubusercontent.com"
|
|
26
|
+
|
|
27
|
+
# Optional token for the GitHub API rate limit (sent to the GitHub API host only, never printed).
|
|
28
|
+
GITHUB_TOKEN_VARIABLE: str = "GITHUB_TOKEN"
|
|
29
|
+
|
|
30
|
+
# URL schemes accepted for the service URLs.
|
|
31
|
+
ALLOWED_SCHEMES: tuple[str, ...] = ("https://", "http://", "file://")
|
|
32
|
+
|
|
33
|
+
# Longest time given to one request, in seconds.
|
|
34
|
+
HTTP_TIMEOUT: float = 15.0
|
|
35
|
+
|
|
36
|
+
# Largest response accepted, in bytes.
|
|
37
|
+
MAX_RESPONSE_SIZE: int = 200 * 1024 * 1024
|
|
38
|
+
|
|
39
|
+
# Version: X.Y.Z, optionally a pre-release (semver `-beta.1`, `-rc.2`, or PEP 440 `b1`, `rc2`, `a1`).
|
|
40
|
+
VERSION_PATTERN: re.Pattern[str] = re.compile(
|
|
41
|
+
r"^v?(\d+)\.(\d+)\.(\d+)(?:[-.]?(alpha|beta|rc|a|b|c|pre|preview)[-.]?(\d+)?)?$", re.IGNORECASE,
|
|
42
|
+
)
|
|
43
|
+
|
|
44
|
+
# Rank of each pre-release label (a final release ranks above every pre-release).
|
|
45
|
+
PRERELEASE_RANK: dict[str, int] = {"alpha": 0, "a": 0, "beta": 1, "b": 1, "pre": 1, "preview": 1, "rc": 2, "c": 2}
|
|
46
|
+
|
|
47
|
+
# Rank of a final release.
|
|
48
|
+
FINAL_RANK: int = 3
|
|
49
|
+
|
|
50
|
+
# Fetches a URL and returns its body (injectable for tests).
|
|
51
|
+
Fetcher = Callable[[str], bytes]
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
@dataclass(frozen=True, slots=True, order=True)
|
|
55
|
+
class Version:
|
|
56
|
+
"""
|
|
57
|
+
A release version, ordered (pre-releases before the final release).
|
|
58
|
+
(dataclass)
|
|
59
|
+
|
|
60
|
+
Attributes
|
|
61
|
+
----------
|
|
62
|
+
key : tuple[int, int, int, int, int]
|
|
63
|
+
(major, minor, patch, pre-release rank, pre-release number).
|
|
64
|
+
text : str
|
|
65
|
+
Normalised text (without a leading "v").
|
|
66
|
+
"""
|
|
67
|
+
|
|
68
|
+
key: tuple[int, int, int, int, int]
|
|
69
|
+
text: str = field(compare=False)
|
|
70
|
+
|
|
71
|
+
@property
|
|
72
|
+
def prerelease(self) -> bool:
|
|
73
|
+
"""
|
|
74
|
+
Whether this is a pre-release (beta channel only).
|
|
75
|
+
|
|
76
|
+
Returns
|
|
77
|
+
----------
|
|
78
|
+
bool
|
|
79
|
+
True for alpha, beta and release candidates.
|
|
80
|
+
"""
|
|
81
|
+
return self.key[3] != FINAL_RANK
|
|
82
|
+
|
|
83
|
+
|
|
84
|
+
def parse_release_version(text: str) -> Version | None:
|
|
85
|
+
"""
|
|
86
|
+
Parse a release version or tag.
|
|
87
|
+
|
|
88
|
+
Parameters
|
|
89
|
+
----------
|
|
90
|
+
text : str
|
|
91
|
+
e.g. "2.1.0", "v2.1.0", "2.1.0-beta.1", "2.1.0rc2".
|
|
92
|
+
|
|
93
|
+
Returns
|
|
94
|
+
----------
|
|
95
|
+
Version | None
|
|
96
|
+
The version, or None when the text is not a release version.
|
|
97
|
+
"""
|
|
98
|
+
match: re.Match[str] | None = VERSION_PATTERN.match(text.strip())
|
|
99
|
+
if match is None:
|
|
100
|
+
return None
|
|
101
|
+
major, minor, patch, label, number = match.groups()
|
|
102
|
+
rank: int = FINAL_RANK if label is None else PRERELEASE_RANK[label.lower()]
|
|
103
|
+
return Version((int(major), int(minor), int(patch), rank, int(number or 0)), text.strip().removeprefix("v").removeprefix("V"))
|
|
104
|
+
|
|
105
|
+
|
|
106
|
+
@dataclass(frozen=True, slots=True)
|
|
107
|
+
class Release:
|
|
108
|
+
"""
|
|
109
|
+
One published release.
|
|
110
|
+
(dataclass)
|
|
111
|
+
|
|
112
|
+
Attributes
|
|
113
|
+
----------
|
|
114
|
+
version : Version
|
|
115
|
+
Its version.
|
|
116
|
+
tag : str
|
|
117
|
+
Git tag (e.g. "v2.1.0").
|
|
118
|
+
prerelease : bool
|
|
119
|
+
Whether it belongs to the beta channel only.
|
|
120
|
+
assets : Mapping[str, str]
|
|
121
|
+
Download URL by asset name (GitHub releases).
|
|
122
|
+
"""
|
|
123
|
+
|
|
124
|
+
version: Version
|
|
125
|
+
tag: str
|
|
126
|
+
prerelease: bool
|
|
127
|
+
assets: Mapping[str, str] = field(default_factory=dict)
|
|
128
|
+
|
|
129
|
+
|
|
130
|
+
def service_url(environment: Mapping[str, str], variable: str, default: str) -> str:
|
|
131
|
+
"""
|
|
132
|
+
Base URL of a service, from its environment variable or the default.
|
|
133
|
+
|
|
134
|
+
Parameters
|
|
135
|
+
----------
|
|
136
|
+
environment : Mapping[str, str]
|
|
137
|
+
Process environment.
|
|
138
|
+
variable : str
|
|
139
|
+
Variable name.
|
|
140
|
+
default : str
|
|
141
|
+
Default URL.
|
|
142
|
+
|
|
143
|
+
Returns
|
|
144
|
+
----------
|
|
145
|
+
str
|
|
146
|
+
The URL, without a trailing slash.
|
|
147
|
+
|
|
148
|
+
Raises
|
|
149
|
+
----------
|
|
150
|
+
ProjectEnvironmentError
|
|
151
|
+
The variable holds an unsupported scheme.
|
|
152
|
+
"""
|
|
153
|
+
url: str = environment.get(variable) or default
|
|
154
|
+
if not url.startswith(ALLOWED_SCHEMES):
|
|
155
|
+
raise ProjectEnvironmentError(f"{variable} must be an http(s) or file URL.")
|
|
156
|
+
return url.rstrip("/")
|
|
157
|
+
|
|
158
|
+
|
|
159
|
+
def http_fetcher(environment: Mapping[str, str]) -> Fetcher:
|
|
160
|
+
"""
|
|
161
|
+
Fetcher using the standard library (proxies from the environment, TLS verification on, timeout, size
|
|
162
|
+
cap). The GitHub token, when set, is sent to the GitHub API host only.
|
|
163
|
+
|
|
164
|
+
Parameters
|
|
165
|
+
----------
|
|
166
|
+
environment : Mapping[str, str]
|
|
167
|
+
Process environment.
|
|
168
|
+
|
|
169
|
+
Returns
|
|
170
|
+
----------
|
|
171
|
+
Fetcher
|
|
172
|
+
The fetcher.
|
|
173
|
+
"""
|
|
174
|
+
token: str | None = environment.get(GITHUB_TOKEN_VARIABLE)
|
|
175
|
+
api: str = service_url(environment, GITHUB_API_URL_VARIABLE, DEFAULT_GITHUB_API_URL)
|
|
176
|
+
|
|
177
|
+
def fetch(url: str) -> bytes:
|
|
178
|
+
if not url.startswith(ALLOWED_SCHEMES):
|
|
179
|
+
raise ProjectEnvironmentError(f"Refusing to fetch '{url}'.")
|
|
180
|
+
headers: dict[str, str] = {"User-Agent": f"{PROGRAM_NAME}/{PROGRAM_VERSION}"}
|
|
181
|
+
if token and url.startswith(api + "/") and url.startswith("https://"):
|
|
182
|
+
headers["Authorization"] = f"Bearer {token}"
|
|
183
|
+
request: urllib.request.Request = urllib.request.Request(url, headers=headers)
|
|
184
|
+
try:
|
|
185
|
+
with urllib.request.urlopen(request, timeout=HTTP_TIMEOUT) as response:
|
|
186
|
+
body: bytes = response.read(MAX_RESPONSE_SIZE + 1)
|
|
187
|
+
except urllib.error.HTTPError as error:
|
|
188
|
+
raise ProjectEnvironmentError(f"Cannot download {url.split('?')[0]}: HTTP {error.code}.") from None
|
|
189
|
+
except (urllib.error.URLError, OSError, ValueError) as error:
|
|
190
|
+
reason: Any = getattr(error, "reason", error)
|
|
191
|
+
raise ProjectEnvironmentError(f"Cannot reach {url.split('?')[0]}: {reason}.", "Check the network connection (and the proxy variables).") from None
|
|
192
|
+
if len(body) > MAX_RESPONSE_SIZE:
|
|
193
|
+
raise ProjectEnvironmentError(f"Response from {url.split('?')[0]} is too large.")
|
|
194
|
+
return body
|
|
195
|
+
|
|
196
|
+
return fetch
|
|
197
|
+
|
|
198
|
+
|
|
199
|
+
def _json(fetch: Fetcher, url: str) -> Any:
|
|
200
|
+
"""
|
|
201
|
+
Fetch and decode a JSON document.
|
|
202
|
+
|
|
203
|
+
Parameters
|
|
204
|
+
----------
|
|
205
|
+
fetch : Fetcher
|
|
206
|
+
The fetcher.
|
|
207
|
+
url : str
|
|
208
|
+
The URL.
|
|
209
|
+
|
|
210
|
+
Returns
|
|
211
|
+
----------
|
|
212
|
+
Any
|
|
213
|
+
The document.
|
|
214
|
+
|
|
215
|
+
Raises
|
|
216
|
+
----------
|
|
217
|
+
ProjectEnvironmentError
|
|
218
|
+
Network failure or invalid JSON.
|
|
219
|
+
"""
|
|
220
|
+
try:
|
|
221
|
+
return json.loads(fetch(url).decode("utf-8"))
|
|
222
|
+
except (ValueError, UnicodeDecodeError):
|
|
223
|
+
raise ProjectEnvironmentError(f"Invalid answer from {url}.") from None
|
|
224
|
+
|
|
225
|
+
|
|
226
|
+
def pypi_releases(fetch: Fetcher, environment: Mapping[str, str]) -> list[Release]:
|
|
227
|
+
"""
|
|
228
|
+
Releases published on PyPI (yanked files ignored).
|
|
229
|
+
|
|
230
|
+
Parameters
|
|
231
|
+
----------
|
|
232
|
+
fetch : Fetcher
|
|
233
|
+
The fetcher.
|
|
234
|
+
environment : Mapping[str, str]
|
|
235
|
+
Process environment (service URL).
|
|
236
|
+
|
|
237
|
+
Returns
|
|
238
|
+
----------
|
|
239
|
+
list[Release]
|
|
240
|
+
The releases.
|
|
241
|
+
"""
|
|
242
|
+
document: Any = _json(fetch, f"{service_url(environment, PYPI_URL_VARIABLE, DEFAULT_PYPI_URL)}/{DISTRIBUTION_NAME}/json")
|
|
243
|
+
releases: list[Release] = []
|
|
244
|
+
for text, files in (document.get("releases") or {}).items():
|
|
245
|
+
version: Version | None = parse_release_version(text)
|
|
246
|
+
if version is None or not files or all(item.get("yanked") for item in files):
|
|
247
|
+
continue
|
|
248
|
+
releases.append(Release(version, f"v{version.text}", version.prerelease))
|
|
249
|
+
return releases
|
|
250
|
+
|
|
251
|
+
|
|
252
|
+
def github_releases(fetch: Fetcher, environment: Mapping[str, str]) -> list[Release]:
|
|
253
|
+
"""
|
|
254
|
+
Releases published on GitHub (drafts ignored), with their assets.
|
|
255
|
+
|
|
256
|
+
Parameters
|
|
257
|
+
----------
|
|
258
|
+
fetch : Fetcher
|
|
259
|
+
The fetcher.
|
|
260
|
+
environment : Mapping[str, str]
|
|
261
|
+
Process environment (service URL).
|
|
262
|
+
|
|
263
|
+
Returns
|
|
264
|
+
----------
|
|
265
|
+
list[Release]
|
|
266
|
+
The releases.
|
|
267
|
+
"""
|
|
268
|
+
document: Any = _json(fetch, f"{service_url(environment, GITHUB_API_URL_VARIABLE, DEFAULT_GITHUB_API_URL)}/repos/{GITHUB_REPOSITORY}/releases?per_page=100")
|
|
269
|
+
releases: list[Release] = []
|
|
270
|
+
for item in document if isinstance(document, list) else []:
|
|
271
|
+
version: Version | None = parse_release_version(str(item.get("tag_name", "")))
|
|
272
|
+
if version is None or item.get("draft"):
|
|
273
|
+
continue
|
|
274
|
+
assets: dict[str, str] = {str(asset.get("name")): str(asset.get("browser_download_url")) for asset in item.get("assets") or []}
|
|
275
|
+
releases.append(Release(version, str(item["tag_name"]), bool(item.get("prerelease")) or version.prerelease, assets))
|
|
276
|
+
return releases
|
|
277
|
+
|
|
278
|
+
|
|
279
|
+
def git_tag_releases(tags: list[str]) -> list[Release]:
|
|
280
|
+
"""
|
|
281
|
+
Releases of a git checkout, from its `v*` tags.
|
|
282
|
+
|
|
283
|
+
Parameters
|
|
284
|
+
----------
|
|
285
|
+
tags : list[str]
|
|
286
|
+
Tag names.
|
|
287
|
+
|
|
288
|
+
Returns
|
|
289
|
+
----------
|
|
290
|
+
list[Release]
|
|
291
|
+
The releases.
|
|
292
|
+
"""
|
|
293
|
+
releases: list[Release] = []
|
|
294
|
+
for tag in tags:
|
|
295
|
+
version: Version | None = parse_release_version(tag)
|
|
296
|
+
if version is not None:
|
|
297
|
+
releases.append(Release(version, tag, version.prerelease))
|
|
298
|
+
return releases
|
|
299
|
+
|
|
300
|
+
|
|
301
|
+
def select_latest(releases: list[Release], *, beta: bool) -> Release | None:
|
|
302
|
+
"""
|
|
303
|
+
Most recent release of a channel (stable: no pre-release; beta: everything).
|
|
304
|
+
|
|
305
|
+
Parameters
|
|
306
|
+
----------
|
|
307
|
+
releases : list[Release]
|
|
308
|
+
Available releases.
|
|
309
|
+
beta : bool
|
|
310
|
+
Whether pre-releases are allowed.
|
|
311
|
+
|
|
312
|
+
Returns
|
|
313
|
+
----------
|
|
314
|
+
Release | None
|
|
315
|
+
The release, or None when there is none.
|
|
316
|
+
"""
|
|
317
|
+
candidates: list[Release] = [release for release in releases if beta or not release.prerelease]
|
|
318
|
+
return max(candidates, key=lambda release: release.version) if candidates else None
|
|
319
|
+
|
|
320
|
+
|
|
321
|
+
def find_release(releases: list[Release], text: str) -> Release | None:
|
|
322
|
+
"""
|
|
323
|
+
Release of an exact version (any channel).
|
|
324
|
+
|
|
325
|
+
Parameters
|
|
326
|
+
----------
|
|
327
|
+
releases : list[Release]
|
|
328
|
+
Available releases.
|
|
329
|
+
text : str
|
|
330
|
+
Version or tag.
|
|
331
|
+
|
|
332
|
+
Returns
|
|
333
|
+
----------
|
|
334
|
+
Release | None
|
|
335
|
+
The release, or None.
|
|
336
|
+
"""
|
|
337
|
+
wanted: Version | None = parse_release_version(text)
|
|
338
|
+
if wanted is None:
|
|
339
|
+
return None
|
|
340
|
+
return next((release for release in releases if release.version == wanted), None)
|
|
341
|
+
|
|
342
|
+
|
|
343
|
+
def changelog_section(changelog: str, version: Version) -> str | None:
|
|
344
|
+
"""
|
|
345
|
+
Section of a CHANGELOG.md for a version: from its `## ...` heading (`## 2.1.0`, `## [2.1.0] - date`,
|
|
346
|
+
`## v2.1.0`) to the next `## ` heading.
|
|
347
|
+
|
|
348
|
+
Parameters
|
|
349
|
+
----------
|
|
350
|
+
changelog : str
|
|
351
|
+
The changelog.
|
|
352
|
+
version : Version
|
|
353
|
+
The version.
|
|
354
|
+
|
|
355
|
+
Returns
|
|
356
|
+
----------
|
|
357
|
+
str | None
|
|
358
|
+
The section (heading included), or None when the version has none.
|
|
359
|
+
"""
|
|
360
|
+
lines: list[str] = changelog.splitlines()
|
|
361
|
+
heading: re.Pattern[str] = re.compile(r"^##\s+\[?v?" + re.escape(version.text) + r"\]?(\s|$)")
|
|
362
|
+
for index, line in enumerate(lines):
|
|
363
|
+
if heading.match(line):
|
|
364
|
+
end: int = next((position for position in range(index + 1, len(lines)) if lines[position].startswith("## ")), len(lines))
|
|
365
|
+
return "\n".join(lines[index:end]).strip() + "\n"
|
|
366
|
+
return None
|
|
367
|
+
|
|
368
|
+
|
|
369
|
+
def release_notes(fetch: Fetcher, environment: Mapping[str, str], release: Release) -> str:
|
|
370
|
+
"""
|
|
371
|
+
Notes of a release: its section of the CHANGELOG.md published at its tag.
|
|
372
|
+
|
|
373
|
+
Parameters
|
|
374
|
+
----------
|
|
375
|
+
fetch : Fetcher
|
|
376
|
+
The fetcher.
|
|
377
|
+
environment : Mapping[str, str]
|
|
378
|
+
Process environment (service URL).
|
|
379
|
+
release : Release
|
|
380
|
+
The release.
|
|
381
|
+
|
|
382
|
+
Returns
|
|
383
|
+
----------
|
|
384
|
+
str
|
|
385
|
+
The notes.
|
|
386
|
+
|
|
387
|
+
Raises
|
|
388
|
+
----------
|
|
389
|
+
ProjectEnvironmentError
|
|
390
|
+
The changelog cannot be downloaded or has no section for the version.
|
|
391
|
+
"""
|
|
392
|
+
base: str = service_url(environment, GITHUB_RAW_URL_VARIABLE, DEFAULT_GITHUB_RAW_URL)
|
|
393
|
+
text: str = fetch(f"{base}/{GITHUB_REPOSITORY}/{release.tag}/CHANGELOG.md").decode("utf-8", "replace")
|
|
394
|
+
section: str | None = changelog_section(text, release.version)
|
|
395
|
+
if section is None:
|
|
396
|
+
raise ProjectEnvironmentError(f"CHANGELOG.md of {release.tag} has no section for {release.version.text}.")
|
|
397
|
+
return section
|
|
@@ -0,0 +1,143 @@
|
|
|
1
|
+
import json
|
|
2
|
+
import os
|
|
3
|
+
from collections.abc import Mapping
|
|
4
|
+
from dataclasses import asdict, dataclass, field
|
|
5
|
+
from pathlib import Path
|
|
6
|
+
from typing import Any
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
# Variable of the XDG base directory for state files.
|
|
10
|
+
STATE_HOME_VARIABLE: str = "XDG_STATE_HOME"
|
|
11
|
+
|
|
12
|
+
# Default state home, under the user's home directory.
|
|
13
|
+
DEFAULT_STATE_HOME: str = ".local/state"
|
|
14
|
+
|
|
15
|
+
# Directory of JCCS inside the state home.
|
|
16
|
+
STATE_DIRECTORY_NAME: str = "jccs"
|
|
17
|
+
|
|
18
|
+
# State file of `jccs update`.
|
|
19
|
+
STATE_FILE_NAME: str = "update.json"
|
|
20
|
+
|
|
21
|
+
# Directory of the binaries kept for `--rollback` (GitHub release installs).
|
|
22
|
+
BACKUP_DIRECTORY_NAME: str = "backups"
|
|
23
|
+
|
|
24
|
+
# Version of the state file format.
|
|
25
|
+
STATE_VERSION: int = 1
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
@dataclass(slots=True)
|
|
29
|
+
class PreviousInstall:
|
|
30
|
+
"""
|
|
31
|
+
What `--rollback` restores.
|
|
32
|
+
(dataclass)
|
|
33
|
+
|
|
34
|
+
Attributes
|
|
35
|
+
----------
|
|
36
|
+
version : str
|
|
37
|
+
Version that was installed before the last update.
|
|
38
|
+
method : str
|
|
39
|
+
Install method at that time ("git", "pypi", "github-release").
|
|
40
|
+
reference : str
|
|
41
|
+
Git commit (git), or path of the kept binary (github-release), or "" (pypi).
|
|
42
|
+
"""
|
|
43
|
+
|
|
44
|
+
version: str
|
|
45
|
+
method: str
|
|
46
|
+
reference: str = ""
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
@dataclass(slots=True)
|
|
50
|
+
class UpdateState:
|
|
51
|
+
"""
|
|
52
|
+
Persistent settings and history of `jccs update` (per user).
|
|
53
|
+
(dataclass)
|
|
54
|
+
|
|
55
|
+
Attributes
|
|
56
|
+
----------
|
|
57
|
+
channel : str
|
|
58
|
+
Remembered channel ("stable" or "beta").
|
|
59
|
+
pinned : str | None
|
|
60
|
+
Pinned version, or None.
|
|
61
|
+
previous : PreviousInstall | None
|
|
62
|
+
Installation before the last update, for `--rollback`.
|
|
63
|
+
"""
|
|
64
|
+
|
|
65
|
+
channel: str = "stable"
|
|
66
|
+
pinned: str | None = None
|
|
67
|
+
previous: PreviousInstall | None = field(default=None)
|
|
68
|
+
|
|
69
|
+
|
|
70
|
+
def state_directory(environment: Mapping[str, str]) -> Path:
|
|
71
|
+
"""
|
|
72
|
+
Directory of the update state: $XDG_STATE_HOME/jccs, else ~/.local/state/jccs.
|
|
73
|
+
|
|
74
|
+
Parameters
|
|
75
|
+
----------
|
|
76
|
+
environment : Mapping[str, str]
|
|
77
|
+
Process environment.
|
|
78
|
+
|
|
79
|
+
Returns
|
|
80
|
+
----------
|
|
81
|
+
Path
|
|
82
|
+
The directory (not created).
|
|
83
|
+
"""
|
|
84
|
+
base: str | None = environment.get(STATE_HOME_VARIABLE)
|
|
85
|
+
home: Path = Path(base) if base and Path(base).is_absolute() else Path(environment.get("HOME") or Path.home()) / DEFAULT_STATE_HOME
|
|
86
|
+
return home / STATE_DIRECTORY_NAME
|
|
87
|
+
|
|
88
|
+
|
|
89
|
+
def load_state(directory: Path) -> UpdateState:
|
|
90
|
+
"""
|
|
91
|
+
Read the update state (defaults when missing or unreadable).
|
|
92
|
+
|
|
93
|
+
Parameters
|
|
94
|
+
----------
|
|
95
|
+
directory : Path
|
|
96
|
+
State directory.
|
|
97
|
+
|
|
98
|
+
Returns
|
|
99
|
+
----------
|
|
100
|
+
UpdateState
|
|
101
|
+
The state.
|
|
102
|
+
"""
|
|
103
|
+
try:
|
|
104
|
+
data: Any = json.loads((directory / STATE_FILE_NAME).read_text(encoding="utf-8"))
|
|
105
|
+
except (OSError, ValueError):
|
|
106
|
+
return UpdateState()
|
|
107
|
+
if not isinstance(data, dict):
|
|
108
|
+
return UpdateState()
|
|
109
|
+
previous: Any = data.get("previous")
|
|
110
|
+
restored: PreviousInstall | None = None
|
|
111
|
+
if isinstance(previous, dict) and previous.get("version") and previous.get("method"):
|
|
112
|
+
restored = PreviousInstall(str(previous["version"]), str(previous["method"]), str(previous.get("reference") or ""))
|
|
113
|
+
channel: str = data.get("channel") if data.get("channel") in ("stable", "beta") else "stable"
|
|
114
|
+
pinned: Any = data.get("pinned")
|
|
115
|
+
return UpdateState(channel, str(pinned) if pinned else None, restored)
|
|
116
|
+
|
|
117
|
+
|
|
118
|
+
def save_state(directory: Path, state: UpdateState) -> None:
|
|
119
|
+
"""
|
|
120
|
+
Write the update state atomically.
|
|
121
|
+
|
|
122
|
+
Parameters
|
|
123
|
+
----------
|
|
124
|
+
directory : Path
|
|
125
|
+
State directory (created when missing).
|
|
126
|
+
state : UpdateState
|
|
127
|
+
The state.
|
|
128
|
+
|
|
129
|
+
Returns
|
|
130
|
+
----------
|
|
131
|
+
None
|
|
132
|
+
Nothing.
|
|
133
|
+
|
|
134
|
+
Raises
|
|
135
|
+
----------
|
|
136
|
+
OSError
|
|
137
|
+
The directory cannot be written.
|
|
138
|
+
"""
|
|
139
|
+
directory.mkdir(parents=True, exist_ok=True)
|
|
140
|
+
payload: dict[str, Any] = {"schema_version": STATE_VERSION, **asdict(state)}
|
|
141
|
+
temporary: Path = directory / f".{STATE_FILE_NAME}.tmp"
|
|
142
|
+
temporary.write_text(json.dumps(payload, indent=2) + "\n", encoding="utf-8")
|
|
143
|
+
os.replace(temporary, directory / STATE_FILE_NAME)
|
|
File without changes
|
|
File without changes
|
|
@@ -0,0 +1,135 @@
|
|
|
1
|
+
from sources.diagnostics.model import SEVERITY_RANK, Diagnostic
|
|
2
|
+
from sources.enums import SeverityLevel
|
|
3
|
+
from sources.outputs.report import ReportView
|
|
4
|
+
|
|
5
|
+
|
|
6
|
+
# GitHub annotation command of each severity (plan 06, section 3).
|
|
7
|
+
COMMAND_BY_SEVERITY: dict[SeverityLevel, str] = {
|
|
8
|
+
SeverityLevel.INFO: "notice",
|
|
9
|
+
SeverityLevel.MINOR: "warning",
|
|
10
|
+
SeverityLevel.MAJOR: "error",
|
|
11
|
+
SeverityLevel.FATAL: "error",
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
# Command used for review items (heuristic and manual checks never fail the run).
|
|
15
|
+
REVIEW_COMMAND: str = "notice"
|
|
16
|
+
|
|
17
|
+
# Annotations GitHub keeps per job; beyond it a notice says the rest is only in the log (plan 08, section 5).
|
|
18
|
+
GITHUB_ANNOTATIONS_PER_JOB: int = 50
|
|
19
|
+
|
|
20
|
+
# Characters escaped in the message of a workflow command.
|
|
21
|
+
DATA_ESCAPES: tuple[tuple[str, str], ...] = (("%", "%25"), ("\r", "%0D"), ("\n", "%0A"))
|
|
22
|
+
|
|
23
|
+
# Characters escaped in the properties of a workflow command (in addition to DATA_ESCAPES).
|
|
24
|
+
PROPERTY_ESCAPES: tuple[tuple[str, str], ...] = DATA_ESCAPES + ((":", "%3A"), (",", "%2C"))
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
def escape_data(text: str) -> str:
|
|
28
|
+
"""
|
|
29
|
+
Escape the message part of a workflow command.
|
|
30
|
+
|
|
31
|
+
Parameters
|
|
32
|
+
----------
|
|
33
|
+
text : str
|
|
34
|
+
Raw text.
|
|
35
|
+
|
|
36
|
+
Returns
|
|
37
|
+
----------
|
|
38
|
+
str
|
|
39
|
+
Escaped text.
|
|
40
|
+
"""
|
|
41
|
+
for raw, escaped in DATA_ESCAPES:
|
|
42
|
+
text = text.replace(raw, escaped)
|
|
43
|
+
return text
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
def escape_property(text: str) -> str:
|
|
47
|
+
"""
|
|
48
|
+
Escape a property value of a workflow command.
|
|
49
|
+
|
|
50
|
+
Parameters
|
|
51
|
+
----------
|
|
52
|
+
text : str
|
|
53
|
+
Raw text.
|
|
54
|
+
|
|
55
|
+
Returns
|
|
56
|
+
----------
|
|
57
|
+
str
|
|
58
|
+
Escaped text.
|
|
59
|
+
"""
|
|
60
|
+
for raw, escaped in PROPERTY_ESCAPES:
|
|
61
|
+
text = text.replace(raw, escaped)
|
|
62
|
+
return text
|
|
63
|
+
|
|
64
|
+
|
|
65
|
+
def _annotation(view: ReportView, item: Diagnostic) -> str:
|
|
66
|
+
"""
|
|
67
|
+
Workflow command of one diagnostic.
|
|
68
|
+
|
|
69
|
+
Parameters
|
|
70
|
+
----------
|
|
71
|
+
view : ReportView
|
|
72
|
+
The report.
|
|
73
|
+
item : Diagnostic
|
|
74
|
+
The diagnostic.
|
|
75
|
+
|
|
76
|
+
Returns
|
|
77
|
+
----------
|
|
78
|
+
str
|
|
79
|
+
e.g. "::error file=src/a.c,line=3,col=5,title=C-C3::the goto keyword is forbidden".
|
|
80
|
+
"""
|
|
81
|
+
location = item.location
|
|
82
|
+
properties: list[tuple[str, str]] = [("file", location.path), ("line", str(location.line)), ("col", str(location.column))]
|
|
83
|
+
if location.end_line is not None:
|
|
84
|
+
properties.append(("endLine", str(location.end_line)))
|
|
85
|
+
if location.end_column is not None and location.end_line in (None, location.line):
|
|
86
|
+
properties.append(("endColumn", str(location.end_column)))
|
|
87
|
+
title: str = view.code(item) + (" (to review)" if item.review else "")
|
|
88
|
+
properties.append(("title", title))
|
|
89
|
+
command: str = REVIEW_COMMAND if item.review else COMMAND_BY_SEVERITY[item.severity]
|
|
90
|
+
rendered: str = ",".join(f"{key}={escape_property(value)}" for key, value in properties)
|
|
91
|
+
return f"::{command} {rendered}::{escape_data(view.message(item))}"
|
|
92
|
+
|
|
93
|
+
|
|
94
|
+
def render_github(view: ReportView, *, summary_only: bool, max_annotations: int | None = None) -> str:
|
|
95
|
+
"""
|
|
96
|
+
Render GitHub Actions workflow annotations (plan 08, section 6): one command per diagnostic, most severe
|
|
97
|
+
first, then a plain summary line. Every annotation is emitted; past the per-job limit a notice says that
|
|
98
|
+
GitHub only displays part of them.
|
|
99
|
+
|
|
100
|
+
Parameters
|
|
101
|
+
----------
|
|
102
|
+
view : ReportView
|
|
103
|
+
The report.
|
|
104
|
+
summary_only : bool
|
|
105
|
+
Whether only the summary line is written.
|
|
106
|
+
max_annotations : int | None
|
|
107
|
+
Largest number of annotations emitted (`--max-annotations`), or None for all.
|
|
108
|
+
|
|
109
|
+
Returns
|
|
110
|
+
----------
|
|
111
|
+
str
|
|
112
|
+
The commands, one per line, with a final newline.
|
|
113
|
+
"""
|
|
114
|
+
lines: list[str] = []
|
|
115
|
+
if not summary_only:
|
|
116
|
+
items: list[Diagnostic] = sorted(
|
|
117
|
+
view.report.result.diagnostics,
|
|
118
|
+
key=lambda item: (item.review, -SEVERITY_RANK[item.severity], item.sort_key()),
|
|
119
|
+
)
|
|
120
|
+
emitted: list[Diagnostic] = items if max_annotations is None else items[:max_annotations]
|
|
121
|
+
lines.extend(_annotation(view, item) for item in emitted)
|
|
122
|
+
if len(emitted) < len(items):
|
|
123
|
+
hidden: str = f"{len(items) - len(emitted)} more finding(s) not annotated (--max-annotations {max_annotations}); see the full report (--report)"
|
|
124
|
+
lines.append(f"::notice title={escape_property('jccs')}::{escape_data(hidden)}")
|
|
125
|
+
elif len(emitted) > GITHUB_ANNOTATIONS_PER_JOB:
|
|
126
|
+
notice: str = (
|
|
127
|
+
f"{len(emitted)} annotations emitted; GitHub displays at most {GITHUB_ANNOTATIONS_PER_JOB} per job, "
|
|
128
|
+
"the others are only in this log (use --report for a full artifact)"
|
|
129
|
+
)
|
|
130
|
+
lines.append(f"::notice title={escape_property('jccs')}::{escape_data(notice)}")
|
|
131
|
+
totals: dict[str, int] = view.severity_totals(view.findings)
|
|
132
|
+
counts: str = ", ".join(f"{count} {name}" for name, count in totals.items())
|
|
133
|
+
fixed: str = f", {len(view.report.fixes)} fixed" if view.report.fixing else ""
|
|
134
|
+
lines.append(f"jccs: {len(view.findings)} finding(s) ({counts}), {len(view.review_items)} to review{fixed}; {view.report.outcome.reason}")
|
|
135
|
+
return "\n".join(lines) + "\n"
|
|
File without changes
|