pyselfupdate 0.5.5__tar.gz → 0.7.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.7.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
@@ -33,7 +33,9 @@ release exists. `update` installs that release when the user asks.
33
33
  `uv tool upgrade` re-resolves the requirement a tool was installed with, so a
34
34
  tool installed at a release tag stays at that tag. `update` asks the release
35
35
  source which tag is newest and reinstalls at that tag. A git install is held to
36
- that tag's `uv.lock`.
36
+ that tag's `uv.lock`. A tool installed from a package index is offered only the
37
+ version its index serves, which can trail a release whose upload has not
38
+ finished.
37
39
 
38
40
  The package has no runtime dependencies. It uses `urllib` for the network,
39
41
  `tomllib` for uv's receipt and lock, and its own semver implementation. CI
@@ -94,13 +96,15 @@ A private repository needs a credential. `gh auth login` is enough, because
94
96
  the check runs `gh auth token` by default.
95
97
 
96
98
  **When the notice never appears, run `mytool update --check` first.** It runs
97
- the two steps that can fail, reading uv's receipt and asking the release
98
- source, and prints what stopped it. The notice stays silent on both. Every
99
- other reason it stays silent is in the table under `notify`.
99
+ the steps that can fail and prints what stopped it. Those are reading uv's
100
+ receipt, asking the release source and, for an index install, asking its
101
+ index. The notice stays silent on each. Every other reason it stays silent is
102
+ in the table under `notify`.
100
103
 
101
104
  ## `notify` — one line after the command's output, never an error
102
105
 
103
- Once per 24 hours, when a newer release exists, one line goes to stderr:
106
+ Once per 24 hours, when a newer release can be installed, one line goes to
107
+ stderr:
104
108
 
105
109
  ```text
106
110
  mytool v1.4.0 available (running v1.3.2) — run `mytool update`
@@ -154,17 +158,18 @@ from pyselfupdate import Config, check, require_updatable
154
158
  config = Config(tool='mytool', owner='you')
155
159
 
156
160
  require_updatable(config) # reads uv's receipt; raises on an install update refuses
157
- result = check(config) # one request to the release source
161
+ result = check(config) # asks the release source, and an index install's index
158
162
  if result.update_available:
159
163
  print(result.current, '->', result.latest)
160
164
  ```
161
165
 
162
- `check` compares the running version with the newest release, and reads
163
- nothing else. A branch build's version can rank below the release it is ahead
164
- of. Three commits past `v1.2.3`, a tool versioned from git tags builds as
165
- `1.2.3-post.3+<commit>`, which semver ranks below `v1.2.3`. So call
166
- `require_updatable` before reporting what `check` found. It refuses every
167
- install `update` refuses.
166
+ `check` compares the running version with the newest version an update can
167
+ install. It reads uv's receipt to learn where that version comes from, and
168
+ refuses nothing the receipt describes. A branch build's version can rank below
169
+ the release it is ahead of. Three commits past `v1.2.3`, a tool versioned from
170
+ git tags builds as `1.2.3-post.3+<commit>`, which semver ranks below `v1.2.3`.
171
+ So call `require_updatable` before reporting what `check` found. It refuses
172
+ every install `update` refuses.
168
173
 
169
174
  The typer extra carries the whole command. `add_update_command(app, config)`
170
175
  registers `mytool update`. `run_update(config, check_only=...)` is the same
@@ -203,7 +208,10 @@ caller matches a type rather than message text:
203
208
  | `NotInstalledError` | uv's receipt is missing or unreadable, or holds a `--with` requirement an update would drop |
204
209
  | `NoReleaseError` | The source publishes no release, or its newest tag is not a semantic version |
205
210
  | `SourceError` | The source could not be reached, or answered with something unusable |
211
+ | `SelfUpdateSourceFailure` | A `SourceError` from a transport or protocol failure, as opposed to a missing release |
212
+ | `RateLimitedError` | A `SelfUpdateSourceFailure` for a spent rate limit. `authenticated` says which ceiling, and `resets_at` when it lifts, or None |
206
213
  | `LockUnreadableError` | The release's `uv.lock` could not be read, so nothing was installed |
214
+ | `IndexUnreadableError` | uv could not say which version an index install's package index serves, so nothing was offered |
207
215
  | `InstallFailedError` | `uv tool install` ran and failed, or uv is not on `PATH` |
208
216
 
209
217
  ### A git install is held to the release's `uv.lock`
@@ -221,11 +229,6 @@ later `uv tool upgrade` stays held to them.
221
229
  | Carries none | Installs unlocked and sets `lock_missing`. `lock_warning` names the tag, and `run_update` and `update_and_reexec` print it |
