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,408 @@
1
+ import json
2
+ from dataclasses import dataclass
3
+ from pathlib import Path
4
+ from typing import Any
5
+
6
+ from sources.cli.context import CommandArguments, ParsedArguments
7
+ from sources.constants import PROGRAM_NAME, PROGRAM_VERSION
8
+ from sources.enums import ExitCode
9
+ from sources.errors.exceptions import ProjectEnvironmentError, UsageError
10
+ from sources.integrations.git.repository import run_git
11
+ from sources.integrations.update.installers import (
12
+ METHOD_GIT,
13
+ METHOD_RELEASE,
14
+ CommandRunner,
15
+ InstallTarget,
16
+ available_releases,
17
+ detect_install,
18
+ install,
19
+ manual_command,
20
+ restore,
21
+ run_command,
22
+ )
23
+ from sources.integrations.update.releases import Fetcher, Release, Version, find_release, http_fetcher, parse_release_version, release_notes, select_latest
24
+ from sources.integrations.update.state import PreviousInstall, UpdateState, load_state, save_state, state_directory
25
+ from sources.services import Services
26
+ from sources.utils.build_info import INSTALL_ROOT, BuildInfo, collect_build_info
27
+
28
+
29
+ # Version of the `update --json` output.
30
+ UPDATE_REPORT_VERSION: int = 1
31
+
32
+ # `--pin` value that removes the pin and installs the latest version of the channel.
33
+ PIN_LATEST: str = "latest"
34
+
35
+ # Answers accepted by the confirmation prompt.
36
+ YES_ANSWERS: frozenset[str] = frozenset({"y", "yes"})
37
+
38
+
39
+ @dataclass(frozen=True, slots=True)
40
+ class UpdateContext:
41
+ """
42
+ Everything `update` works with; the network and the commands are injectable for tests.
43
+ (dataclass)
44
+
45
+ Attributes
46
+ ----------
47
+ services : Services
48
+ Process seams.
49
+ environment : Any
50
+ Environment used for git and HTTP (None: the process environment).
51
+ fetch : Fetcher
52
+ HTTP fetcher.
53
+ runner : CommandRunner
54
+ Command runner (installers, uv).
55
+ build : BuildInfo
56
+ Where the running JCCS comes from.
57
+ target : InstallTarget
58
+ Install method.
59
+ current : Version
60
+ Running version.
61
+ state_directory : Path
62
+ Update state directory.
63
+ state : UpdateState
64
+ Remembered channel, pin and previous install.
65
+ """
66
+
67
+ services: Services
68
+ environment: Any
69
+ fetch: Fetcher
70
+ runner: CommandRunner
71
+ build: BuildInfo
72
+ target: InstallTarget
73
+ current: Version
74
+ state_directory: Path
75
+ state: UpdateState
76
+
77
+
78
+ def _context(services: Services, fetch: Fetcher | None, runner: CommandRunner | None, build: BuildInfo | None, target: InstallTarget | None) -> UpdateContext:
79
+ """
80
+ Build the context of a run.
81
+
82
+ Parameters
83
+ ----------
84
+ services : Services
85
+ Process seams.
86
+ fetch : Fetcher | None
87
+ HTTP fetcher (default: the network).
88
+ runner : CommandRunner | None
89
+ Command runner (default: subprocess).
90
+ build : BuildInfo | None
91
+ Build information (default: detected).
92
+ target : InstallTarget | None
93
+ Install method (default: detected).
94
+
95
+ Returns
96
+ ----------
97
+ UpdateContext
98
+ The context.
99
+ """
100
+ environment: Any = services.env or None
101
+ build = build or collect_build_info()
102
+ current: Version = parse_release_version(build.version) or parse_release_version(PROGRAM_VERSION) # type: ignore[assignment]
103
+ directory: Path = state_directory(services.env)
104
+ return UpdateContext(
105
+ services=services,
106
+ environment=environment,
107
+ fetch=fetch or http_fetcher(services.env),
108
+ runner=runner or run_command,
109
+ build=build,
110
+ target=target or detect_install(build.source, INSTALL_ROOT),
111
+ current=current,
112
+ state_directory=directory,
113
+ state=load_state(directory),
114
+ )
115
+
116
+
117
+ def _describe(context: UpdateContext) -> str:
118
+ """
119
+ Short description of the installation.
120
+
121
+ Parameters
122
+ ----------
123
+ context : UpdateContext
124
+ The context.
125
+
126
+ Returns
127
+ ----------
128
+ str
129
+ e.g. "jccs 2.0.0 (pypi via pipx)".
130
+ """
131
+ target: InstallTarget = context.target
132
+ method: str = f"{target.method} via {target.installer}" if target.installer else target.method
133
+ return f"{PROGRAM_NAME} {context.current.text} ({method})"
134
+
135
+
136
+ def _payload(context: UpdateContext, action: str, channel: str, latest: Release | None, **extra: Any) -> dict[str, Any]:
137
+ """
138
+ JSON output of a run.
139
+
140
+ Parameters
141
+ ----------
142
+ context : UpdateContext
143
+ The context.
144
+ action : str
145
+ "check", "update", "pin", "rollback" or "notes".
146
+ channel : str
147
+ Channel used.
148
+ latest : Release | None
149
+ Latest release of the channel.
150
+ **extra : Any
151
+ Action-specific keys.
152
+
153
+ Returns
154
+ ----------
155
+ dict[str, Any]
156
+ The object.
157
+ """
158
+ return {
159
+ "schema_version": UPDATE_REPORT_VERSION,
160
+ "action": action,
161
+ "current": context.current.text,
162
+ "latest": latest.version.text if latest else None,
163
+ "channel": channel,
164
+ "pinned": context.state.pinned,
165
+ "install": {
166
+ "method": context.target.method,
167
+ "installer": context.target.installer,
168
+ "location": str(context.target.location),
169
+ "updatable": context.target.problem is None,
170
+ },
171
+ **extra,
172
+ }
173
+
174
+
175
+ def _emit(context: UpdateContext, as_json: bool, payload: dict[str, Any], text: str) -> None:
176
+ """
177
+ Write the result (JSON object or text) on stdout.
178
+
179
+ Parameters
180
+ ----------
181
+ context : UpdateContext
182
+ The context.
183
+ as_json : bool
184
+ JSON output.
185
+ payload : dict[str, Any]
186
+ JSON object.
187
+ text : str
188
+ Text output.
189
+
190
+ Returns
191
+ ----------
192
+ None
193
+ Nothing.
194
+ """
195
+ context.services.stdout.write(json.dumps(payload, indent=2) + "\n" if as_json else text.rstrip("\n") + "\n")
196
+
197
+
198
+ def _confirm(context: UpdateContext, question: str, assume_yes: bool) -> bool:
199
+ """
200
+ Ask before changing the installation (plan 02: never hang without a terminal).
201
+
202
+ Parameters
203
+ ----------
204
+ context : UpdateContext
205
+ The context.
206
+ question : str
207
+ The question.
208
+ assume_yes : bool
209
+ `--yes`.
210
+
211
+ Returns
212
+ ----------
213
+ bool
214
+ True to proceed.
215
+
216
+ Raises
217
+ ----------
218
+ UsageError
219
+ No --yes and standard input is not a terminal.
220
+ """
221
+ if assume_yes:
222
+ return True
223
+ services: Services = context.services
224
+ if not services.is_tty(services.stdin):
225
+ raise UsageError("Cannot prompt for confirmation: standard input is not a terminal.", "Add --yes to update without confirmation.")
226
+ services.stderr.write(f"{question} [y/N] ")
227
+ services.stderr.flush()
228
+ return services.stdin.readline().strip().lower() in YES_ANSWERS
229
+
230
+
231
+ def _save(context: UpdateContext) -> None:
232
+ """
233
+ Save the update state.
234
+
235
+ Parameters
236
+ ----------
237
+ context : UpdateContext
238
+ The context.
239
+
240
+ Returns
241
+ ----------
242
+ None
243
+ Nothing.
244
+
245
+ Raises
246
+ ----------
247
+ ProjectEnvironmentError
248
+ The state directory cannot be written.
249
+ """
250
+ try:
251
+ save_state(context.state_directory, context.state)
252
+ except OSError as error:
253
+ raise ProjectEnvironmentError(f"Cannot write the update state in '{context.state_directory}': {error.strerror}.") from None
254
+
255
+
256
+ def _rollback(context: UpdateContext, as_json: bool, assume_yes: bool) -> ExitCode:
257
+ """
258
+ `--rollback`: reinstall the version recorded before the last update; the pin is removed and the two
259
+ installs swap (a second --rollback goes forward again).
260
+
261
+ Parameters
262
+ ----------
263
+ context : UpdateContext
264
+ The context.
265
+ as_json : bool
266
+ JSON output.
267
+ assume_yes : bool
268
+ `--yes`.
269
+
270
+ Returns
271
+ ----------
272
+ ExitCode
273
+ OK.
274
+
275
+ Raises
276
+ ----------
277
+ ProjectEnvironmentError
278
+ Nothing to roll back to, or the rollback failed.
279
+ """
280
+ previous = context.state.previous
281
+ if previous is None:
282
+ raise ProjectEnvironmentError("Nothing to roll back to: no update was recorded.")
283
+ if not _confirm(context, f"Roll back {_describe(context)} to {previous.version}?", assume_yes):
284
+ context.services.stderr.write("jccs: rollback cancelled\n")
285
+ return ExitCode.OK
286
+ restore(context.target, previous, runner=context.runner, environment=context.environment)
287
+ reference: str = previous.reference if context.target.method == METHOD_RELEASE else ""
288
+ if context.target.method == METHOD_GIT:
289
+ reference = run_git(context.target.location, "rev-parse", "HEAD", environment=context.environment).decode().strip()
290
+ context.state.previous = PreviousInstall(context.current.text, context.target.method, reference)
291
+ context.state.pinned = None
292
+ _save(context)
293
+ _emit(context, as_json, _payload(context, "rollback", context.state.channel, None, result="rolled_back", to=previous.version),
294
+ f"Rolled back {PROGRAM_NAME} from {context.current.text} to {previous.version}.")
295
+ return ExitCode.OK
296
+
297
+
298
+ def run_update(
299
+ arguments: ParsedArguments,
300
+ services: Services,
301
+ *,
302
+ fetch: Fetcher | None = None,
303
+ runner: CommandRunner | None = None,
304
+ build: BuildInfo | None = None,
305
+ target: InstallTarget | None = None,
306
+ ) -> ExitCode:
307
+ """
308
+ `jccs update` (plan 02 section 7, plan 12): check, install, pin, roll back JCCS itself, and print release
309
+ notes. The install method (git checkout, PyPI, GitHub release binary) decides how; the channel and the pin
310
+ are remembered per user. The only command that uses the network (plan 01).
311
+
312
+ Parameters
313
+ ----------
314
+ arguments : ParsedArguments
315
+ Parsed command line.
316
+ services : Services
317
+ Process seams.
318
+ fetch : Fetcher | None
319
+ HTTP fetcher (tests).
320
+ runner : CommandRunner | None
321
+ Command runner (tests).
322
+ build : BuildInfo | None
323
+ Build information (tests).
324
+ target : InstallTarget | None
325
+ Install method (tests).
326
+
327
+ Returns
328
+ ----------
329
+ ExitCode
330
+ OK, or UPDATE_AVAILABLE (10) for `--check` when a newer version exists.
331
+
332
+ Raises
333
+ ----------
334
+ UsageError
335
+ Unknown --pin version, or no terminal to confirm.
336
+ ProjectEnvironmentError
337
+ Network failure, unsupported install method, or failed installation.
338
+ """
339
+ flags: CommandArguments = arguments.command
340
+ context: UpdateContext = _context(services, fetch, runner, build, target)
341
+ as_json: bool = flags["json"].is_called
342
+ assume_yes: bool = flags["yes"].is_called
343
+ if flags["rollback"].is_called:
344
+ return _rollback(context, as_json, assume_yes)
345
+ channel: str = str(flags["channel"].value) if flags["channel"].is_called else context.state.channel
346
+ releases: list[Release] = available_releases(context.target, context.fetch, context.environment or services.env)
347
+ latest: Release | None = select_latest(releases, beta=channel == "beta")
348
+ pin: str | None = str(flags["pin"].value) if flags["pin"].is_called else None
349
+ if flags["notes"].is_called:
350
+ wanted: Release | None = latest if pin in (None, PIN_LATEST) else find_release(releases, pin)
351
+ if wanted is None:
352
+ raise UsageError(f"No release {pin or 'on the ' + channel + ' channel'}.")
353
+ notes: str = release_notes(context.fetch, services.env, wanted)
354
+ _emit(context, as_json, _payload(context, "notes", channel, latest, version=wanted.version.text, notes=notes), notes)
355
+ return ExitCode.OK
356
+ if flags["check"].is_called:
357
+ pinned: str | None = context.state.pinned
358
+ available: bool = latest is not None and latest.version > context.current and pinned is None
359
+ if latest is None:
360
+ text: str = f"{_describe(context)}: no release on the {channel} channel"
361
+ elif pinned is not None:
362
+ text = f"{_describe(context)}: pinned to {pinned} (latest {channel}: {latest.version.text})"
363
+ elif available:
364
+ text = f"{_describe(context)}: update available: {latest.version.text} ({channel})"
365
+ else:
366
+ text = f"{_describe(context)}: up to date ({channel})"
367
+ _emit(context, as_json, _payload(context, "check", channel, latest, update_available=available), text)
368
+ return ExitCode.UPDATE_AVAILABLE if available else ExitCode.OK
369
+ new_pin: str | None = context.state.pinned
370
+ if pin is not None:
371
+ desired: Release | None = latest if pin == PIN_LATEST else find_release(releases, pin)
372
+ if desired is None:
373
+ known: str = ", ".join(release.version.text for release in sorted(releases, key=lambda item: item.version, reverse=True)[:5]) or "none"
374
+ raise UsageError(f"No release {pin}." if pin != PIN_LATEST else f"No release on the {channel} channel.", f"Recent releases: {known}.")
375
+ new_pin = None if pin == PIN_LATEST else desired.version.text
376
+ elif context.state.pinned is not None:
377
+ _emit(context, as_json, _payload(context, "update", channel, latest, result="pinned"),
378
+ f"{_describe(context)} is pinned to {context.state.pinned}; run jccs update --pin latest to unpin.")
379
+ return ExitCode.OK
380
+ else:
381
+ desired = latest
382
+ if desired is None:
383
+ raise ProjectEnvironmentError(f"No release published on the {channel} channel.")
384
+ action: str = "pin" if pin is not None else "update"
385
+ if desired.version == context.current:
386
+ context.state.channel = channel
387
+ context.state.pinned = new_pin
388
+ _save(context)
389
+ status: str = f"pinned to {new_pin}" if new_pin else "up to date"
390
+ _emit(context, as_json, _payload(context, action, channel, latest, result="up_to_date", to=desired.version.text), f"{_describe(context)} is {status}.")
391
+ return ExitCode.OK
392
+ if not _confirm(context, f"Update {_describe(context)} to {desired.version.text}?", assume_yes):
393
+ services.stderr.write("jccs: update cancelled\n")
394
+ return ExitCode.OK
395
+ if context.target.problem is not None:
396
+ raise ProjectEnvironmentError(f"Cannot update: {context.target.problem}.", f"Install it yourself: {manual_command(context.target, desired.version.text)}")
397
+ previous = install(
398
+ context.target, desired, context.current.text,
399
+ fetch=context.fetch, runner=context.runner, environment=context.environment, state_directory=context.state_directory,
400
+ )
401
+ context.state.previous = previous
402
+ context.state.channel = channel
403
+ context.state.pinned = new_pin
404
+ _save(context)
405
+ pinned_note: str = " and pinned it" if new_pin else ""
406
+ _emit(context, as_json, _payload(context, action, channel, latest, result="updated", to=desired.version.text),
407
+ f"Updated {PROGRAM_NAME} from {context.current.text} to {desired.version.text}{pinned_note}.")
408
+ return ExitCode.OK
File without changes
@@ -0,0 +1,188 @@
1
+ import json
2
+ import platform
3
+ import subprocess
4
+ from dataclasses import dataclass
5
+ from pathlib import Path
6
+ from typing import Any
7
+
8
+ from sources.constants import PROGRAM_VERSION
9
+ from sources.utils.git import git_run
10
+
11
+
12
+ # Root of the JCCS installation (the directory that holds `sources/`).
13
+ INSTALL_ROOT: Path = Path(__file__).resolve().parents[2]
14
+
15
+ # File written by the release pipeline for installs without git (PyPI, GitHub release).
16
+ BUILD_INFO_FILE: Path = INSTALL_ROOT / "sources" / "build_info.json"
17
+
18
+ # Release sources a build_info.json may declare.
19
+ RELEASE_SOURCES: frozenset[str] = frozenset({"pypi", "github-release"})
20
+
21
+ # Value used for what cannot be determined.
22
+ UNKNOWN: str = "unknown"
23
+
24
+ # Longest time given to git, in seconds.
25
+ GIT_TIMEOUT: float = 5.0
26
+
27
+
28
+ @dataclass(frozen=True, slots=True)
29
+ class BuildInfo:
30
+ """
31
+ Where the running JCCS comes from (`info --build`).
32
+ (dataclass)
33
+
34
+ Attributes
35
+ ----------
36
+ source : str
37
+ "git", "pypi", "github-release" or "unknown".
38
+ version : str
39
+ Version of the release (the program version for a git checkout).
40
+ date : str
41
+ Commit date (git) or release date (ISO 8601), or "unknown".
42
+ commit : str
43
+ Commit hash, or "unknown".
44
+ dirty : bool | None
45
+ Whether the git checkout has uncommitted changes (None outside git).
46
+ implementation : str
47
+ Python implementation (CPython...).
48
+ python : str
49
+ Python version.
50
+ platform : str
51
+ Operating system and architecture.
52
+ """
53
+
54
+ source: str
55
+ version: str
56
+ date: str
57
+ commit: str
58
+ dirty: bool | None
59
+ implementation: str
60
+ python: str
61
+ platform: str
62
+
63
+ def as_dict(self) -> dict[str, Any]:
64
+ """
65
+ JSON form.
66
+
67
+ Returns
68
+ ----------
69
+ dict[str, Any]
70
+ The fields, in a fixed order.
71
+ """
72
+ return {
73
+ "source": self.source,
74
+ "version": self.version,
75
+ "date": self.date,
76
+ "commit": self.commit,
77
+ "dirty": self.dirty,
78
+ "runtime": {"implementation": self.implementation, "python": self.python, "platform": self.platform},
79
+ }
80
+
81
+
82
+ def _git(root: Path, *arguments: str) -> str | None:
83
+ """
84
+ Run a read-only git command in the JCCS repository.
85
+
86
+ Parameters
87
+ ----------
88
+ root : Path
89
+ Repository root.
90
+ *arguments : str
91
+ git arguments.
92
+
93
+ Returns
94
+ ----------
95
+ str | None
96
+ Standard output, stripped, or None on failure.
97
+ """
98
+ try:
99
+ completed: subprocess.CompletedProcess[bytes] = git_run(root, *arguments, timeout=GIT_TIMEOUT)
100
+ except (OSError, subprocess.SubprocessError):
101
+ return None
102
+ return completed.stdout.decode("utf-8", "replace").strip() if completed.returncode == 0 else None
103
+
104
+
105
+ def _from_file(path: Path) -> dict[str, str] | None:
106
+ """
107
+ Release information written by the release pipeline.
108
+
109
+ Parameters
110
+ ----------
111
+ path : Path
112
+ The build_info.json file.
113
+
114
+ Returns
115
+ ----------
116
+ dict[str, str] | None
117
+ source, version, date and commit, or None when the file is missing or invalid.
118
+ """
119
+ try:
120
+ data: Any = json.loads(path.read_text(encoding="utf-8"))
121
+ except (OSError, ValueError):
122
+ return None
123
+ if not isinstance(data, dict) or data.get("source") not in RELEASE_SOURCES:
124
+ return None
125
+ return {key: str(data.get(key) or UNKNOWN) for key in ("source", "version", "date", "commit")}
126
+
127
+
128
+ def collect_build_info(root: Path = INSTALL_ROOT, build_file: Path = BUILD_INFO_FILE) -> BuildInfo:
129
+ """
130
+ Build information: from git when JCCS runs from its repository, else from the build_info.json of a
131
+ release (PyPI, GitHub release), else unknown. Never uses the network.
132
+
133
+ Parameters
134
+ ----------
135
+ root : Path
136
+ JCCS installation root.
137
+ build_file : Path
138
+ build_info.json location.
139
+
140
+ Returns
141
+ ----------
142
+ BuildInfo
143
+ The information.
144
+ """
145
+ runtime: tuple[str, str, str] = (platform.python_implementation(), platform.python_version(), f"{platform.system()} {platform.machine()}".strip())
146
+ if (root / ".git").exists():
147
+ commit: str | None = _git(root, "rev-parse", "HEAD")
148
+ if commit:
149
+ date: str = _git(root, "log", "-1", "--format=%cI") or UNKNOWN
150
+ status: str | None = _git(root, "status", "--porcelain", "--untracked-files=no")
151
+ return BuildInfo("git", PROGRAM_VERSION, date, commit, None if status is None else bool(status), *runtime)
152
+ release: dict[str, str] | None = _from_file(build_file)
153
+ if release is not None:
154
+ return BuildInfo(release["source"], release["version"], release["date"], release["commit"], None, *runtime)
155
+ return BuildInfo(UNKNOWN, PROGRAM_VERSION, UNKNOWN, UNKNOWN, None, *runtime)
156
+
157
+
158
+ def write_build_info(path: Path, *, source: str, version: str, date: str, commit: str) -> None:
159
+ """
160
+ Write the build_info.json of a release (called by the release pipeline, plan 12).
161
+
162
+ Parameters
163
+ ----------
164
+ path : Path
165
+ Destination.
166
+ source : str
167
+ "pypi" or "github-release".
168
+ version : str
169
+ Released version.
170
+ date : str
171
+ Release date (ISO 8601).
172
+ commit : str
173
+ Released commit.
174
+
175
+ Returns
176
+ ----------
177
+ None
178
+ Nothing.
179
+
180
+ Raises
181
+ ----------
182
+ ValueError
183
+ Unknown source.
184
+ """
185
+ if source not in RELEASE_SOURCES:
186
+ raise ValueError(f"source must be one of {', '.join(sorted(RELEASE_SOURCES))}")
187
+ payload: dict[str, str] = {"source": source, "version": version, "date": date, "commit": commit}
188
+ path.write_text(json.dumps(payload, indent=2) + "\n", encoding="utf-8")
sources/utils/git.py ADDED
@@ -0,0 +1,73 @@
1
+ import os
2
+ import subprocess
3
+ from collections.abc import Mapping
4
+ from pathlib import Path
5
+
6
+
7
+ # Default longest time given to one git call, in seconds.
8
+ DEFAULT_GIT_TIMEOUT: float = 30.0
9
+
10
+ # Variables forced for every git call: stable messages, no optional locks, never prompt.
11
+ GIT_ENVIRONMENT: dict[str, str] = {"LC_ALL": "C", "GIT_OPTIONAL_LOCKS": "0", "GIT_TERMINAL_PROMPT": "0"}
12
+
13
+
14
+ def git_environment(base: Mapping[str, str] | None = None) -> dict[str, str]:
15
+ """
16
+ Environment of a git call: the given (or process) environment without any GIT_* variable (GIT_DIR,
17
+ GIT_WORK_TREE... could redirect git to another repository), plus GIT_ENVIRONMENT (plan 10, section 3).
18
+
19
+ Parameters
20
+ ----------
21
+ base : Mapping[str, str] | None
22
+ Environment to start from (default: os.environ).
23
+
24
+ Returns
25
+ ----------
26
+ dict[str, str]
27
+ The sanitised environment.
28
+ """
29
+ source: Mapping[str, str] = base if base is not None else os.environ
30
+ clean: dict[str, str] = {key: value for key, value in source.items() if not key.startswith("GIT_")}
31
+ clean.update(GIT_ENVIRONMENT)
32
+ return clean
33
+
34
+
35
+ def git_run(
36
+ directory: Path,
37
+ *arguments: str,
38
+ environment: Mapping[str, str] | None = None,
39
+ timeout: float = DEFAULT_GIT_TIMEOUT,
40
+ ) -> subprocess.CompletedProcess[bytes]:
41
+ """
42
+ Run git in a directory: argument list (never a shell), output captured, timeout, sanitised environment.
43
+ Every git call of JCCS goes through this function.
44
+
45
+ Parameters
46
+ ----------
47
+ directory : Path
48
+ Directory git runs in (`git -C`).
49
+ *arguments : str
50
+ git arguments.
51
+ environment : Mapping[str, str] | None
52
+ Environment to start from (default: os.environ).
53
+ timeout : float
54
+ Longest time given to git, in seconds.
55
+
56
+ Returns
57
+ ----------
58
+ subprocess.CompletedProcess[bytes]
59
+ The completed process (any exit code).
60
+
61
+ Raises
62
+ ----------
63
+ FileNotFoundError
64
+ git is not installed.
65
+ subprocess.TimeoutExpired
66
+ git did not finish in time.
67
+ OSError
68
+ git could not be started.
69
+ """
70
+ return subprocess.run(
71
+ ["git", "-C", str(directory), *arguments],
72
+ capture_output=True, timeout=timeout, check=False, env=git_environment(environment),
73
+ )