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,529 @@
1
+ import hashlib
2
+ import os
3
+ import shutil
4
+ import stat
5
+ import subprocess
6
+ import sys
7
+ import tempfile
8
+ from collections.abc import Callable, Mapping
9
+ from dataclasses import dataclass
10
+ from pathlib import Path
11
+
12
+ from sources.errors.exceptions import ProjectEnvironmentError
13
+ from sources.integrations.git.repository import run_git
14
+ from sources.integrations.update.releases import DISTRIBUTION_NAME, Fetcher, Release, git_tag_releases, github_releases, pypi_releases
15
+ from sources.integrations.update.state import BACKUP_DIRECTORY_NAME, PreviousInstall
16
+
17
+
18
+ # Install methods (build_info sources, plan 12).
19
+ METHOD_GIT: str = "git"
20
+ METHOD_PYPI: str = "pypi"
21
+ METHOD_RELEASE: str = "github-release"
22
+ METHOD_UNKNOWN: str = "unknown"
23
+
24
+ # Installers of a PyPI install.
25
+ INSTALLER_PIPX: str = "pipx"
26
+ INSTALLER_UV: str = "uv"
27
+ INSTALLER_PIP: str = "pip"
28
+
29
+ # Longest time given to an installer, in seconds.
30
+ INSTALL_TIMEOUT: float = 900.0
31
+
32
+ # Name of the platform in the GitHub release assets (`jccs-<version>-<os>[.exe]`).
33
+ PLATFORM_NAMES: tuple[tuple[str, str], ...] = (("linux", "linux"), ("darwin", "macos"), ("win", "windows"))
34
+
35
+ # Runs a command (argument list, working directory) and returns (exit code, output); injectable for tests.
36
+ CommandRunner = Callable[[list[str], Path | None], tuple[int, str]]
37
+
38
+
39
+ @dataclass(frozen=True, slots=True)
40
+ class InstallTarget:
41
+ """
42
+ How the running JCCS is installed.
43
+ (dataclass)
44
+
45
+ Attributes
46
+ ----------
47
+ method : str
48
+ "git", "pypi", "github-release" or "unknown".
49
+ installer : str | None
50
+ "pipx", "uv" or "pip" for a PyPI install.
51
+ location : Path
52
+ Repository root (git), Python prefix (pypi) or executable (github-release).
53
+ problem : str | None
54
+ Why this installation cannot be updated by JCCS (None when it can).
55
+ """
56
+
57
+ method: str
58
+ installer: str | None
59
+ location: Path
60
+ problem: str | None = None
61
+
62
+
63
+ def run_command(arguments: list[str], directory: Path | None) -> tuple[int, str]:
64
+ """
65
+ Run a command with an argument list (no shell) and a timeout.
66
+
67
+ Parameters
68
+ ----------
69
+ arguments : list[str]
70
+ Command and arguments.
71
+ directory : Path | None
72
+ Working directory.
73
+
74
+ Returns
75
+ ----------
76
+ tuple[int, str]
77
+ Exit code and combined output.
78
+ """
79
+ try:
80
+ completed: subprocess.CompletedProcess[bytes] = subprocess.run(arguments, cwd=directory, capture_output=True, timeout=INSTALL_TIMEOUT, check=False)
81
+ except FileNotFoundError:
82
+ return 127, f"{arguments[0]}: command not found"
83
+ except subprocess.TimeoutExpired:
84
+ return 124, f"{arguments[0]} timed out after {INSTALL_TIMEOUT:g} s"
85
+ return completed.returncode, (completed.stdout + completed.stderr).decode("utf-8", "replace")
86
+
87
+
88
+ def platform_name(platform: str = sys.platform) -> str | None:
89
+ """
90
+ Platform name used in release asset names.
91
+
92
+ Parameters
93
+ ----------
94
+ platform : str
95
+ sys.platform value.
96
+
97
+ Returns
98
+ ----------
99
+ str | None
100
+ "linux", "macos", "windows", or None for another platform.
101
+ """
102
+ return next((name for prefix, name in PLATFORM_NAMES if platform.startswith(prefix)), None)
103
+
104
+
105
+ def asset_name(version: str, platform: str = sys.platform) -> str | None:
106
+ """
107
+ Name of the release binary of a version for a platform (plan 12: `jccs-<version>-<os>[.exe]`).
108
+
109
+ Parameters
110
+ ----------
111
+ version : str
112
+ Version.
113
+ platform : str
114
+ sys.platform value.
115
+
116
+ Returns
117
+ ----------
118
+ str | None
119
+ The asset name, or None for an unsupported platform.
120
+ """
121
+ name: str | None = platform_name(platform)
122
+ if name is None:
123
+ return None
124
+ return f"jccs-{version}-{name}" + (".exe" if name == "windows" else "")
125
+
126
+
127
+ def detect_install(
128
+ source: str,
129
+ root: Path,
130
+ *,
131
+ prefix: str = sys.prefix,
132
+ base_prefix: str = sys.base_prefix,
133
+ frozen: bool = bool(getattr(sys, "frozen", False)),
134
+ executable: str = sys.executable,
135
+ ) -> InstallTarget:
136
+ """
137
+ Install method of the running JCCS (build_info source, plan 12) and, for PyPI, the installer that owns
138
+ it (pipx venv, uv tool, or a virtual environment for pip).
139
+
140
+ Parameters
141
+ ----------
142
+ source : str
143
+ build_info source ("git", "pypi", "github-release", "unknown").
144
+ root : Path
145
+ JCCS installation root.
146
+ prefix : str
147
+ sys.prefix.
148
+ base_prefix : str
149
+ sys.base_prefix.
150
+ frozen : bool
151
+ Whether JCCS runs as a standalone binary.
152
+ executable : str
153
+ sys.executable.
154
+
155
+ Returns
156
+ ----------
157
+ InstallTarget
158
+ The target.
159
+ """
160
+ if source == METHOD_GIT:
161
+ return InstallTarget(METHOD_GIT, None, root)
162
+ if source == METHOD_PYPI:
163
+ parts: tuple[str, ...] = Path(prefix).parts
164
+ if any(parts[index:index + 2] == ("pipx", "venvs") for index in range(len(parts))):
165
+ return InstallTarget(METHOD_PYPI, INSTALLER_PIPX, Path(prefix))
166
+ if any(parts[index:index + 2] == ("uv", "tools") for index in range(len(parts))):
167
+ return InstallTarget(METHOD_PYPI, INSTALLER_UV, Path(prefix))
168
+ if prefix != base_prefix:
169
+ return InstallTarget(METHOD_PYPI, INSTALLER_PIP, Path(prefix))
170
+ return InstallTarget(METHOD_PYPI, None, Path(prefix), "JCCS is installed in the system Python; jccs does not modify it (no sudo)")
171
+ if source == METHOD_RELEASE:
172
+ if not frozen:
173
+ return InstallTarget(METHOD_RELEASE, None, Path(executable), "this GitHub release is not a standalone binary")
174
+ return InstallTarget(METHOD_RELEASE, None, Path(executable))
175
+ return InstallTarget(METHOD_UNKNOWN, None, root, "the install method is unknown (no git checkout, no release information)")
176
+
177
+
178
+ def manual_command(target: InstallTarget, version: str) -> str:
179
+ """
180
+ Command a user can run to install a version by hand.
181
+
182
+ Parameters
183
+ ----------
184
+ target : InstallTarget
185
+ The installation.
186
+ version : str
187
+ Version.
188
+
189
+ Returns
190
+ ----------
191
+ str
192
+ The command.
193
+ """
194
+ if target.method == METHOD_GIT:
195
+ return f"git -C {target.location} fetch --tags origin && git -C {target.location} checkout v{version}"
196
+ if target.method == METHOD_RELEASE:
197
+ return f"download {asset_name(version) or 'the binary'} from https://github.com/Jarjarbin06/Jarbin-C-Coding-Style/releases/tag/v{version}"
198
+ return f"pipx install --force {DISTRIBUTION_NAME}=={version}"
199
+
200
+
201
+ def available_releases(target: InstallTarget, fetch: Fetcher, environment: Mapping[str, str]) -> list[Release]:
202
+ """
203
+ Releases this installation can move to: tags of the git remote, PyPI releases, or GitHub releases.
204
+
205
+ Parameters
206
+ ----------
207
+ target : InstallTarget
208
+ The installation.
209
+ fetch : Fetcher
210
+ HTTP fetcher.
211
+ environment : Mapping[str, str]
212
+ Process environment.
213
+
214
+ Returns
215
+ ----------
216
+ list[Release]
217
+ The releases.
218
+
219
+ Raises
220
+ ----------
221
+ ProjectEnvironmentError
222
+ Network or git failure.
223
+ """
224
+ if target.method == METHOD_GIT:
225
+ output: str = run_git(target.location, "ls-remote", "--tags", "--refs", "origin", environment=environment).decode("utf-8", "replace")
226
+ tags: list[str] = [line.split("refs/tags/", 1)[1] for line in output.splitlines() if "refs/tags/" in line]
227
+ return git_tag_releases(tags)
228
+ if target.method == METHOD_RELEASE:
229
+ return github_releases(fetch, environment)
230
+ return pypi_releases(fetch, environment)
231
+
232
+
233
+ def _install_git(target: InstallTarget, release: Release, environment: Mapping[str, str], runner: CommandRunner) -> str:
234
+ """
235
+ Move a git checkout to a release tag (refused when the working tree has changes), then sync the
236
+ dependencies with uv.
237
+
238
+ Parameters
239
+ ----------
240
+ target : InstallTarget
241
+ The installation.
242
+ release : Release
243
+ Target release.
244
+ environment : Mapping[str, str]
245
+ Process environment.
246
+ runner : CommandRunner
247
+ Command runner (uv).
248
+
249
+ Returns
250
+ ----------
251
+ str
252
+ Commit checked out before the change.
253
+
254
+ Raises
255
+ ----------
256
+ ProjectEnvironmentError
257
+ Local changes, unknown tag, or git failure.
258
+ """
259
+ root: Path = target.location
260
+ if run_git(root, "status", "--porcelain", "--untracked-files=no", environment=environment).strip():
261
+ raise ProjectEnvironmentError(f"The JCCS checkout '{root}' has local changes.", "Commit or stash them, then run jccs update again.")
262
+ previous: str = run_git(root, "rev-parse", "HEAD", environment=environment).decode().strip()
263
+ run_git(root, "fetch", "--tags", "--quiet", "origin", environment=environment)
264
+ run_git(root, "checkout", "--quiet", "--end-of-options", f"refs/tags/{release.tag}", environment=environment)
265
+ _sync_dependencies(root, runner)
266
+ return previous
267
+
268
+
269
+ def _sync_dependencies(root: Path, runner: CommandRunner) -> None:
270
+ """
271
+ Sync the virtual environment of a git checkout (`uv sync`), when uv is available.
272
+
273
+ Parameters
274
+ ----------
275
+ root : Path
276
+ Repository root.
277
+ runner : CommandRunner
278
+ Command runner.
279
+
280
+ Returns
281
+ ----------
282
+ None
283
+ Nothing.
284
+
285
+ Raises
286
+ ----------
287
+ ProjectEnvironmentError
288
+ uv failed.
289
+ """
290
+ if shutil.which("uv") is None:
291
+ return
292
+ code, output = runner(["uv", "sync"], root)
293
+ if code != 0:
294
+ raise ProjectEnvironmentError(f"uv sync failed in '{root}': {output.strip().splitlines()[-1] if output.strip() else code}.", "Run make update in the checkout.")
295
+
296
+
297
+ def _install_pypi(target: InstallTarget, version: str, runner: CommandRunner) -> None:
298
+ """
299
+ Install a PyPI version with the installer that owns this installation.
300
+
301
+ Parameters
302
+ ----------
303
+ target : InstallTarget
304
+ The installation.
305
+ version : str
306
+ Version.
307
+ runner : CommandRunner
308
+ Command runner.
309
+
310
+ Returns
311
+ ----------
312
+ None
313
+ Nothing.
314
+
315
+ Raises
316
+ ----------
317
+ ProjectEnvironmentError
318
+ The installer is missing or failed.
319
+ """
320
+ requirement: str = f"{DISTRIBUTION_NAME}=={version}"
321
+ commands: dict[str, list[str]] = {
322
+ INSTALLER_PIPX: ["pipx", "install", "--force", requirement],
323
+ INSTALLER_UV: ["uv", "tool", "install", "--force", requirement],
324
+ INSTALLER_PIP: [str(target.location / ("Scripts" if os.name == "nt" else "bin") / ("python.exe" if os.name == "nt" else "python")), "-m", "pip", "install", requirement],
325
+ }
326
+ command: list[str] = commands[target.installer or INSTALLER_PIP]
327
+ if command[0] in ("pipx", "uv") and shutil.which(command[0]) is None:
328
+ raise ProjectEnvironmentError(f"{command[0]} is not on the PATH.", f"Install it, or run: {' '.join(command)}")
329
+ code, output = runner(command, None)
330
+ if code != 0:
331
+ tail: str = output.strip().splitlines()[-1] if output.strip() else f"exit {code}"
332
+ raise ProjectEnvironmentError(f"{command[0]} failed: {tail}", f"Run it by hand: {' '.join(command)}")
333
+
334
+
335
+ def _sha256_of(text: str) -> str | None:
336
+ """
337
+ Hash of a `.sha256` file (`<hex>` or `<hex> <name>`).
338
+
339
+ Parameters
340
+ ----------
341
+ text : str
342
+ File content.
343
+
344
+ Returns
345
+ ----------
346
+ str | None
347
+ The lowercase hash, or None when the file is not a SHA-256 file.
348
+ """
349
+ token: str = text.strip().split()[0].lower() if text.strip() else ""
350
+ return token if len(token) == 64 and all(character in "0123456789abcdef" for character in token) else None
351
+
352
+
353
+ def _replace_binary(executable: Path, content: bytes) -> None:
354
+ """
355
+ Replace the running executable atomically (on Windows the running file is renamed first).
356
+
357
+ Parameters
358
+ ----------
359
+ executable : Path
360
+ The executable.
361
+ content : bytes
362
+ New binary.
363
+
364
+ Returns
365
+ ----------
366
+ None
367
+ Nothing.
368
+
369
+ Raises
370
+ ----------
371
+ ProjectEnvironmentError
372
+ No write permission.
373
+ """
374
+ directory: Path = executable.parent
375
+ if not os.access(directory, os.W_OK):
376
+ raise ProjectEnvironmentError(f"No write permission on '{directory}'.", "Reinstall JCCS where you can write, or replace the binary yourself (jccs never uses sudo).")
377
+ descriptor, temporary = tempfile.mkstemp(dir=directory, prefix=".jccs-update-")
378
+ try:
379
+ with os.fdopen(descriptor, "wb") as stream:
380
+ stream.write(content)
381
+ stream.flush()
382
+ os.fsync(stream.fileno())
383
+ os.chmod(temporary, stat.S_IMODE(executable.stat().st_mode) | stat.S_IXUSR)
384
+ if os.name == "nt":
385
+ os.replace(executable, executable.with_name(executable.name + ".old"))
386
+ os.replace(temporary, executable)
387
+ except BaseException:
388
+ Path(temporary).unlink(missing_ok=True)
389
+ raise
390
+
391
+
392
+ def _install_release(target: InstallTarget, release: Release, current_version: str, fetch: Fetcher, state_directory: Path) -> str:
393
+ """
394
+ Replace a standalone binary by the release asset of this platform, after checking its SHA-256 against
395
+ the `.sha256` file of the release; the current binary is kept for --rollback.
396
+
397
+ Parameters
398
+ ----------
399
+ target : InstallTarget
400
+ The installation.
401
+ release : Release
402
+ Target release.
403
+ current_version : str
404
+ Running version.
405
+ fetch : Fetcher
406
+ HTTP fetcher.
407
+ state_directory : Path
408
+ Update state directory.
409
+
410
+ Returns
411
+ ----------
412
+ str
413
+ Path of the kept binary.
414
+
415
+ Raises
416
+ ----------
417
+ ProjectEnvironmentError
418
+ Missing asset or checksum, checksum mismatch, or no write permission.
419
+ """
420
+ name: str | None = asset_name(release.version.text)
421
+ if name is None:
422
+ raise ProjectEnvironmentError(f"No release binary for this platform ({sys.platform}).")
423
+ if name not in release.assets or f"{name}.sha256" not in release.assets:
424
+ raise ProjectEnvironmentError(f"Release {release.tag} has no {name} with its {name}.sha256.")
425
+ expected: str | None = _sha256_of(fetch(release.assets[f"{name}.sha256"]).decode("utf-8", "replace"))
426
+ if expected is None:
427
+ raise ProjectEnvironmentError(f"{name}.sha256 of release {release.tag} is not a SHA-256 checksum.")
428
+ binary: bytes = fetch(release.assets[name])
429
+ if hashlib.sha256(binary).hexdigest() != expected:
430
+ raise ProjectEnvironmentError(f"Checksum mismatch for {name}: the download is corrupted or tampered with.", "Nothing was replaced.")
431
+ backups: Path = state_directory / BACKUP_DIRECTORY_NAME
432
+ backups.mkdir(parents=True, exist_ok=True)
433
+ kept: Path = backups / (asset_name(current_version) or f"jccs-{current_version}")
434
+ shutil.copy2(target.location, kept)
435
+ _replace_binary(target.location, binary)
436
+ return str(kept)
437
+
438
+
439
+ def install(
440
+ target: InstallTarget,
441
+ release: Release,
442
+ current_version: str,
443
+ *,
444
+ fetch: Fetcher,
445
+ runner: CommandRunner,
446
+ environment: Mapping[str, str],
447
+ state_directory: Path,
448
+ ) -> PreviousInstall:
449
+ """
450
+ Install a release with the method of this installation.
451
+
452
+ Parameters
453
+ ----------
454
+ target : InstallTarget
455
+ The installation.
456
+ release : Release
457
+ Target release.
458
+ current_version : str
459
+ Running version.
460
+ fetch : Fetcher
461
+ HTTP fetcher.
462
+ runner : CommandRunner
463
+ Command runner.
464
+ environment : Mapping[str, str]
465
+ Process environment.
466
+ state_directory : Path
467
+ Update state directory.
468
+
469
+ Returns
470
+ ----------
471
+ PreviousInstall
472
+ What --rollback needs to come back.
473
+
474
+ Raises
475
+ ----------
476
+ ProjectEnvironmentError
477
+ The installation cannot be updated, or the update failed.
478
+ """
479
+ if target.problem is not None:
480
+ raise ProjectEnvironmentError(f"Cannot update: {target.problem}.", f"Install it yourself: {manual_command(target, release.version.text)}")
481
+ if target.method == METHOD_GIT:
482
+ return PreviousInstall(current_version, METHOD_GIT, _install_git(target, release, environment, runner))
483
+ if target.method == METHOD_RELEASE:
484
+ return PreviousInstall(current_version, METHOD_RELEASE, _install_release(target, release, current_version, fetch, state_directory))
485
+ _install_pypi(target, release.version.text, runner)
486
+ return PreviousInstall(current_version, METHOD_PYPI)
487
+
488
+
489
+ def restore(target: InstallTarget, previous: PreviousInstall, *, runner: CommandRunner, environment: Mapping[str, str]) -> None:
490
+ """
491
+ Go back to the installation recorded before the last update (`--rollback`).
492
+
493
+ Parameters
494
+ ----------
495
+ target : InstallTarget
496
+ The installation.
497
+ previous : PreviousInstall
498
+ What was installed before.
499
+ runner : CommandRunner
500
+ Command runner.
501
+ environment : Mapping[str, str]
502
+ Process environment.
503
+
504
+ Returns
505
+ ----------
506
+ None
507
+ Nothing.
508
+
509
+ Raises
510
+ ----------
511
+ ProjectEnvironmentError
512
+ The method changed since, the kept binary is missing, or the reinstall failed.
513
+ """
514
+ if target.problem is not None:
515
+ raise ProjectEnvironmentError(f"Cannot roll back: {target.problem}.")
516
+ if previous.method != target.method:
517
+ raise ProjectEnvironmentError(f"The previous version was installed with {previous.method}, this one with {target.method}.", "Reinstall it by hand.")
518
+ if target.method == METHOD_GIT:
519
+ if run_git(target.location, "status", "--porcelain", "--untracked-files=no", environment=environment).strip():
520
+ raise ProjectEnvironmentError(f"The JCCS checkout '{target.location}' has local changes.", "Commit or stash them first.")
521
+ run_git(target.location, "checkout", "--quiet", "--end-of-options", previous.reference, environment=environment)
522
+ _sync_dependencies(target.location, runner)
523
+ elif target.method == METHOD_RELEASE:
524
+ kept: Path = Path(previous.reference)
525
+ if not kept.is_file():
526
+ raise ProjectEnvironmentError(f"The kept binary '{kept}' is missing.")
527
+ _replace_binary(target.location, kept.read_bytes())
528
+ else:
529
+ _install_pypi(target, previous.version, runner)