222
230
  | Will not clone, uv will not export its lock, or git or uv is not on `PATH` | Raises `LockUnreadableError` and installs nothing |
223
231
 
224
- An install from an index reads no lock, because a wheel carries none. It
225
- takes the release as a floor, `mytool>=2.0.0`, rather than a pin. uv records
226
- the specifier in the receipt, and `uv tool upgrade` refuses to move an exact
227
- pin.
228
-
229
232
  An update reinstalls the tool's own extras, as in `mytool[fast]`, with their
230
233
  dependencies held to the lock. Every `--with` and `--with-editable`
231
234
  requirement is passed back to uv as well.
@@ -241,6 +244,26 @@ file can declare one and the reinstall reads that file again. Dropping any
241
244
  other recorded option changes how the tool resolves or builds, never whether it
242
245
  is found.
243
246
 
247
+ ### An index install is offered only what its index serves
248
+
249
+ A release exists on GitHub before its upload to the package index finishes,
250
+ and stays there when the upload fails. So for an index install `check` asks
251
+ the index too, through uv. It runs `uv pip compile --no-deps` on the tool's
252
+ name with the flags above, so uv reads the index with the configuration and
253
+ credentials the reinstall uses. The version uv names becomes `latest`, and
254
+ `index_latest` holds it.
255
+
256
+ | The index serves | What `check` reports |
257
+ | --- | --- |
258
+ | The newest release | `latest` is that release |
259
+ | Another version | `latest` is the index's version, or `current` when that is not newer. `index_warning` names both versions, and `run_update` and `update_and_reexec` print it |
260
+ | Nothing uv can read within `Config.timeout` seconds | Raises `IndexUnreadableError` |
261
+
262
+ An install from an index reads no lock, because a wheel carries none. It
263
+ takes the index's version as a floor, `mytool>=2.0.0`, rather than a pin. uv
264
+ records the specifier in the receipt, and `uv tool upgrade` refuses to move an
265
+ exact pin.
266
+
244
267
  ## What may be updated is read from uv's receipt, not guessed from the version
245
268
 
246
269
  uv writes `uv-receipt.toml` into the tool's directory at install time. It
