incur-cli 0.10.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.
incur/_update.py ADDED
@@ -0,0 +1,373 @@
1
+ """Update checks and `--update`: cached latest versions, detached refreshes, and installers."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import asyncio
6
+ import contextlib
7
+ import inspect
8
+ import os
9
+ import re
10
+ import subprocess
11
+ import sys
12
+ import time
13
+ import urllib.parse
14
+ from collections.abc import Awaitable, Callable, Mapping
15
+ from dataclasses import dataclass
16
+
17
+ from . import _js, _pm
18
+ from ._http import Request, fetch, join_url, parse_json
19
+ from ._js import Json
20
+
21
+ #: The hidden flag of detached update checks.
22
+ CHECK_FLAG = "--incur-update-check"
23
+
24
+ _SEMVER = re.compile(
25
+ r"^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)(?:-([0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*))?"
26
+ r"(?:\+[0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*)?$"
27
+ )
28
+ _PACKAGE = re.compile(r"^(?:@[A-Za-z0-9][A-Za-z0-9._~-]*/)?[A-Za-z0-9][A-Za-z0-9._~-]*$")
29
+
30
+
31
+ @dataclass
32
+ class UpdateCheck:
33
+ """What a custom update checker receives."""
34
+
35
+ current: str
36
+ """The current CLI version."""
37
+ name: str
38
+ """The CLI name."""
39
+ package: str | None = None
40
+ """The registry package name, when configured or inferred."""
41
+
42
+
43
+ @dataclass
44
+ class UpdateInstall:
45
+ """What a custom update installer receives."""
46
+
47
+ name: str
48
+ """The CLI name."""
49
+ current: str | None = None
50
+ """The current CLI version, when known."""
51
+ latest: str | None = None
52
+ """The latest cached version, when known."""
53
+ package: str | None = None
54
+ """The registry package name, when configured or inferred."""
55
+
56
+
57
+ @dataclass
58
+ class Update:
59
+ """Settings of update checks and `--update`.
60
+
61
+ By default the CLI updates as the npm package that contains its entry point. Standalone
62
+ distributions provide `check` and `install`.
63
+
64
+ >>> def latest(c: UpdateCheck) -> str | None:
65
+ ... return "2.0.0"
66
+ >>> Update(check=latest, interval=3600).interval
67
+ 3600
68
+ """
69
+
70
+ check: Callable[[UpdateCheck], str | Awaitable[str | None] | None] | None = None
71
+ """Returns the latest version, or `None`. It may be an `async def` function."""
72
+ install: Callable[[UpdateInstall], object] | None = None
73
+ """Installs the latest version. It may be an `async def` function."""
74
+ deferred: bool = False
75
+ """Whether installation finishes after the updating process exits."""
76
+ interval: float = 24 * 60 * 60
77
+ """Minimum seconds between update checks. Defaults to one day."""
78
+ package: str | None = None
79
+ """The registry package name. Defaults to the package containing the entry point."""
80
+
81
+
82
+ @dataclass
83
+ class Options:
84
+ """The update settings of one run."""
85
+
86
+ update: Update
87
+ version: str | None
88
+
89
+
90
+ @dataclass
91
+ class Available:
92
+ """An available update."""
93
+
94
+ current: str
95
+ latest: str
96
+ name: str
97
+
98
+
99
+ @dataclass
100
+ class _Provider:
101
+ key: str
102
+ name: str
103
+ check: Callable[[UpdateCheck], object] | None
104
+ install: Callable[[], Awaitable[None]] | None
105
+ command: str | None
106
+ current: str | None
107
+ package: str | None
108
+ deferred: bool
109
+
110
+
111
+ def _now() -> int:
112
+ return int(time.time() * 1000)
113
+
114
+
115
+ def _package_of(name: str) -> tuple[str, str] | None:
116
+ """Finds the npm package, name and version, that contains the entry point."""
117
+ entry = sys.argv[0] if sys.argv else ""
118
+ if not entry or not os.path.exists(entry):
119
+ return None
120
+ directory = os.path.dirname(os.path.realpath(entry))
121
+ while True:
122
+ metadata = _read_json(os.path.join(directory, "package.json"))
123
+ if isinstance(metadata, dict):
124
+ pkg, version = metadata.get("name"), metadata.get("version")
125
+ if isinstance(pkg, str) and isinstance(version, str) and _provides(metadata, name):
126
+ return pkg, version
127
+ parent = os.path.dirname(directory)
128
+ if parent == directory:
129
+ return None
130
+ directory = parent
131
+
132
+
133
+ def _provides(metadata: dict[str, Json], name: str) -> bool:
134
+ """Whether package metadata declares the CLI name."""
135
+ pkg = metadata.get("name")
136
+ binary = metadata.get("bin")
137
+ if pkg == name or (isinstance(binary, dict) and name in binary):
138
+ return True
139
+ return isinstance(binary, str) and isinstance(pkg, str) and pkg.split("/")[-1] == name
140
+
141
+
142
+ def _read_json(path: str) -> Json | None:
143
+ try:
144
+ with open(path, encoding="utf-8") as file:
145
+ return parse_json(file.read())
146
+ except (OSError, ValueError):
147
+ return None
148
+
149
+
150
+ def _provider(name: str, options: Options, env: Mapping[str, str]) -> _Provider | None:
151
+ """Resolves package defaults and custom overrides."""
152
+ update = options.update
153
+ executing = _package_of(name)
154
+ package = update.package or (executing[0] if executing else None)
155
+ if package and not _PACKAGE.match(package):
156
+ return None
157
+ current = options.version or (executing[1] if executing else None)
158
+ invocation = _pm.global_install(package, env) if package else None
159
+ checker: Callable[[UpdateCheck], object] | None = update.check
160
+ if checker is None and package:
161
+ registry = package
162
+
163
+ def latest(_: UpdateCheck) -> Awaitable[str | None]:
164
+ return _fetch_latest(registry, env)
165
+
166
+ checker = latest
167
+
168
+ install: Callable[[], Awaitable[None]] | None = None
169
+ if update.install is not None:
170
+ custom = update.install
171
+
172
+ async def run_custom() -> None:
173
+ cached = _read_cache(_cache_path(package or name, env))
174
+ latest = cached.get("latest") if cached else None
175
+ context = UpdateInstall(
176
+ name, current or None, latest if isinstance(latest, str) else None, package
177
+ )
178
+ result = custom(context)
179
+ if inspect.isawaitable(result):
180
+ await result
181
+
182
+ install = run_custom
183
+ elif invocation is not None:
184
+ argv = invocation
185
+
186
+ async def run_package() -> None:
187
+ await _exec(argv, env)
188
+
189
+ install = run_package
190
+
191
+ if checker is None and install is None:
192
+ return None
193
+ command = " ".join(invocation) if invocation and update.install is None else None
194
+ return _Provider(
195
+ package or name,
196
+ package or name,
197
+ checker,
198
+ install,
199
+ command,
200
+ current or None,
201
+ package,
202
+ update.deferred,
203
+ )
204
+
205
+
206
+ async def _fetch_latest(package: str, env: Mapping[str, str]) -> str | None:
207
+ """Fetches the latest version of an npm package from the registry."""
208
+ registry = env.get("npm_config_registry") or "https://registry.npmjs.org"
209
+ base = registry if registry.endswith("/") else f"{registry}/"
210
+ url = join_url(base, urllib.parse.quote(package, safe="-_.!~*'()"))
211
+ accept = "application/vnd.npm.install-v1+json; q=1.0, application/json; q=0.8, */*"
212
+ response = await asyncio.wait_for(fetch(Request(url, headers={"accept": accept})), 10)
213
+ if not response.ok:
214
+ return None
215
+ metadata = parse_json(await response.text())
216
+ tags = metadata.get("dist-tags") if isinstance(metadata, dict) else None
217
+ latest = tags.get("latest") if isinstance(tags, dict) else None
218
+ return latest if isinstance(latest, str) else None
219
+
220
+
221
+ def _version(text: str) -> tuple[list[int], list[int | str]] | None:
222
+ """Parses a semantic version into its core numbers and prerelease identifiers."""
223
+ match = _SEMVER.match(text)
224
+ if not match:
225
+ return None
226
+ prerelease: list[int | str] = []
227
+ for part in match[4].split(".") if match[4] else []:
228
+ if not part.isdigit():
229
+ prerelease.append(part)
230
+ elif len(part) > 1 and part.startswith("0"):
231
+ return None
232
+ else:
233
+ prerelease.append(int(part))
234
+ return [int(match[1]), int(match[2]), int(match[3])], prerelease
235
+
236
+
237
+ def is_newer(candidate: str, current: str) -> bool:
238
+ """Whether `candidate` is a newer semantic version than `current`."""
239
+ a, b = _version(candidate), _version(current)
240
+ if a is None or b is None:
241
+ return False
242
+ if a[0] != b[0]:
243
+ return a[0] > b[0]
244
+ pa, pb = a[1], b[1]
245
+ if not pa or not pb:
246
+ return not pa and bool(pb)
247
+ for x, y in zip(pa, pb, strict=False):
248
+ if x == y:
249
+ continue
250
+ if isinstance(x, int) != isinstance(y, int):
251
+ return isinstance(x, str)
252
+ return x > y # type: ignore[operator]
253
+ return len(pa) > len(pb)
254
+
255
+
256
+ def _cache_path(key: str, env: Mapping[str, str]) -> str:
257
+ home = env.get("HOME") or os.path.expanduser("~")
258
+ root = env.get("XDG_CACHE_HOME") or os.path.join(home, ".cache")
259
+ return os.path.join(root, "incur", "updates", f"{urllib.parse.quote(key, safe='')}.json")
260
+
261
+
262
+ def _read_cache(path: str) -> dict[str, Json] | None:
263
+ value = _read_json(path)
264
+ if not isinstance(value, dict):
265
+ return None
266
+ checked = value.get("checkedAt")
267
+ latest = value.get("latest", "")
268
+ if isinstance(checked, bool) or not isinstance(checked, (int, float)):
269
+ return None
270
+ return value if isinstance(latest, str) else None
271
+
272
+
273
+ def _write_cache(path: str, cache: dict[str, Json]) -> None:
274
+ os.makedirs(os.path.dirname(path), exist_ok=True)
275
+ with open(path, "w", encoding="utf-8") as file:
276
+ file.write(_js.stringify(cache) + "\n")
277
+
278
+
279
+ def _disabled(env: Mapping[str, str]) -> bool:
280
+ """Whether the environment suppresses update notifications."""
281
+ if env.get("NO_UPDATE_NOTIFIER") or env.get("npm_config_update_notifier") == "false":
282
+ return True
283
+ ci = env.get("CI")
284
+ return bool(ci) and ci != "false"
285
+
286
+
287
+ def check(name: str, options: Options, env: Mapping[str, str]) -> Available | None:
288
+ """Returns a cached available update, and schedules a detached refresh when it is stale."""
289
+ if _disabled(env):
290
+ return None
291
+ provider = _provider(name, options, env)
292
+ if provider is None or provider.check is None or provider.current is None:
293
+ return None
294
+ path = _cache_path(provider.key, env)
295
+ cached = _read_cache(path)
296
+ now = _now()
297
+ interval = max(0.0, options.update.interval * 1000)
298
+ latest = cached.get("latest") if cached else None
299
+ checked = cached["checkedAt"] if cached else 0
300
+ assert isinstance(checked, (int, float))
301
+ if cached is None or now - checked >= interval:
302
+ _schedule_refresh(path, now, latest if isinstance(latest, str) else None)
303
+ if not isinstance(latest, str) or not is_newer(latest, provider.current):
304
+ return None
305
+ return Available(provider.current, latest, provider.name)
306
+
307
+
308
+ def _schedule_refresh(path: str, now: int, latest: str | None) -> None:
309
+ """Marks a check and starts a detached self-invocation that refreshes the cache."""
310
+ entry = sys.argv[0] if sys.argv else ""
311
+ if not entry:
312
+ return
313
+ frozen = getattr(sys, "frozen", False)
314
+ command = [sys.executable, CHECK_FLAG] if frozen else [sys.executable, entry, CHECK_FLAG]
315
+ cache: dict[str, Json] = {"checkedAt": now}
316
+ if latest:
317
+ cache["latest"] = latest
318
+ with contextlib.suppress(OSError):
319
+ _write_cache(path, cache)
320
+ subprocess.Popen(
321
+ command,
322
+ stdin=subprocess.DEVNULL,
323
+ stdout=subprocess.DEVNULL,
324
+ stderr=subprocess.DEVNULL,
325
+ start_new_session=True,
326
+ )
327
+
328
+
329
+ async def refresh(name: str, options: Options, env: Mapping[str, str]) -> None:
330
+ """Refreshes the cached latest version through the provider."""
331
+ provider = _provider(name, options, env)
332
+ if provider is None or provider.check is None or provider.current is None:
333
+ return
334
+ latest = provider.check(UpdateCheck(provider.current, name, provider.package))
335
+ if inspect.isawaitable(latest):
336
+ latest = await latest
337
+ if not isinstance(latest, str) or not latest or _version(latest) is None:
338
+ return
339
+ _write_cache(_cache_path(provider.key, env), {"checkedAt": _now(), "latest": latest})
340
+
341
+
342
+ async def install(name: str, options: Options, env: Mapping[str, str]) -> dict[str, Json]:
343
+ """Installs the latest version through the provider. Returns what `--update` reports."""
344
+ provider = _provider(name, options, env)
345
+ if provider is None or provider.install is None:
346
+ raise RuntimeError(f"No update installer is configured for '{name}'.")
347
+ await provider.install()
348
+ out: dict[str, Json] = {}
349
+ if provider.command:
350
+ out["command"] = provider.command
351
+ if provider.deferred:
352
+ out["deferred"] = True
353
+ out["name"] = provider.name
354
+ return out
355
+
356
+
357
+ async def _exec(command: list[str], env: Mapping[str, str]) -> None:
358
+ """Runs a package-manager command, failing with its useful error output."""
359
+ try:
360
+ process = await asyncio.create_subprocess_exec(
361
+ *command,
362
+ env=dict(env),
363
+ stdin=subprocess.DEVNULL,
364
+ stdout=subprocess.PIPE,
365
+ stderr=subprocess.PIPE,
366
+ )
367
+ except OSError as error:
368
+ raise RuntimeError(f"spawn {command[0]} ENOENT") from error
369
+ stdout, stderr = await process.communicate()
370
+ if process.returncode == 0:
371
+ return
372
+ message = stderr.decode().strip() or stdout.decode().strip()
373
+ raise RuntimeError(message or f"Command failed: {' '.join(command)}")