pyselfupdate 0.5.5__tar.gz → 0.6.0__tar.gz

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.
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.5
2
2
  Name: pyselfupdate
3
- Version: 0.5.5
3
+ Version: 0.6.0
4
4
  Summary: Self-update and update notification for Python CLIs installed with uv tool
5
5
  Project-URL: Repository, https://github.com/datapointchris/pyselfupdate
6
6
  Project-URL: Issues, https://github.com/datapointchris/pyselfupdate/issues
@@ -203,6 +203,8 @@ caller matches a type rather than message text:
203
203
  | `NotInstalledError` | uv's receipt is missing or unreadable, or holds a `--with` requirement an update would drop |
204
204
  | `NoReleaseError` | The source publishes no release, or its newest tag is not a semantic version |
205
205
  | `SourceError` | The source could not be reached, or answered with something unusable |
206
+ | `SelfUpdateSourceFailure` | A `SourceError` from a transport or protocol failure, as opposed to a missing release |
207
+ | `RateLimitedError` | A `SelfUpdateSourceFailure` for a spent rate limit. `authenticated` says which ceiling, and `resets_at` when it lifts, or None |
206
208
  | `LockUnreadableError` | The release's `uv.lock` could not be read, so nothing was installed |
207
209
  | `InstallFailedError` | `uv tool install` ran and failed, or uv is not on `PATH` |
208
210
 
@@ -180,6 +180,8 @@ caller matches a type rather than message text:
180
180
  | `NotInstalledError` | uv's receipt is missing or unreadable, or holds a `--with` requirement an update would drop |
181
181
  | `NoReleaseError` | The source publishes no release, or its newest tag is not a semantic version |
182
182
  | `SourceError` | The source could not be reached, or answered with something unusable |
183
+ | `SelfUpdateSourceFailure` | A `SourceError` from a transport or protocol failure, as opposed to a missing release |
184
+ | `RateLimitedError` | A `SelfUpdateSourceFailure` for a spent rate limit. `authenticated` says which ceiling, and `resets_at` when it lifts, or None |
183
185
  | `LockUnreadableError` | The release's `uv.lock` could not be read, so nothing was installed |
184
186
  | `InstallFailedError` | `uv tool install` ran and failed, or uv is not on `PATH` |
185
187
 
@@ -24,7 +24,9 @@ from pyselfupdate.errors import LocalInstallError
24
24
  from pyselfupdate.errors import LockUnreadableError
25
25
  from pyselfupdate.errors import NoReleaseError
26
26
  from pyselfupdate.errors import NotInstalledError
27
+ from pyselfupdate.errors import RateLimitedError
27
28
  from pyselfupdate.errors import SelfUpdateError
29
+ from pyselfupdate.errors import SelfUpdateSourceFailure
28
30
  from pyselfupdate.errors import SourceError
29
31
  from pyselfupdate.github import GitHubSource
30
32
  from pyselfupdate.install import Installation