@@ -279,7 +302,7 @@ config = Config(
279
302
  version='1.2.3', # defaults to that distribution's installed metadata
280
303
  token='', # see Authentication below; you almost certainly want the default
281
304
  token_func=None, # a source of your own, tried before $GITHUB_TOKEN_COMMAND
282
- timeout=10.0, # seconds, per request
305
+ timeout=10.0, # seconds per read: the release source's, and uv's read of an index
283
306
  tag_prefix='', # 'cli/' for tags like cli/v1.2.3
284
307
  allow_prerelease=False,
285
308
  source=None, # a custom Source; defaults to a GitHubSource built from the fields above
@@ -10,7 +10,9 @@ release exists. `update` installs that release when the user asks.
10
10
  `uv tool upgrade` re-resolves the requirement a tool was installed with, so a
11
11
  tool installed at a release tag stays at that tag. `update` asks the release
12
12
  source which tag is newest and reinstalls at that tag. A git install is held to
13
- that tag's `uv.lock`.
13
+ that tag's `uv.lock`. A tool installed from a package index is offered only the
14
+ version its index serves, which can trail a release whose upload has not
15
+ finished.
14
16
 
15
17
  The package has no runtime dependencies. It uses `urllib` for the network,
16
18
  `tomllib` for uv's receipt and lock, and its own semver implementation. CI
@@ -71,13 +73,15 @@ A private repository needs a credential. `gh auth login` is enough, because
71
73
  the check runs `gh auth token` by default.
72
74
 
73
75
  **When the notice never appears, run `mytool update --check` first.** It runs
74
- the two steps that can fail, reading uv's receipt and asking the release
75
- source, and prints what stopped it. The notice stays silent on both. Every
76
- other reason it stays silent is in the table under `notify`.
76
+ the steps that can fail and prints what stopped it. Those are reading uv's
77
+ receipt, asking the release source and, for an index install, asking its
78
+ index. The notice stays silent on each. Every other reason it stays silent is
79
+ in the table under `notify`.
77
80
 
78
81
  ## `notify` — one line after the command's output, never an error
79
82
 
80
- Once per 24 hours, when a newer release exists, one line goes to stderr:
83
+ Once per 24 hours, when a newer release can be installed, one line goes to
84
+ stderr:
81
85
 
82
86
  ```text
83
87
  mytool v1.4.0 available (running v1.3.2) — run `mytool update`
@@ -131,17 +135,18 @@ from pyselfupdate import Config, check, require_updatable
131
135
  config = Config(tool='mytool', owner='you')
132
136
 
133
137
  require_updatable(config) # reads uv's receipt; raises on an install update refuses
134
- result = check(config) # one request to the release source
138
+ result = check(config) # asks the release source, and an index install's index
135
139
  if result.update_available:
136
140
  print(result.current, '->', result.latest)
137
141
  ```
138
142
 
139
- `check` compares the running version with the newest release, and reads
140
- nothing else. A branch build's version can rank below the release it is ahead
141
- of. Three commits past `v1.2.3`, a tool versioned from git tags builds as
142
- `1.2.3-post.3+<commit>`, which semver ranks below `v1.2.3`. So call
143
- `require_updatable` before reporting what `check` found. It refuses every
144
- install `update` refuses.
143
+ `check` compares the running version with the newest version an update can
144
+ install. It reads uv's receipt to learn where that version comes from, and
145
+ refuses nothing the receipt describes. A branch build's version can rank below
146
+ the release it is ahead of. Three commits past `v1.2.3`, a tool versioned from
147
+ git tags builds as `1.2.3-post.3+<commit>`, which semver ranks below `v1.2.3`.
148
+ So call `require_updatable` before reporting what `check` found. It refuses
149
+ every install `update` refuses.
145
150
 
146
151
  The typer extra carries the whole command. `add_update_command(app, config)`
147
152
  registers `mytool update`. `run_update(config, check_only=...)` is the same
@@ -180,7 +185,10 @@ caller matches a type rather than message text:
180
185
  | `NotInstalledError` | uv's receipt is missing or unreadable, or holds a `--with` requirement an update would drop |
181
186
  | `NoReleaseError` | The source publishes no release, or its newest tag is not a semantic version |
182
187
  | `SourceError` | The source could not be reached, or answered with something unusable |
188
+ | `SelfUpdateSourceFailure` | A `SourceError` from a transport or protocol failure, as opposed to a missing release |
189
+ | `RateLimitedError` | A `SelfUpdateSourceFailure` for a spent rate limit. `authenticated` says which ceiling, and `resets_at` when it lifts, or None |
183
190
  | `LockUnreadableError` | The release's `uv.lock` could not be read, so nothing was installed |
191
+ | `IndexUnreadableError` | uv could not say which version an index install's package index serves, so nothing was offered |
184
192
  | `InstallFailedError` | `uv tool install` ran and failed, or uv is not on `PATH` |
185
193
 
186
194
  ### A git install is held to the release's `uv.lock`
@@ -198,11 +206,6 @@ later `uv tool upgrade` stays held to them.
198
206
  | Carries none | Installs unlocked and sets `lock_missing`. `lock_warning` names the tag, and `run_update` and `update_and_reexec` print it |
199
207
  | Will not clone, uv will not export its lock, or git or uv is not on `PATH` | Raises `LockUnreadableError` and installs nothing |
200
208
 
201
- An install from an index reads no lock, because a wheel carries none. It
202
- takes the release as a floor, `mytool>=2.0.0`, rather than a pin. uv records
203
- the specifier in the receipt, and `uv tool upgrade` refuses to move an exact
204
- pin.
205
-
206
209
  An update reinstalls the tool's own extras, as in `mytool[fast]`, with their
207
210
  dependencies held to the lock. Every `--with` and `--with-editable`
208
211
  requirement is passed back to uv as well.
@@ -218,6 +221,26 @@ file can declare one and the reinstall reads that file again. Dropping any
218
221
  other recorded option changes how the tool resolves or builds, never whether it
219
222
  is found.
220
223
 
224
+ ### An index install is offered only what its index serves
225
+
226
+ A release exists on GitHub before its upload to the package index finishes,
227
+ and stays there when the upload fails. So for an index install `check` asks
228
+ the index too, through uv. It runs `uv pip compile --no-deps` on the tool's
229
+ name with the flags above, so uv reads the index with the configuration and
230
+ credentials the reinstall uses. The version uv names becomes `latest`, and
231
+ `index_latest` holds it.
232
+
233
+ | The index serves | What `check` reports |
234
+ | --- | --- |
235
+ | The newest release | `latest` is that release |
236
+ | Another version | `latest` is the index's version, or `current` when that is not newer. `index_warning` names both versions, and `run_update` and `update_and_reexec` print it |
237
+ | Nothing uv can read within `Config.timeout` seconds | Raises `IndexUnreadableError` |
238
+
239
+ An install from an index reads no lock, because a wheel carries none. It
240
+ takes the index's version as a floor, `mytool>=2.0.0`, rather than a pin. uv
241
+ records the specifier in the receipt, and `uv tool upgrade` refuses to move an
242
+ exact pin.
243
+
221
244
  ## What may be updated is read from uv's receipt, not guessed from the version
222
245
 
223
246
  uv writes `uv-receipt.toml` into the tool's directory at install time. It
@@ -256,7 +279,7 @@ config = Config(
256
279
  version='1.2.3', # defaults to that distribution's installed metadata
257
280
  token='', # see Authentication below; you almost certainly want the default
258
281
  token_func=None, # a source of your own, tried before $GITHUB_TOKEN_COMMAND
259
- timeout=10.0, # seconds, per request
282
+ timeout=10.0, # seconds per read: the release source's, and uv's read of an index
260
283
  tag_prefix='', # 'cli/' for tags like cli/v1.2.3
261
284
  allow_prerelease=False,
262
285
  source=None, # a custom Source; defaults to a GitHubSource built from the fields above
@@ -18,13 +18,16 @@ lives in `pyselfupdate.typercmd` and is installed with the `typer` extra.
18
18
  """
19
19
 
20
20
  from pyselfupdate.config import Config
21
+ from pyselfupdate.errors import IndexUnreadableError
21
22
  from pyselfupdate.errors import InstallFailedError
22
23
  from pyselfupdate.errors import InvalidConfigError
23
24
  from pyselfupdate.errors import LocalInstallError
24
25
  from pyselfupdate.errors import LockUnreadableError
25
26
  from pyselfupdate.errors import NoReleaseError
26
27
  from pyselfupdate.errors import NotInstalledError
28
+ from pyselfupdate.errors import RateLimitedError
27
29
  from pyselfupdate.errors import SelfUpdateError
30
+ from pyselfupdate.errors import SelfUpdateSourceFailure
28
31
  from pyselfupdate.errors import SourceError
29
32
  from pyselfupdate.github import GitHubSource
30
33
  from pyselfupdate.install import Installation
@@ -50,6 +53,7 @@ from pyselfupdate.updater import update_and_reexec
50
53
  __all__ = [
51
54
  'Config',
52
55
  'GitHubSource',
56
+ 'IndexUnreadableError',
53
57
  'InstallFailedError',
54
58
  'InstallKind',
55
59
  'Installation',
@@ -59,9 +63,11 @@ __all__ = [
59
63
  'NoReleaseError',
60
64
  'NotInstalledError',
61
65
  'Outcome',
66
+ 'RateLimitedError',
62
67
  'Release',
63
68
  'Result',
64
69
  'SelfUpdateError',
70
+ 'SelfUpdateSourceFailure',
65
71
  'Skip',
66
72
  'Source',
67
73
  'SourceError',
@@ -46,7 +46,10 @@ class Config:
46
46
  # invocations where the notify gate declines to check.
47
47
  token_func: Callable[[], str] | None = None
48
48
 
49
+ # Seconds that each read a check makes may take: the release source's
50
+ # request, and for an index install uv's read of the package index.
49
51
  timeout: float = DEFAULT_TIMEOUT
52
+
50
53
  allow_prerelease: bool = False
51
54
 
52
55
  # Selects one release stream in a repository publishing several, as in
@@ -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
 
@@ -52,3 +82,12 @@ class LockUnreadableError(SelfUpdateError):
52
82
  refuses the lock. A tag with no `uv.lock` at all is not this error: it
53
83
  installs unlocked and sets `Result.lock_missing`.
54
84
  """
85
+
86
+
87
+ class IndexUnreadableError(SelfUpdateError):
88
+ """uv could not say which version of an index-installed tool its package index serves.
89
+
90
+ Raised when uv is not on PATH, takes longer than `Config.timeout`, cannot
91
+ reach the index, or finds no version of the tool there. Nothing is offered,
92
+ because a version the index does not serve cannot be installed.
93
+ """
@@ -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:
@@ -30,6 +30,7 @@ from importlib.metadata import version as installed_version
30
30
  from itertools import chain
31
31
  from pathlib import Path
32
32
 
33
+ from pyselfupdate.errors import IndexUnreadableError
33
34
  from pyselfupdate.errors import InstallFailedError
34
35
  from pyselfupdate.errors import LockUnreadableError
35
36
  from pyselfupdate.errors import NotInstalledError
@@ -47,6 +48,14 @@ on one line: uv writes every hash as a continuation line, and
47
48
  `_pins_from_export` reads line by line.
48
49
  """
49
50
 
51
+ LOCK_READ_TIMEOUT_SECONDS = 120.0
52
+ """The bound on each of the clone and the export that read a release's lock.
53
+
54
+ Both run before anything is installed, so a stalled remote or a credential
55
+ prompt nobody answers fails the update with `LockUnreadableError` rather than
56
+ holding the command someone typed.
57
+ """
58
+
50
59
 
51
60
  class InstallKind(Enum):
52
61
  """How a uv tool was installed, which decides whether it may be updated."""
@@ -64,10 +73,9 @@ class Installation:
64
73
  kind: InstallKind
65
74
  url: str = ''
66
75
 
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.
76
+ # Whatever followed the `@` at install time, read from the receipt by
77
+ # `_split_git`. `updater.installed_from_release` reads it as a release tag
78
+ # or refuses it.
71
79
  revision: str = ''
72
80
 
73
81
  extras: tuple[str, ...] = ()
@@ -86,7 +94,7 @@ class Installation:
86
94
  # `read_installation` records them rather than raising: the notify gate
87
95
  # treats a failed read as a local install and prints no notice. `update`
88
96
  # raises NotInstalledError on them instead of dropping them.
89
- _unrebuildable: tuple[str, ...] = field(default=(), repr=False)
97
+ unrebuildable: tuple[str, ...] = field(default=(), repr=False)
90
98
 
91
99
 
92
100
  def tool_dir() -> Path:
@@ -121,7 +129,11 @@ def read_installation(tool: str) -> Installation:
121
129
  """
122
130
  receipt = tool_dir() / tool / RECEIPT_NAME
123
131
  if not receipt.is_file():
124
- raise NotInstalledError(f'{tool} is not installed as a uv tool ({receipt} does not exist)')
132
+ raise NotInstalledError(
133
+ f'{tool} is not installed as a uv tool ({receipt} does not exist). '
134
+ f"Install a release with `uv tool install '{tool} @ git+<repository url>@<release tag>'`, "
135
+ f'or `uv tool install {tool}` from a package index'
136
+ )
125
137
 
126
138
  try:
127
139
  payload = tomllib.loads(receipt.read_text(encoding='utf-8'))
@@ -264,6 +276,50 @@ def current_version(package: str) -> str:
264
276
  return ''
265
277
 
266
278
 
279
+ INDEX_READ = ('pip', 'compile', '-', '--no-deps', '--no-header', '--no-annotate', '--quiet')
280
+ """Resolves the requirement read from stdin, and only it, printing `<name>==<version>`."""
281
+
282
+
283
+ def read_index_latest(installation: Installation, *, timeout: float, allow_prerelease: bool = False) -> str:
284
+ """The newest version of an index-installed tool that its package index serves, as uv prints it.
285
+
286
+ A release can exist before its upload to the index finishes, and stays when
287
+ the upload fails, so the release source cannot say what an index install
288
+ can take. uv resolves the tool's name alone, with the receipt's package
289
+ sources, and reads the index through the configuration and credentials the
290
+ reinstall uses. The receipt's `--python` is passed back too, so a release
291
+ that has dropped that Python is not offered. With none recorded, uv
292
+ resolves for the running interpreter.
293
+
294
+ The read is bounded by `timeout`, since the notify gate runs it before the
295
+ command someone typed returns. Raises `IndexUnreadableError` when uv is not
296
+ on PATH, outlasts the bound, or names no version.
297
+ """
298
+ uv = shutil.which('uv')
299
+ if not uv:
300
+ raise IndexUnreadableError(
301
+ f'uv is not on PATH, so the versions of {installation.tool} its package index serves cannot be read. '
302
+ 'Add the directory holding uv to PATH, then check again'
303
+ )
304
+ python = () if '--python' in installation.source_flags else ('--python', sys.executable)
305
+ prerelease = ('--prerelease', 'allow') if allow_prerelease else ()
306
+ command = [uv, *INDEX_READ, *installation.source_flags, *python, *prerelease]
307
+ try:
308
+ resolved = run_command(command, stdin=f'{installation.tool}\n', timeout=timeout)
309
+ except subprocess.TimeoutExpired as error:
310
+ raise IndexUnreadableError(
311
+ f'reading which version of {installation.tool} its package index serves took longer than {error.timeout:g}s'
312
+ ) from error
313
+ if resolved.returncode != 0:
314
+ raise IndexUnreadableError(f'uv could not read which version of {installation.tool} its package index serves: {_reason(resolved)}')
315
+ pinned = [line.split(';', 1)[0].partition('==')[2].strip() for line in resolved.stdout.splitlines() if '==' in line]
316
+ if len(pinned) != 1 or not pinned[0]:
317
+ raise IndexUnreadableError(
318
+ f'uv resolved {installation.tool} from its package index to {resolved.stdout.strip()!r}, which names no one version'
319
+ )
320
+ return pinned[0]
321
+
322
+
267
323
  def requirement_for(installation: Installation, ref: str) -> str:
268
324
  """The requirement string that installs `ref` of an already-installed tool, with the extras it has.
269
325
 
@@ -318,25 +374,37 @@ def read_lock(url: str, ref: str, *, extras: Sequence[str] = ()) -> Pins | None:
318
374
  a dependent requests of a git dependency, which `_override_extras` restores.
319
375
 
320
376
  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:
377
+ clone, uv will not export its lock, or either outlasts
378
+ `LOCK_READ_TIMEOUT_SECONDS`. None is not a failure:
322
379
  `install_release` installs that tag unlocked and sets `lock_missing`.
323
380
  """
324
381
  git = shutil.which('git')
325
382
  uv = shutil.which('uv')
326
383
  if not git or not uv:
327
384
  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')
385
+ raise LockUnreadableError(
386
+ f'{missing} is not on PATH, so the uv.lock at {ref} cannot be read. '
387
+ f'Install {missing}, or add the directory holding it to PATH, then run the update again'
388
+ )
329
389
 
330
390
  # A clone that cannot be deleted stays in the system temp, and the update goes ahead.
331
391
  with tempfile.TemporaryDirectory(prefix='pyselfupdate-lock-', ignore_cleanup_errors=True) as scratch:
332
392
  checkout = Path(scratch) / 'checkout'
333
- cloned = _run([git, 'clone', '--quiet', '--depth', '1', '--branch', ref, url, str(checkout)])
393
+ clone = [git, 'clone', '--quiet', '--depth', '1', '--branch', ref, url, str(checkout)]
394
+ try:
395
+ cloned = run_command(clone, timeout=LOCK_READ_TIMEOUT_SECONDS)
396
+ except subprocess.TimeoutExpired as error:
397
+ raise LockUnreadableError(f'cloning {url} at {ref} to read its uv.lock took longer than {error.timeout:g}s') from error
334
398
  if cloned.returncode != 0:
335
399
  raise LockUnreadableError(f'could not clone {url} at {ref} to read its uv.lock: {_reason(cloned)}')
336
400
  lock = checkout / LOCK_NAME
337
401
  if not lock.is_file():
338
402
  return None
339
- exported = _run([uv, *EXPORT, *chain.from_iterable(('--extra', extra) for extra in extras)], cwd=checkout)
403
+ export = [uv, *EXPORT, *chain.from_iterable(('--extra', extra) for extra in extras)]
404
+ try:
405
+ exported = run_command(export, cwd=checkout, timeout=LOCK_READ_TIMEOUT_SECONDS)
406
+ except subprocess.TimeoutExpired as error:
407
+ raise LockUnreadableError(f'uv export of the uv.lock at {ref} took longer than {error.timeout:g}s') from error
340
408
  if exported.returncode != 0:
341
409
  raise LockUnreadableError(f'uv export would not read the uv.lock at {ref}: {_reason(exported)}')
342
410
  try:
@@ -417,10 +485,16 @@ def run_install(
417
485
  the way `--with` and `--with-editable` install them. `--force` is what
418
486
  allows an entry point that already exists to be replaced; without it uv
419
487
  refuses rather than overwriting.
488
+
489
+ The install runs unbounded. Killed part way, it leaves the tool's
490
+ environment half rewritten, which is worse than a slow install.
420
491
  """
421
492
  executable = shutil.which('uv')
422
493
  if not executable:
423
- raise InstallFailedError('uv is not on PATH, so the tool cannot reinstall itself')
494
+ raise InstallFailedError(
495
+ 'uv is not on PATH, so the tool cannot reinstall itself. '
496
+ 'Add the directory holding uv to PATH, or install uv from https://docs.astral.sh/uv/, then run the update again'
497
+ )
424
498
 
425
499
  with tempfile.TemporaryDirectory(prefix='pyselfupdate-pins-', ignore_cleanup_errors=True) as scratch:
426
500
  held = pins.arguments(Path(scratch)) if pins else []
@@ -432,14 +506,22 @@ def run_install(
432
506
  command = [executable, 'tool', 'install', '--force', *source_flags, *held, *beside, requirement]
433
507
  if quiet:
434
508
  command.insert(1, '--quiet')
435
- completed = _run(command)
509
+ completed = run_command(command)
436
510
 
437
511
  if completed.returncode != 0:
438
512
  raise InstallFailedError(f'uv tool install failed: {_reason(completed)}')
439
513
 
440
514
 
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)
515
+ def run_command(
516
+ command: list[str], *, cwd: Path | None = None, timeout: float | None = None, stdin: str | None = None
517
+ ) -> subprocess.CompletedProcess[str]:
518
+ """Run a program to completion and capture what it printed.
519
+
520
+ Every process this package starts goes through here. `timeout` bounds the call in seconds. Past it the program is killed and
521
+ `subprocess.TimeoutExpired` is raised, which each caller turns into its own
522
+ failure. None runs unbounded. `stdin` is written to the program's standard input.
523
+ """
524
+ return subprocess.run(command, cwd=cwd, input=stdin, capture_output=True, text=True, check=False, timeout=timeout)
443
525
 
444
526
 
445
527
  def _reason(completed: subprocess.CompletedProcess[str]) -> str:
@@ -101,12 +101,14 @@ def run_update(config: Config, *, check_only: bool = False, skip_changelog: bool
101
101
 
102
102
  if not result.update_available:
103
103
  typer.echo(f'✓ {tool} already at latest: {result.latest}')
104
+ _echo_warnings(tool, result.index_warning)
104
105
  return
105
106
 
106
107
  subjects = [] if skip_changelog else changelog(config, result.current, result.latest)
107
108
 
108
109
  if check_only:
109
110
  typer.echo(f'✓ {tool} update available: {result.current} → {result.latest}')
111
+ _echo_warnings(tool, result.index_warning)
110
112
  _echo_changes(subjects)
111
113
  return
112
114
 
@@ -117,12 +119,17 @@ def run_update(config: Config, *, check_only: bool = False, skip_changelog: bool
117
119
  raise typer.Exit(1) from error
118
120
 
119
121
  typer.echo(f'✓ {tool} updated: {result.current} → {result.latest}')
120
- if installed.lock_warning:
121
- typer.echo(f'! {tool}: {installed.lock_warning}', err=True)
122
+ _echo_warnings(tool, installed.lock_warning, installed.index_warning)
122
123
  _echo_changes(subjects)
123
124
  exit_now()
124
125
 
125
126
 
127
+ def _echo_warnings(tool: str, *warnings: str) -> None:
128
+ for warning in warnings:
129
+ if warning:
130
+ typer.echo(f'! {tool}: {warning}', err=True)
131
+
132
+
126
133
  def _echo_changes(subjects: list[str]) -> None:
127
134
  if not subjects:
128
135
  return
@@ -13,6 +13,7 @@ from pyselfupdate.errors import NoReleaseError
13
13
  from pyselfupdate.errors import NotInstalledError
14
14
  from pyselfupdate.install import Installation
15
15
  from pyselfupdate.install import InstallKind
16
+ from pyselfupdate.install import read_index_latest
16
17
  from pyselfupdate.install import read_installation
17
18
  from pyselfupdate.install import read_lock
18
19
  from pyselfupdate.install import reexec
@@ -30,17 +31,25 @@ class Result:
30
31
  current: str
31
32
 
32
33
  # The version now installed, or the one `update` would install after a
33
- # `check`. Equals `current` when nothing is newer.
34
+ # `check`. Equals `current` when nothing newer can be installed. An index
35
+ # install takes it from `index_latest` rather than from `release`.
34
36
  latest: str
35
37
 
36
38
  applied: bool = False
39
+
40
+ # The newest release the source names, whether or not it is newer.
37
41
  release: Release | None = None
42
+
38
43
  metadata: dict[str, str] = field(default_factory=dict)
39
44
 
40
45
  # True when a git install ran unlocked because its tag carries no uv.lock.
41
46
  # An index install reads no lock, so it leaves this False.
42
47
  lock_missing: bool = False
43
48
 
49
+ # For an index install, the newest version its package index serves,
50
+ # canonicalized. Empty for any other install, which takes the release's tag.
51
+ index_latest: str = ''
52
+
44
53
  @property
45
54
  def update_available(self) -> bool:
46
55
  return self.current != self.latest
@@ -56,26 +65,53 @@ class Result:
56
65
  tag = self.release.install_ref() if self.release else self.latest
57
66
  return f'{tag} has no uv.lock, so its dependencies were installed at their newest versions'
58
67
 
68
+ @property
69
+ def index_warning(self) -> str:
70
+ """A line naming both versions when the index serves other than the newest release, else an empty string.
71
+
72
+ `run_update` and `update_and_reexec` print it to stderr.
73
+ """
74
+ if not self.index_latest or self.release is None:
75
+ return ''
76
+ released = semver.canonical(self.release.tag)
77
+ if self.index_latest == released:
78
+ return ''
79
+ return f'the newest release is {released}, but the package index holds {self.index_latest}'
80
+
59
81
 
60
82
  def check(config: Config) -> Result:
61
- """Report whether a newer release exists, without installing anything.
83
+ """Report whether a newer version can be installed, without installing anything.
62
84
 
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
85
+ Reads uv's receipt to learn where an update would come from. A git install
86
+ takes the source's newest release, whose tag exists once the release does.
87
+ An index install takes the newest version its index serves, which
88
+ `read_index_latest` asks uv for: a release can exist before its upload
89
+ finishes, and stays when the upload fails.
90
+
91
+ Raises `NotInstalledError` when the receipt cannot be read, and refuses no
92
+ install the receipt describes. A caller reporting the result runs
65
93
  `require_updatable` first, as `update` and `typercmd.run_update` do.
94
+ `installed_from_release` says why a version alone cannot decide.
66
95
  """
67
96
  resolved = config.resolved()
68
97
  current = _current_version(resolved)
98
+ installation = read_installation(resolved.tool)
69
99
 
70
100
  release = resolved.require_source().latest_release()
71
101
  latest = semver.canonical(release.tag)
72
102
  if not semver.is_valid(latest):
73
103
  raise NoReleaseError(f'tag {release.tag!r} is not a semantic version')
74
104
 
75
- if semver.compare(latest, current) <= 0:
76
- return Result(current=current, latest=current)
105
+ index_latest = ''
106
+ if installation.kind is InstallKind.INDEX:
107
+ served = read_index_latest(installation, timeout=resolved.timeout, allow_prerelease=resolved.allow_prerelease)
108
+ index_latest = latest = semver.canonical(served)
109
+ if not semver.is_valid(index_latest):
110
+ raise NoReleaseError(f'the package index serves {resolved.tool} {served}, which is not a semantic version')
77
111
 
78
- return Result(current=current, latest=latest, release=release)
112
+ if semver.compare(latest, current) <= 0:
113
+ latest = current
114
+ return Result(current=current, latest=latest, release=release, index_latest=index_latest)
79
115
 
80
116
 
81
117
  def require_updatable(config: Config) -> Installation:
@@ -124,12 +160,16 @@ def install_release(config: Config, result: Result, installation: Installation,
124
160
  A git install is held to the `uv.lock` at the release's tag. A tag without
125
161
  one installs unlocked and comes back with `lock_missing` set. A lock that
126
162
  cannot be read raises `LockUnreadableError` before anything is installed.
163
+ An index install takes `latest`, the version its index serves, as a floor.
127
164
  """
128
165
  if not result.update_available or result.release is None:
129
166
  return result
130
167
 
131
- ref = result.release.install_ref()
132
- pins = read_lock(installation.url, ref, extras=installation.extras) if installation.kind is InstallKind.GIT else None
168
+ if installation.kind is InstallKind.GIT:
169
+ ref = result.release.install_ref()
170
+ pins = read_lock(installation.url, ref, extras=installation.extras)
171
+ else:
172
+ ref, pins = result.latest, None
133
173
  run_install(
134
174
  requirement_for(installation, ref),
135
175
  quiet=quiet,
@@ -144,6 +184,7 @@ def install_release(config: Config, result: Result, installation: Installation,
144
184
  applied=True,
145
185
  release=result.release,
146
186
  lock_missing=installation.kind is InstallKind.GIT and pins is None,
187
+ index_latest=result.index_latest,
147
188
  )
148
189
 
149
190
 
@@ -166,12 +207,13 @@ def update_and_reexec(config: Config, *, quiet: bool = True) -> Result:
166
207
 
167
208
  Returns normally only when nothing was installed; otherwise it does not
168
209
  return at all. The caller never sees the `Result` of an install, so this
169
- writes its `lock_warning` to stderr before the re-exec.
210
+ writes its `lock_warning` and `index_warning` to stderr before the re-exec.
170
211
  """
171
212
  result = update(config, quiet=quiet)
172
213
  if result.applied:
173
- if result.lock_warning:
174
- print(f'! {config.tool}: {result.lock_warning}', file=sys.stderr)
214
+ for warning in (result.lock_warning, result.index_warning):
215
+ if warning:
216
+ print(f'! {config.tool}: {warning}', file=sys.stderr)
175
217
  reexec()
176
218
  return result
177
219
 
@@ -213,9 +255,9 @@ def _require_updatable(installation: Installation, tag_prefix: str) -> None:
213
255
  f'so a release version cannot be compared against it; '
214
256
  f'reinstall from a tagged release to enable updates'
215
257
  )
216
- if installation._unrebuildable:
258
+ if installation.unrebuildable:
217
259
  raise NotInstalledError(
218
- f'{installation.tool} was installed with {", ".join(installation._unrebuildable)}, '
260
+ f'{installation.tool} was installed with {", ".join(installation.unrebuildable)}, '
219
261
  f'which an update cannot pass back to uv and would drop. '
220
262
  f'Reinstall {installation.tool} by hand with `uv tool install --force`'
221
263
  )
File without changes
File without changes