githubtemplateastraluv 0.0.2__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.
@@ -0,0 +1,247 @@
1
+ #!/usr/bin/env python3
2
+ ## @file management.py
3
+ # @brief Management commands of githubtemplateastraluv, isolated from core
4
+ # dispatch logic.
5
+ # @details Implements exact help-screen rendering, `uv tool` install and
6
+ # uninstall lifecycle with Linux-only execution gating, and the
7
+ # manual-command fallback for non-Linux platforms.
8
+ import subprocess
9
+ import sys
10
+
11
+ ## @brief Canonical program name used across help text and uv commands.
12
+ PROGRAM_NAME = "githubtemplateastraluv"
13
+
14
+ ## @brief Exact `uv tool install` argv executed on Linux by
15
+ # `--upgrade` without `--force` (REQ-003).
16
+ # @details `' '.join(UPGRADE_COMMAND)` equals the literal string mandated
17
+ # by REQ-003 and is printed verbatim as the manual command on
18
+ # non-Linux platforms (REQ-004). Source resolves from PyPI; the
19
+ # standard process applies no forcing option (REQ-037).
20
+ UPGRADE_COMMAND = [
21
+ "uv",
22
+ "tool",
23
+ "install",
24
+ "githubtemplateastraluv",
25
+ ]
26
+
27
+ ## @brief Exact `uv tool install` argv executed on Linux by
28
+ # `--upgrade --force` (REQ-035).
29
+ # @details `' '.join(UPGRADE_FORCE_COMMAND)` equals the literal string
30
+ # mandated by REQ-035 and is printed verbatim as the manual
31
+ # command on non-Linux platforms (REQ-004). The forcing options
32
+ # force the full re-download and complete reinstallation of the
33
+ # package from PyPI (REQ-037).
34
+ UPGRADE_FORCE_COMMAND = [
35
+ "uv",
36
+ "tool",
37
+ "install",
38
+ "githubtemplateastraluv",
39
+ "--force",
40
+ "--reinstall",
41
+ "--refresh",
42
+ ]
43
+
44
+ ## @brief Exact `uv tool install` argv executed on Linux by
45
+ # `--upgrade --develop` without `--force` (REQ-032).
46
+ # @details `' '.join(UPGRADE_DEVELOP_COMMAND)` equals the literal string
47
+ # mandated by REQ-032 and is printed verbatim as the manual
48
+ # command on non-Linux platforms (REQ-033). Source resolves from
49
+ # the GitHub repository (latest tagged release, any branch); the
50
+ # standard process applies no forcing option (REQ-037).
51
+ UPGRADE_DEVELOP_COMMAND = [
52
+ "uv",
53
+ "tool",
54
+ "install",
55
+ "githubtemplateastraluv",
56
+ "--from",
57
+ "git+https://github.com/Ogekuri/GitHub-Template-AstralUV.git",
58
+ ]
59
+
60
+ ## @brief Exact `uv tool install` argv executed on Linux by
61
+ # `--upgrade --develop --force` (REQ-036).
62
+ # @details `' '.join(UPGRADE_DEVELOP_FORCE_COMMAND)` equals the literal
63
+ # string mandated by REQ-036 and is printed verbatim as the
64
+ # manual command on non-Linux platforms (REQ-033). The forcing
65
+ # options force the full re-download and complete reinstallation
66
+ # from the GitHub repository source (REQ-037).
67
+ UPGRADE_DEVELOP_FORCE_COMMAND = [
68
+ "uv",
69
+ "tool",
70
+ "install",
71
+ "githubtemplateastraluv",
72
+ "--force",
73
+ "--reinstall",
74
+ "--refresh",
75
+ "--from",
76
+ "git+https://github.com/Ogekuri/GitHub-Template-AstralUV.git",
77
+ ]
78
+
79
+ ## @brief Exact `uv tool uninstall` argv executed on Linux by `--uninstall`.
80
+ # @details `' '.join(UNINSTALL_COMMAND)` equals the literal string mandated
81
+ # by REQ-005 and is printed verbatim as the manual command on
82
+ # non-Linux platforms (REQ-006).
83
+ UNINSTALL_COMMAND = ["uv", "tool", "uninstall", "githubtemplateastraluv"]
84
+
85
+ ## @brief Flag column width keeping management help lines aligned.
86
+ _FLAG_COLUMN_WIDTH = len("--uninstall")
87
+
88
+
89
+ def is_linux() -> bool:
90
+ """@brief Report whether the current operating system is Linux.
91
+
92
+ @details `sys.platform` prefix check (covers `linux` and historical
93
+ `linux2` values); all other platforms take the manual-command
94
+ branch (A-09).
95
+ @return {bool} True on Linux, False otherwise.
96
+ @satisfies A-09 CTN-009
97
+ """
98
+ return sys.platform.startswith("linux")
99
+
100
+
101
+ def _management_entry(flag: str, description: str) -> str:
102
+ """@brief Render one aligned management-command help line.
103
+
104
+ @param flag {str} Command flag (e.g. `--upgrade`).
105
+ @param description {str} Description text placed after the dash.
106
+ @return {str} Line matching the REQ-001 template alignment.
107
+ @satisfies REQ-001
108
+ """
109
+ return f" {flag:<{_FLAG_COLUMN_WIDTH}} - {description}"
110
+
111
+
112
+ def _upgrade_command(develop: bool, force: bool) -> list[str]:
113
+ """@brief Select the exact `uv tool install` argv for the variant.
114
+
115
+ @details Mapping mandated by the SRS: `(False, False)` ->
116
+ UPGRADE_COMMAND (REQ-003), `(False, True)` ->
117
+ UPGRADE_FORCE_COMMAND (REQ-035), `(True, False)` ->
118
+ UPGRADE_DEVELOP_COMMAND (REQ-032), `(True, True)` ->
119
+ UPGRADE_DEVELOP_FORCE_COMMAND (REQ-036). Forcing options are
120
+ applied only when `force` is True (REQ-037).
121
+ @param develop {bool} True selects the GitHub development source.
122
+ @param force {bool} True selects the forced reinstallation variant.
123
+ @return {list[str]} Exact argv of the requested upgrade variant.
124
+ @satisfies REQ-003 REQ-032 REQ-035 REQ-036 REQ-037
125
+ """
126
+ if develop:
127
+ return (
128
+ UPGRADE_DEVELOP_FORCE_COMMAND if force
129
+ else UPGRADE_DEVELOP_COMMAND
130
+ )
131
+ return UPGRADE_FORCE_COMMAND if force else UPGRADE_COMMAND
132
+
133
+
134
+ def build_help_text(version: str) -> str:
135
+ """@brief Render the full help screen text (REQ-001 template).
136
+
137
+ @details The literal `(x.y.z)` slot of the template receives the
138
+ installed version (A-01); the `Options:` section documents
139
+ the `--develop` and `--force` modifiers of `--upgrade`; the
140
+ `Commands:` section ends with the literal `...` line (A-02).
141
+ @param version {str} Installed version in `x.y.z` format.
142
+ @return {str} Help text without trailing newline; the caller prints it.
143
+ @satisfies REQ-001 A-01 A-02
144
+ """
145
+ entries = [
146
+ _management_entry(
147
+ "--upgrade",
148
+ f"Reinstall {PROGRAM_NAME} on Linux; "
149
+ "print manual command elsewhere.",
150
+ ),
151
+ _management_entry(
152
+ "--uninstall",
153
+ f"Uninstall {PROGRAM_NAME} on Linux; "
154
+ "print manual command elsewhere.",
155
+ ),
156
+ _management_entry("--ver", f"Print the {PROGRAM_NAME} version."),
157
+ _management_entry("--version", f"Print the {PROGRAM_NAME} version."),
158
+ _management_entry(
159
+ "--help",
160
+ "Print the full help screen or the help text of a specific "
161
+ "command.",
162
+ ),
163
+ ]
164
+ option_entries = [
165
+ _management_entry(
166
+ "--develop",
167
+ "With --upgrade: install from the GitHub development source.",
168
+ ),
169
+ _management_entry(
170
+ "--force",
171
+ "With --upgrade: force full re-download and reinstallation.",
172
+ ),
173
+ ]
174
+ header = f"Usage: {PROGRAM_NAME} [command] [options] ({version})"
175
+ lines = (
176
+ [header, "", "Management Commands:"]
177
+ + entries
178
+ + ["", "Options:"]
179
+ + option_entries
180
+ + ["", "Commands:", " ..."]
181
+ )
182
+ return "\n".join(lines)
183
+
184
+
185
+ def print_help(version: str) -> int:
186
+ """@brief Print the full help screen to stdout.
187
+
188
+ @param version {str} Installed version in `x.y.z` format.
189
+ @return {int} Always 0.
190
+ @satisfies REQ-001 PRJ-005
191
+ """
192
+ print(build_help_text(version))
193
+ return 0
194
+
195
+
196
+ def cmd_upgrade(develop: bool = False, force: bool = False) -> int:
197
+ """@brief Reinstall the tool via `uv tool install` on Linux.
198
+
199
+ @details On Linux the exact argv selected by `develop` and `force`
200
+ executes through subprocess and its exit code propagates:
201
+ UPGRADE_COMMAND for the standard PyPI process (REQ-003),
202
+ UPGRADE_FORCE_COMMAND for the forced PyPI reinstallation
203
+ (REQ-035), UPGRADE_DEVELOP_COMMAND for the standard GitHub
204
+ development source (REQ-032), and
205
+ UPGRADE_DEVELOP_FORCE_COMMAND for the forced development
206
+ reinstallation (REQ-036); forcing options apply only when
207
+ `force` is True (REQ-037). On any other OS no process spawns;
208
+ a warning plus the matching manual command print instead
209
+ (REQ-004, REQ-033).
210
+ @param develop {bool} True selects the GitHub development source
211
+ (`--upgrade --develop`); False selects the PyPI source
212
+ (default).
213
+ @param force {bool} True selects the forced full re-download and
214
+ reinstallation variant (`--upgrade --force`, REQ-037);
215
+ False executes the standard process without any forcing
216
+ option.
217
+ @return {int} 0 on manual fallback or successful subprocess;
218
+ otherwise the `uv` process exit code.
219
+ @satisfies REQ-003 REQ-004 REQ-032 REQ-033 REQ-035 REQ-036 REQ-037
220
+ CTN-009
221
+ """
222
+ command = _upgrade_command(develop, force)
223
+ if not is_linux():
224
+ print("WARNING: --upgrade executes automatically on Linux only.")
225
+ print(f"Run manually: {' '.join(command)}")
226
+ return 0
227
+ completed = subprocess.run(command, check=False)
228
+ return int(completed.returncode)
229
+
230
+
231
+ def cmd_uninstall() -> int:
232
+ """@brief Uninstall the tool via `uv tool uninstall` on Linux.
233
+
234
+ @details On Linux the exact UNINSTALL_COMMAND argv executes through
235
+ subprocess and its exit code propagates. On any other OS no
236
+ process spawns; a warning plus the manual command print
237
+ instead (REQ-006).
238
+ @return {int} 0 on manual fallback or successful subprocess;
239
+ otherwise the `uv` process exit code.
240
+ @satisfies REQ-005 REQ-006 CTN-009
241
+ """
242
+ if not is_linux():
243
+ print("WARNING: --uninstall executes automatically on Linux only.")
244
+ print(f"Run manually: {' '.join(UNINSTALL_COMMAND)}")
245
+ return 0
246
+ completed = subprocess.run(UNINSTALL_COMMAND, check=False)
247
+ return int(completed.returncode)
@@ -0,0 +1,389 @@
1
+ #!/usr/bin/env python3
2
+ ## @file version_check.py
3
+ # @brief Online new-version check and dual-source version report executed
4
+ # before CLI argument parsing.
5
+ # @details Queries the PyPI JSON API with a hardcoded 2 s timeout for the
6
+ # gated availability check, throttled through an idle-time JSON
7
+ # cache under `$HOME`, and renders the aligned three-row report
8
+ # (`--ver`) fetching both PyPI and the GitHub releases API.
9
+ # Notifications use the colors configured in the configuration
10
+ # subsystem (REQ-026), falling back to bright green / bright red
11
+ # schema defaults when configuration cannot be loaded. Success
12
+ # refreshes the cache with a 3600 s idle-delay; any failure backs
13
+ # off 86400 s.
14
+ import json
15
+ import os
16
+ import time
17
+ import urllib.error
18
+ import urllib.request
19
+ from pathlib import Path
20
+ from typing import Any
21
+
22
+ from githubtemplateastraluv import config
23
+
24
+ ## @brief PyPI JSON API endpoint returning latest published version
25
+ # metadata (REQ-009, REQ-028).
26
+ _PYPI_JSON_ENDPOINT = "https://pypi.org/pypi/githubtemplateastraluv/json"
27
+ ## @brief GitHub API endpoint returning latest release metadata; source of
28
+ # the report `Latest @ GitHub` row (REQ-029) and of the
29
+ # `--upgrade --develop` download (REQ-032).
30
+ _GITHUB_RELEASES_ENDPOINT = (
31
+ "https://api.github.com/repos/Ogekuri/"
32
+ "GitHub-Template-AstralUV/releases/latest"
33
+ )
34
+ ## @brief HTTP(S) request timeout in seconds, hardcoded (CTN-006).
35
+ _HTTP_TIMEOUT_SECONDS = 2
36
+ ## @brief Idle-delay in seconds after every successful check (CTN-007).
37
+ _IDLE_DELAY_SUCCESS_SECONDS = 3600
38
+ ## @brief Idle-delay in seconds after any failed check (CTN-007).
39
+ _IDLE_DELAY_FAILURE_SECONDS = 86400
40
+ ## @brief Cache file location relative to `$HOME` (DES-007).
41
+ _CACHE_RELATIVE_PATH = (
42
+ ".cache",
43
+ "githubtemplateastraluv",
44
+ "check_version_idle-time.json",
45
+ )
46
+ ## @brief ANSI SGR reset suffix closing colored notifications.
47
+ # @details Notification prefix colors are configured through the
48
+ # configuration subsystem (config.notification_colors, REQ-026);
49
+ # only the reset suffix stays local.
50
+ _ANSI_RESET = "\033[0m"
51
+ ## @brief Report row label for the installed version (REQ-027).
52
+ _REPORT_LABEL_INSTALLED = "Current Installed"
53
+ ## @brief Report row label for the PyPI latest version (REQ-027).
54
+ _REPORT_LABEL_PYPI = "Latest @ PyPI"
55
+ ## @brief Report row label for the GitHub latest release version (REQ-027).
56
+ _REPORT_LABEL_GITHUB = "Latest @ GitHub"
57
+ ## @brief Label pad width keeping report version columns aligned (REQ-027).
58
+ # @details Equals the length of the longest label `_REPORT_LABEL_INSTALLED`.
59
+ _REPORT_LABEL_WIDTH = len(_REPORT_LABEL_INSTALLED)
60
+ ## @brief Placeholder replacing the version of a failed report source
61
+ # before the reason suffix is appended (REQ-030).
62
+ _REPORT_UNKNOWN = "unknown"
63
+
64
+
65
+ def _cache_path() -> Path:
66
+ """@brief Resolve the absolute cache file path from `$HOME`.
67
+
68
+ @details Prefers the `HOME` environment variable (CTN-008); falls back
69
+ to `Path.home()` when unset. Does not create directories.
70
+ @return {Path} Absolute cache file path.
71
+ @satisfies DES-007 CTN-008
72
+ """
73
+ if "HOME" in os.environ:
74
+ base = Path(os.environ["HOME"])
75
+ else:
76
+ base = Path.home()
77
+ return base.joinpath(*_CACHE_RELATIVE_PATH)
78
+
79
+
80
+ def _read_cache(path: Path) -> dict[str, Any] | None:
81
+ """@brief Load the idle-time cache JSON document.
82
+
83
+ @details Returns None when the file is absent, unreadable, unparsable,
84
+ or not a JSON object; callers treat None as cache-miss.
85
+ @param path {Path} Cache file path.
86
+ @return {dict[str, Any] | None} Parsed cache payload or None.
87
+ @satisfies REQ-008
88
+ """
89
+ try:
90
+ with path.open("r", encoding="utf-8") as handle:
91
+ payload = json.load(handle)
92
+ except (OSError, ValueError):
93
+ return None
94
+ return payload if isinstance(payload, dict) else None
95
+
96
+
97
+ def _human_timestamp(epoch_seconds: float) -> str:
98
+ """@brief Format an epoch value as UTC ISO-8601.
99
+
100
+ @param epoch_seconds {float} Epoch seconds to render.
101
+ @return {str} Timestamp shaped `YYYY-MM-DDTHH:MM:SSZ`.
102
+ """
103
+ return time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime(epoch_seconds))
104
+
105
+
106
+ def _write_cache(
107
+ path: Path,
108
+ check_epoch: float,
109
+ idle_delay_seconds: int,
110
+ ) -> None:
111
+ """@brief Persist the four-field idle-time cache document.
112
+
113
+ @details Creates missing parent directories. Field names follow A-03.
114
+ @param path {Path} Cache file path.
115
+ @param check_epoch {float} Epoch seconds of the check attempt.
116
+ @param idle_delay_seconds {int} Idle-delay applied after this check.
117
+ @return {None}
118
+ @post Cache file holds exactly four fields: last_check_epoch,
119
+ last_check_human, idle_time_epoch, idle_time_human.
120
+ @satisfies REQ-010 REQ-011 DES-007
121
+ """
122
+ idle_epoch = int(check_epoch) + idle_delay_seconds
123
+ payload = {
124
+ "last_check_epoch": int(check_epoch),
125
+ "last_check_human": _human_timestamp(check_epoch),
126
+ "idle_time_epoch": idle_epoch,
127
+ "idle_time_human": _human_timestamp(idle_epoch),
128
+ }
129
+ path.parent.mkdir(parents=True, exist_ok=True)
130
+ with path.open("w", encoding="utf-8") as handle:
131
+ json.dump(payload, handle)
132
+
133
+
134
+ def _gate_allows_request(
135
+ cache: dict[str, Any] | None,
136
+ now_epoch: float,
137
+ ) -> bool:
138
+ """@brief Evaluate the idle-time request gate.
139
+
140
+ @details Gate opens on cache-miss (None), non-numeric idle_time_epoch,
141
+ or `now_epoch >= idle_time_epoch`; otherwise it stays closed.
142
+ @param cache {dict[str, Any] | None} Parsed cache payload or None.
143
+ @param now_epoch {float} Current epoch seconds.
144
+ @return {bool} True when an HTTPS request is permitted.
145
+ @satisfies REQ-008
146
+ """
147
+ if cache is None:
148
+ return True
149
+ idle_epoch = cache.get("idle_time_epoch")
150
+ if not isinstance(idle_epoch, (int, float)):
151
+ return True
152
+ return now_epoch >= idle_epoch
153
+
154
+
155
+ def _parse_version(version: str) -> tuple[int, ...]:
156
+ """@brief Parse a dotted version string into a comparable tuple.
157
+
158
+ @details Strips one leading `v`/`V` prefix before splitting on dots.
159
+ @param version {str} Version or release tag (e.g. `v1.2.3`).
160
+ @return {tuple[int, ...]} Comparable component tuple.
161
+ @throws {ValueError} If any component is not an integer.
162
+ """
163
+ text = version[1:] if version[:1] in ("v", "V") else version
164
+ return tuple(int(part) for part in text.split("."))
165
+
166
+
167
+ def _fetch_latest_pypi_version() -> str:
168
+ """@brief GET the PyPI JSON payload and extract the latest version.
169
+
170
+ @details Sends a plain GET to the PyPI JSON API; no Accept header is
171
+ required. Payload shape: `{"info": {"version": "x.y.z"}}`.
172
+ @return {str} Latest published version in `x.y.z` format.
173
+ @throws {urllib.error.URLError} On HTTP and network failures; includes
174
+ HTTPError carrying the status code (e.g. 429, 503).
175
+ @throws {TimeoutError} On the 2-second timeout expiry.
176
+ @throws {ValueError} On unparsable payload or missing version.
177
+ @satisfies REQ-009 REQ-028 CTN-006
178
+ """
179
+ request = urllib.request.Request(_PYPI_JSON_ENDPOINT)
180
+ with urllib.request.urlopen(
181
+ request, timeout=_HTTP_TIMEOUT_SECONDS
182
+ ) as response:
183
+ payload = json.loads(response.read().decode("utf-8"))
184
+ info = payload.get("info") if isinstance(payload, dict) else None
185
+ version = info.get("version") if isinstance(info, dict) else None
186
+ if not isinstance(version, str) or not version:
187
+ raise ValueError("PyPI payload misses info.version")
188
+ return version
189
+
190
+
191
+ def _fetch_latest_github_version() -> str:
192
+ """@brief GET the latest GitHub release payload and extract its version.
193
+
194
+ @details Strips one leading `v`/`V` prefix from `tag_name`; the returned
195
+ value is exactly the version downloaded by
196
+ `--upgrade --develop` (REQ-032) regardless of the branch the
197
+ release was tagged on.
198
+ @return {str} Latest release version in `x.y.z` format.
199
+ @throws {urllib.error.URLError} On HTTP and network failures; includes
200
+ HTTPError carrying the status code (e.g. 429, 503).
201
+ @throws {TimeoutError} On the 2-second timeout expiry.
202
+ @throws {ValueError} On unparsable payload or missing tag_name.
203
+ @satisfies REQ-029 CTN-006
204
+ """
205
+ request = urllib.request.Request(
206
+ _GITHUB_RELEASES_ENDPOINT,
207
+ headers={"Accept": "application/vnd.github+json"},
208
+ )
209
+ with urllib.request.urlopen(
210
+ request, timeout=_HTTP_TIMEOUT_SECONDS
211
+ ) as response:
212
+ payload = json.loads(response.read().decode("utf-8"))
213
+ tag_name = payload.get("tag_name") if isinstance(payload, dict) else None
214
+ if not isinstance(tag_name, str) or not tag_name:
215
+ raise ValueError("release payload misses tag_name")
216
+ return tag_name[1:] if tag_name[:1] in ("v", "V") else tag_name
217
+
218
+
219
+ def _format_report_row(label: str, value: str) -> str:
220
+ """@brief Render one report row with the label padded to 17 columns.
221
+
222
+ @param label {str} Row label (e.g. `Latest @ PyPI`).
223
+ @param value {str} Version string or `unknown (<reason>)` placeholder.
224
+ @return {str} Row shaped `<label padded to 17> : <value>` (REQ-027).
225
+ @satisfies REQ-027
226
+ """
227
+ return f"{label:<{_REPORT_LABEL_WIDTH}} : {value}"
228
+
229
+
230
+ def _unknown_value(reason: str) -> str:
231
+ """@brief Render the failed-source placeholder with its reason.
232
+
233
+ @details REQ-030 mandates the `unknown (<reason>)` shape, where
234
+ `<reason>` names the actually encountered error (e.g. an
235
+ HTTP 403/404 rate-limit response or a timeout); an empty
236
+ reason degrades to the bare `unknown` placeholder.
237
+ @param reason {str} String rendering of the encountered error.
238
+ @return {str} `unknown (<reason>)`, or `unknown` when reason is empty.
239
+ @satisfies REQ-030
240
+ """
241
+ if not reason:
242
+ return _REPORT_UNKNOWN
243
+ return f"{_REPORT_UNKNOWN} ({reason})"
244
+
245
+
246
+ def _print_colored(color: str, message: str) -> None:
247
+ """@brief Print a message wrapped in an ANSI color prefix and reset.
248
+
249
+ @param color {str} ANSI SGR prefix (bright green or bright red).
250
+ @param message {str} Plain-text message content.
251
+ @return {None}
252
+ @satisfies DES-008
253
+ """
254
+ print(f"{color}{message}{_ANSI_RESET}")
255
+
256
+
257
+ def _report_failure(
258
+ check_epoch: float,
259
+ error: BaseException,
260
+ color: str,
261
+ ) -> None:
262
+ """@brief Emit the failure note and write the 86400 s cache.
263
+
264
+ @details The note renders with the configured error color (REQ-026).
265
+ @param check_epoch {float} Epoch seconds of the failed attempt.
266
+ @param error {BaseException} Encountered error rendered in the note.
267
+ @param color {str} ANSI SGR prefix for the failure note.
268
+ @return {None}
269
+ @satisfies REQ-014 REQ-015 REQ-026 A-05
270
+ """
271
+ _print_colored(color, f"Version check failed: {error}")
272
+ _write_cache(_cache_path(), check_epoch, _IDLE_DELAY_FAILURE_SECONDS)
273
+
274
+
275
+ def run_version_check(installed_version: str, force: bool = False) -> None:
276
+ """@brief Execute the gated (or forced) online version check on PyPI.
277
+
278
+ @details Flow: cache read -> gate evaluation (skipped when `force`) ->
279
+ PyPI JSON fetch -> version compare -> notify -> cache write.
280
+ Notification colors come from the configuration subsystem
281
+ with schema-default fallback (REQ-026). Success always
282
+ refreshes the cache with the 3600 s idle-delay (REQ-013,
283
+ A-04); fetch or parse failures print the configured error
284
+ note and back off 86400 s (REQ-014, REQ-015, A-05). The call
285
+ always returns normally; callers continue parsing (A-06).
286
+ @param installed_version {str} Installed version in `x.y.z` format.
287
+ @param force {bool} True bypasses the idle-time gate (REQ-002,
288
+ REQ-007).
289
+ @return {None}
290
+ @satisfies REQ-007 REQ-008 REQ-009 REQ-010 REQ-011 REQ-012 REQ-013
291
+ REQ-014 REQ-015 REQ-024 REQ-025 REQ-026
292
+ """
293
+ check_epoch = time.time()
294
+ colors = config.notification_colors()
295
+ cache = _read_cache(_cache_path())
296
+ if not force and not _gate_allows_request(cache, check_epoch):
297
+ return
298
+ try:
299
+ latest_version = _fetch_latest_pypi_version()
300
+ available = _parse_version(latest_version)
301
+ installed = _parse_version(installed_version)
302
+ except (
303
+ urllib.error.URLError,
304
+ TimeoutError,
305
+ OSError,
306
+ ValueError,
307
+ ) as error:
308
+ _report_failure(check_epoch, error, colors["error_color"])
309
+ return
310
+ if available > installed:
311
+ _print_colored(
312
+ colors["new_version_color"],
313
+ f"New version available: {latest_version} "
314
+ f"(installed version: {installed_version})",
315
+ )
316
+ _write_cache(_cache_path(), check_epoch, _IDLE_DELAY_SUCCESS_SECONDS)
317
+
318
+
319
+ def run_version_report(installed_version: str) -> None:
320
+ """@brief Execute the forced dual-source version report (`--ver`).
321
+
322
+ @details Flow: fetch PyPI -> fetch GitHub -> emit the three aligned
323
+ rows. Each failed fetch emits one bright red note naming the
324
+ failed source with the configured error color (REQ-030) and
325
+ its row prints `unknown (<reason>)`, carrying the actually
326
+ encountered error, in place of the version (REQ-030). Rows
327
+ print in order: installed, PyPI, GitHub; version columns
328
+ aligned via a 17-character label pad (REQ-027). The GitHub
329
+ row shows the latest release tag stripped of its `v` prefix,
330
+ exactly the version downloaded by `--upgrade --develop`
331
+ (REQ-029). The idle-time gate and cache file are bypassed
332
+ (REQ-002); the cache write follows the PyPI outcome only:
333
+ 3600 s on success, 86400 s on failure (REQ-031). The call
334
+ always returns normally (A-06).
335
+ @param installed_version {str} Installed version in `x.y.z` format.
336
+ @return {None}
337
+ @satisfies REQ-002 REQ-027 REQ-028 REQ-029 REQ-030 REQ-031 REQ-026
338
+ """
339
+ colors = config.notification_colors()
340
+ check_epoch = time.time()
341
+ pypi_version: str | None = None
342
+ github_version: str | None = None
343
+ pypi_reason = ""
344
+ github_reason = ""
345
+ try:
346
+ pypi_version = _fetch_latest_pypi_version()
347
+ except (
348
+ urllib.error.URLError,
349
+ TimeoutError,
350
+ OSError,
351
+ ValueError,
352
+ ) as error:
353
+ pypi_reason = str(error)
354
+ _print_colored(
355
+ colors["error_color"], f"Version check failed @ PyPI: {error}"
356
+ )
357
+ try:
358
+ github_version = _fetch_latest_github_version()
359
+ except (
360
+ urllib.error.URLError,
361
+ TimeoutError,
362
+ OSError,
363
+ ValueError,
364
+ ) as error:
365
+ github_reason = str(error)
366
+ _print_colored(
367
+ colors["error_color"], f"Version check failed @ GitHub: {error}"
368
+ )
369
+ print(_format_report_row(_REPORT_LABEL_INSTALLED, installed_version))
370
+ print(
371
+ _format_report_row(
372
+ _REPORT_LABEL_PYPI,
373
+ pypi_version
374
+ if pypi_version is not None
375
+ else _unknown_value(pypi_reason),
376
+ )
377
+ )
378
+ print(
379
+ _format_report_row(
380
+ _REPORT_LABEL_GITHUB,
381
+ github_version
382
+ if github_version is not None
383
+ else _unknown_value(github_reason),
384
+ )
385
+ )
386
+ if pypi_version is not None:
387
+ _write_cache(_cache_path(), check_epoch, _IDLE_DELAY_SUCCESS_SECONDS)
388
+ else:
389
+ _write_cache(_cache_path(), check_epoch, _IDLE_DELAY_FAILURE_SECONDS)