@@ -59,9 +61,11 @@ __all__ = [
59
61
  'NoReleaseError',
60
62
  'NotInstalledError',
61
63
  'Outcome',
64
+ 'RateLimitedError',
62
65
  'Release',
63
66
  'Result',
64
67
  'SelfUpdateError',
68
+ 'SelfUpdateSourceFailure',
65
69
  'Skip',
66
70
  'Source',
67
71
  'SourceError',
@@ -1,10 +1,15 @@
1
1
  """Exceptions raised by pyselfupdate.
2
2
 
3
3
  Every failure mode has its own class so callers match on a type rather than on
4
- message text. The hierarchy is one level deep under `SelfUpdateError`, which is
5
- what a caller catches when it does not care why an update did not happen.
4
+ message text. Every class derives from `SelfUpdateError`, which is what a caller
5
+ catches when it does not care why an update did not happen. A class that narrows
6
+ another derives from it, so catching `SourceError` still catches a rate limit.
6
7
  """
7
8
 
9
+ from __future__ import annotations
10
+
11
+ import datetime as dt
12
+
8
13
 
9
14
  class SelfUpdateError(Exception):
10
15
  """Base class for every error this package raises."""
@@ -41,6 +46,31 @@ class SourceError(SelfUpdateError):
41
46
  """The release source could not be reached or returned something unusable."""
42
47
 
43
48
 
49
+ class SelfUpdateSourceFailure(SourceError):
50
+ """A transport or protocol failure, as opposed to a missing release.
51
+
52
+ Distinct from NoReleaseError so a caller can tell "GitHub is unreachable"
53
+ apart from "this repository has published nothing", which are the same HTTP
54
+ status for a private repository and want different messages.
55
+ """
56
+
57
+
58
+ class RateLimitedError(SelfUpdateSourceFailure):
59
+ """The source's rate limit for this caller is spent.
60
+
61
+ `authenticated` says which ceiling was hit. Without a credential the limit
62
+ is shared by every host behind one address, and supplying a token lifts it.
63
+ With one, nothing is left to configure, and the caller can only wait.
64
+ `resets_at` is when the ceiling lifts, in UTC, or None when the response
65
+ did not say.
66
+ """
67
+
68
+ def __init__(self, message: str, *, authenticated: bool, resets_at: dt.datetime | None = None) -> None:
69
+ super().__init__(message)
70
+ self.authenticated = authenticated
71
+ self.resets_at = resets_at
72
+
73
+
44
74
  class InstallFailedError(SelfUpdateError):
45
75
  """The install command ran and failed."""
46
76
 
@@ -27,8 +27,11 @@ from dataclasses import field
27
27
  from typing import IO
28
28
 
29
29
  from pyselfupdate.errors import NoReleaseError
30
+ from pyselfupdate.errors import RateLimitedError
30
31
  from pyselfupdate.errors import SelfUpdateError
32
+ from pyselfupdate.errors import SelfUpdateSourceFailure
31
33
  from pyselfupdate.errors import SourceError
34
+ from pyselfupdate.install import run_command
32
35
  from pyselfupdate.source import Release
33
36
 
34
37
  API = 'https://api.github.com'
@@ -131,7 +134,7 @@ def token_from_command() -> str:
131
134
  if not binary:
132
135
  return ''
133
136
  try:
134
- result = subprocess.run([binary, *argv[1:]], capture_output=True, text=True, check=False, timeout=COMMAND_TIMEOUT_SECONDS) # noqa: S603
137
+ result = run_command([binary, *argv[1:]], timeout=COMMAND_TIMEOUT_SECONDS)
135
138
  except (OSError, subprocess.SubprocessError):
136
139
  return ''
137
140
  return result.stdout.strip() if result.returncode == 0 else ''
@@ -306,15 +309,6 @@ class GitHubSource:
306
309
  raise SelfUpdateSourceFailure(f'{API}{path} returned invalid JSON') from error
307
310
 
308
311
 
309
- class SelfUpdateSourceFailure(SourceError):
310
- """A transport or protocol failure, as opposed to a missing release.
311
-
312
- Distinct from NoReleaseError so a caller can tell "GitHub is unreachable"
313
- apart from "this repository has published nothing", which are the same HTTP
314
- status for a private repository and want different messages.
315
- """
316
-
317
-
318
312
  def _http_error(owner: str, repo: str, error: urllib.error.HTTPError, *, authenticated: bool) -> SelfUpdateError:
319
313
  if error.code == 404:
320
314
  # A private repository reached without a token is indistinguishable
@@ -324,12 +318,14 @@ def _http_error(owner: str, repo: str, error: urllib.error.HTTPError, *, authent
324
318
  if error.code in (401, 403):
325
319
  remaining = error.headers.get('x-ratelimit-remaining') if error.headers else None
326
320
  if remaining == '0':
327
- return SelfUpdateSourceFailure(_rate_limit_message(error, authenticated=authenticated))
321
+ resets_at = _reset_moment(error)
322
+ message = _rate_limit_message(authenticated=authenticated, resets_at=resets_at)
323
+ return RateLimitedError(message, authenticated=authenticated, resets_at=resets_at)
328
324
  return SelfUpdateSourceFailure(f'GitHub refused the request for {owner}/{repo} ({error.code})')
329
325
  return SelfUpdateSourceFailure(f'GitHub returned {error.code} for {owner}/{repo}')
330
326
 
331
327
 
332
- def _rate_limit_message(error: urllib.error.HTTPError, *, authenticated: bool) -> str:
328
+ def _rate_limit_message(*, authenticated: bool, resets_at: dt.datetime | None) -> str:
333
329
  """Which ceiling was hit, and what to do about that one.
334
330
 
335
331
  The two are different problems with different fixes, and one sentence for
@@ -341,7 +337,10 @@ def _rate_limit_message(error: urllib.error.HTTPError, *, authenticated: bool) -
341
337
  The authenticated case should be rare, so it says when the ceiling lifts
342
338
  rather than what to change -- there is nothing to change.
343
339
  """
344
- resets = _reset_clock(error)
340
+ # A wall-clock time rather than "in 43 minutes", because the message is read
341
+ # out of a state file long after the request that produced it and a duration
342
+ # would be counted from the wrong instant.
343
+ resets = f'; resets at {resets_at:%H:%M} UTC' if resets_at else ''
345
344
  if authenticated:
346
345
  return f"GitHub's authenticated rate limit (5,000/hour) is exhausted{resets}"
347
346
  return (
@@ -350,19 +349,13 @@ def _rate_limit_message(error: urllib.error.HTTPError, *, authenticated: bool) -
350
349
  )
351
350
 
352
351
 
353
- def _reset_clock(error: urllib.error.HTTPError) -> str:
354
- """`; resets at 14:22 UTC`, or nothing when the header is absent or unusable.
355
-
356
- A wall-clock time rather than "in 43 minutes", because the message is read
357
- out of a state file long after the request that produced it and a duration
358
- would be counted from the wrong instant.
359
- """
352
+ def _reset_moment(error: urllib.error.HTTPError) -> dt.datetime | None:
353
+ """When the spent limit lifts, in UTC, or None when the header is absent or unusable."""
360
354
  header = error.headers.get('x-ratelimit-reset') if error.headers else None
361
355
  try:
362
- moment = dt.datetime.fromtimestamp(int(header or ''), tz=dt.UTC)
356
+ return dt.datetime.fromtimestamp(int(header or ''), tz=dt.UTC)
363
357
  except (TypeError, ValueError, OSError, OverflowError):
364
- return ''
365
- return f'; resets at {moment:%H:%M} UTC'
358
+ return None
366
359
 
367
360
 
368
361
  def _quote(ref: str) -> str:
@@ -47,6 +47,14 @@ on one line: uv writes every hash as a continuation line, and
47
47
  `_pins_from_export` reads line by line.
48
48
  """
49
49
 
50
+ LOCK_READ_TIMEOUT_SECONDS = 120.0
51
+ """The bound on each of the clone and the export that read a release's lock.
52
+
53
+ Both run before anything is installed, so a stalled remote or a credential
54
+ prompt nobody answers fails the update with `LockUnreadableError` rather than
55
+ holding the command someone typed.
56
+ """
57
+
50
58
 
51
59
  class InstallKind(Enum):
52
60
  """How a uv tool was installed, which decides whether it may be updated."""
@@ -64,10 +72,9 @@ class Installation:
64
72
  kind: InstallKind
65
73
  url: str = ''
66
74
 
67
- # Whatever followed the `@` at install time: a tag, a branch or a commit,
68
- # which uv records alike as `rev=`. Empty when the install follows the
69
- # default branch. `updater.installed_from_release` reads it as a release
70
- # tag or refuses it.
75
+ # Whatever followed the `@` at install time, read from the receipt by
76
+ # `_split_git`. `updater.installed_from_release` reads it as a release tag
77
+ # or refuses it.
71
78
  revision: str = ''
72
79
 
73
80
  extras: tuple[str, ...] = ()
@@ -121,7 +128,11 @@ def read_installation(tool: str) -> Installation:
121
128
  """
122
129
  receipt = tool_dir() / tool / RECEIPT_NAME
123
130
  if not receipt.is_file():
124
- raise NotInstalledError(f'{tool} is not installed as a uv tool ({receipt} does not exist)')
131
+ raise NotInstalledError(
132
+ f'{tool} is not installed as a uv tool ({receipt} does not exist). '
133
+ f"Install a release with `uv tool install '{tool} @ git+<repository url>@<release tag>'`, "
134
+ f'or `uv tool install {tool}` from a package index'
135
+ )
125
136
 
126
137
  try:
127
138
  payload = tomllib.loads(receipt.read_text(encoding='utf-8'))
@@ -318,25 +329,37 @@ def read_lock(url: str, ref: str, *, extras: Sequence[str] = ()) -> Pins | None:
318
329
  a dependent requests of a git dependency, which `_override_extras` restores.
319
330
 
320
331
  Raises `LockUnreadableError` when git or uv is not on PATH, the ref will not
321
- clone, or uv will not export its lock. None is not a failure:
332
+ clone, uv will not export its lock, or either outlasts
333
+ `LOCK_READ_TIMEOUT_SECONDS`. None is not a failure:
322
334
  `install_release` installs that tag unlocked and sets `lock_missing`.
323
335
  """
324
336
  git = shutil.which('git')
325
337
  uv = shutil.which('uv')
326
338
  if not git or not uv:
327
339
  missing = 'git' if not git else 'uv'
328
- raise LockUnreadableError(f'{missing} is not on PATH, so the uv.lock at {ref} cannot be read')
340
+ raise LockUnreadableError(
341
+ f'{missing} is not on PATH, so the uv.lock at {ref} cannot be read. '
342
+ f'Install {missing}, or add the directory holding it to PATH, then run the update again'
343
+ )
329
344
 
330
345
  # A clone that cannot be deleted stays in the system temp, and the update goes ahead.
331
346
  with tempfile.TemporaryDirectory(prefix='pyselfupdate-lock-', ignore_cleanup_errors=True) as scratch:
332
347
  checkout = Path(scratch) / 'checkout'
333
- cloned = _run([git, 'clone', '--quiet', '--depth', '1', '--branch', ref, url, str(checkout)])
348
+ clone = [git, 'clone', '--quiet', '--depth', '1', '--branch', ref, url, str(checkout)]
349
+ try:
350
+ cloned = run_command(clone, timeout=LOCK_READ_TIMEOUT_SECONDS)
351
+ except subprocess.TimeoutExpired as error:
352
+ raise LockUnreadableError(f'cloning {url} at {ref} to read its uv.lock took longer than {error.timeout:g}s') from error
334
353
  if cloned.returncode != 0:
335
354
  raise LockUnreadableError(f'could not clone {url} at {ref} to read its uv.lock: {_reason(cloned)}')
336
355
  lock = checkout / LOCK_NAME
337
356
  if not lock.is_file():
338
357
  return None
339
- exported = _run([uv, *EXPORT, *chain.from_iterable(('--extra', extra) for extra in extras)], cwd=checkout)
358
+ export = [uv, *EXPORT, *chain.from_iterable(('--extra', extra) for extra in extras)]
359
+ try:
360
+ exported = run_command(export, cwd=checkout, timeout=LOCK_READ_TIMEOUT_SECONDS)
361
+ except subprocess.TimeoutExpired as error:
362
+ raise LockUnreadableError(f'uv export of the uv.lock at {ref} took longer than {error.timeout:g}s') from error
340
363
  if exported.returncode != 0:
341
364
  raise LockUnreadableError(f'uv export would not read the uv.lock at {ref}: {_reason(exported)}')
342
365
  try:
@@ -417,10 +440,16 @@ def run_install(
417
440
  the way `--with` and `--with-editable` install them. `--force` is what
418
441
  allows an entry point that already exists to be replaced; without it uv
419
442
  refuses rather than overwriting.
443
+
444
+ The install runs unbounded. Killed part way, it leaves the tool's
445
+ environment half rewritten, which is worse than a slow install.
420
446
  """
421
447
  executable = shutil.which('uv')
422
448
  if not executable:
423
- raise InstallFailedError('uv is not on PATH, so the tool cannot reinstall itself')
449
+ raise InstallFailedError(
450
+ 'uv is not on PATH, so the tool cannot reinstall itself. '
451
+ 'Add the directory holding uv to PATH, or install uv from https://docs.astral.sh/uv/, then run the update again'
452
+ )
424
453
 
425
454
  with tempfile.TemporaryDirectory(prefix='pyselfupdate-pins-', ignore_cleanup_errors=True) as scratch:
426
455
  held = pins.arguments(Path(scratch)) if pins else []
@@ -432,14 +461,20 @@ def run_install(
432
461
  command = [executable, 'tool', 'install', '--force', *source_flags, *held, *beside, requirement]
433
462
  if quiet:
434
463
  command.insert(1, '--quiet')
435
- completed = _run(command)
464
+ completed = run_command(command)
436
465
 
437
466
  if completed.returncode != 0:
438
467
  raise InstallFailedError(f'uv tool install failed: {_reason(completed)}')
439
468
 
440
469
 
441
- def _run(command: list[str], cwd: Path | None = None) -> subprocess.CompletedProcess[str]:
442
- return subprocess.run(command, cwd=cwd, capture_output=True, text=True, check=False)
470
+ def run_command(command: list[str], *, cwd: Path | None = None, timeout: float | None = None) -> subprocess.CompletedProcess[str]:
471
+ """Run a program to completion and capture what it printed.
472
+
473
+ Every process this package starts goes through here. `timeout` bounds the call in seconds. Past it the program is killed and
474
+ `subprocess.TimeoutExpired` is raised, which each caller turns into its own
475
+ failure. None runs unbounded.
476
+ """
477
+ return subprocess.run(command, cwd=cwd, capture_output=True, text=True, check=False, timeout=timeout)
443
478
 
444
479
 
445
480
  def _reason(completed: subprocess.CompletedProcess[str]) -> str:
@@ -60,9 +60,9 @@ class Result:
60
60
  def check(config: Config) -> Result:
61
61
  """Report whether a newer release exists, without installing anything.
62
62
 
63
- Compares versions and reads nothing else. A branch build's version can rank
64
- below the release it is ahead of, so a caller reporting the result runs
63
+ Compares versions and reads nothing else. A caller reporting the result runs
65
64
  `require_updatable` first, as `update` and `typercmd.run_update` do.
65
+ `installed_from_release` says why a version alone cannot decide.
66
66
  """
67
67
  resolved = config.resolved()
68
68
  current = _current_version(resolved)
File without changes
File without changes