pyselfupdate 0.1.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.
@@ -0,0 +1,261 @@
1
+ """Telling the user a newer release exists, and nothing else.
2
+
3
+ This layer never installs. `<tool> update` installs, and `<tool> update` is
4
+ where errors are printed; a failure here is recorded in the state file and
5
+ swallowed. That single rule is what keeps a dev checkout from printing an
6
+ upgrade failure on every invocation.
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ import atexit
12
+ import os
13
+ import sys
14
+ import time
15
+ from collections.abc import Iterable
16
+ from dataclasses import dataclass
17
+ from datetime import timedelta
18
+ from enum import Enum
19
+ from typing import Any
20
+ from typing import TextIO
21
+
22
+ from pyselfupdate import state as state_module
23
+ from pyselfupdate.config import Config
24
+ from pyselfupdate.errors import SelfUpdateError
25
+ from pyselfupdate.install import InstallKind
26
+ from pyselfupdate.install import read_installation
27
+ from pyselfupdate.updater import check
28
+
29
+ DEFAULT_INTERVAL = timedelta(hours=24)
30
+
31
+ # Environment variables. Presence-only, any value including empty -- the
32
+ # NO_COLOR convention -- so that NO_AUTO_UPDATE=0 cannot mean "on". The interval
33
+ # gets its own name precisely so presence and value never share one variable.
34
+ FLEET_DISABLE = 'NO_AUTO_UPDATE'
35
+ FLEET_INTERVAL = 'AUTO_UPDATE_INTERVAL'
36
+
37
+ CI_VARIABLES = ('CI', 'BUILD_NUMBER', 'RUN_ID', 'GITHUB_ACTIONS', 'CODESPACES')
38
+
39
+
40
+ class Skip(Enum):
41
+ """Why a check did not happen."""
42
+
43
+ DISABLED = 'disabled'
44
+ LOCAL_INSTALL = 'local-install'
45
+ NOT_A_TTY = 'not-a-tty'
46
+ CI = 'ci'
47
+ INTERVAL = 'interval'
48
+ FAILED = 'failed'
49
+
50
+
51
+ @dataclass(frozen=True)
52
+ class Outcome:
53
+ """What `notify` did. Returned for tests and dashboards, not for control flow."""
54
+
55
+ checked: bool = False
56
+ skip: Skip | None = None
57
+ current: str = ''
58
+ latest: str = ''
59
+
60
+ @property
61
+ def update_available(self) -> bool:
62
+ return bool(self.latest) and self.latest != self.current
63
+
64
+
65
+ def notify(
66
+ config: Config,
67
+ *,
68
+ interval: timedelta | None = None,
69
+ out: TextIO | None = None,
70
+ defer: bool = True,
71
+ interactive: bool | None = None,
72
+ ) -> Outcome:
73
+ """Check at most once per interval and print one line when behind.
74
+
75
+ Never raises. Call it from a CLI's root callback and ignore the return
76
+ value; an update notice must not be able to break the command the user
77
+ actually typed.
78
+
79
+ With `defer` the notice is printed at interpreter exit rather than
80
+ immediately, so it lands after the command's own output instead of being
81
+ buried in it.
82
+
83
+ `interactive` overrides terminal detection. Pass False from a program that
84
+ already knows it is writing somewhere a human will not read -- into a pager,
85
+ a log, a structured-output mode -- since nothing about the streams
86
+ themselves reveals that.
87
+ """
88
+ try:
89
+ return _notify(config, interval=interval, out=out, defer=defer, interactive=interactive)
90
+ except SelfUpdateError:
91
+ return Outcome(skip=Skip.FAILED)
92
+ except Exception: # noqa: BLE001 - a notice may never break the caller
93
+ return Outcome(skip=Skip.FAILED)
94
+
95
+
96
+ def enabled(config: Config, *, interactive: bool | None = None) -> tuple[bool, Skip | None]:
97
+ """Whether a check would run, without touching the network or the clock.
98
+
99
+ Backs `<tool> update --why` and any fleet dashboard. The interval is
100
+ deliberately not consulted: this answers "is this tool opted in", not "is it
101
+ due".
102
+ """
103
+ if _disabled_by_env(config.tool):
104
+ return False, Skip.DISABLED
105
+ if not (_is_interactive() if interactive is None else interactive):
106
+ return False, Skip.NOT_A_TTY
107
+ if _in_ci():
108
+ return False, Skip.CI
109
+ if _is_local_install(config.tool):
110
+ return False, Skip.LOCAL_INSTALL
111
+ return True, None
112
+
113
+
114
+ def _notify(
115
+ config: Config,
116
+ *,
117
+ interval: timedelta | None,
118
+ out: TextIO | None,
119
+ defer: bool,
120
+ interactive: bool | None,
121
+ ) -> Outcome:
122
+ resolved = config.resolved()
123
+ tool = resolved.tool
124
+
125
+ allowed, reason = enabled(resolved, interactive=interactive)
126
+ if not allowed:
127
+ return Outcome(skip=reason)
128
+
129
+ stored = state_module.read(tool)
130
+ window = _interval(tool, interval)
131
+ if not _is_due(stored, window):
132
+ return Outcome(skip=Skip.INTERVAL)
133
+
134
+ # Stamped before the network call, not after. gh stamps only on success, so
135
+ # a rate-limited or offline user re-hits the API on every single invocation
136
+ # until the window resets. The whole point of an interval is to bound the
137
+ # request rate, and only this ordering actually does that.
138
+ stored.skip = ''
139
+ state_module.write(state_module.stamp(stored))
140
+
141
+ try:
142
+ result = check(resolved)
143
+ except SelfUpdateError as error:
144
+ stored.last_error = str(error)
145
+ state_module.write(stored)
146
+ return Outcome(skip=Skip.FAILED)
147
+
148
+ stored.last_error = ''
149
+ stored.current_version = result.current
150
+ stored.latest_version = result.latest
151
+ state_module.write(stored)
152
+
153
+ if not result.update_available:
154
+ return Outcome(checked=True, current=result.current, latest=result.latest)
155
+
156
+ message = f'{tool} {result.latest} available (running {result.current}) — run `{tool} update`'
157
+ _emit(message, out=out, defer=defer)
158
+ return Outcome(checked=True, current=result.current, latest=result.latest)
159
+
160
+
161
+ def _emit(message: str, *, out: TextIO | None, defer: bool) -> None:
162
+ stream = out or sys.stderr
163
+ if not defer:
164
+ print(message, file=stream)
165
+ return
166
+
167
+ def flush() -> None:
168
+ try:
169
+ print(message, file=stream)
170
+ except (OSError, ValueError):
171
+ # The stream can be closed by the time interpreter shutdown runs.
172
+ return
173
+
174
+ atexit.register(flush)
175
+
176
+
177
+ def _disabled_by_env(tool: str) -> bool:
178
+ return FLEET_DISABLE in os.environ or _tool_variable(tool, 'NO_AUTO_UPDATE') in os.environ
179
+
180
+
181
+ def _in_ci() -> bool:
182
+ return any(name in os.environ for name in CI_VARIABLES)
183
+
184
+
185
+ def _is_interactive(streams: Iterable[Any] | None = None) -> bool:
186
+ """Both streams must be terminals.
187
+
188
+ Checking both matters: `tool list | jq` should still be allowed to notify on
189
+ stderr, but `tool list > file 2>&1` must not, or the notice lands in the
190
+ file. Requiring both is the conservative reading and matches gh.
191
+
192
+ Typed loosely rather than as TextIO: all this needs is `isatty`, the check
193
+ below is deliberate duck-typing, and demanding the full TextIO surface
194
+ would reject both a reasonable stand-in and the object-without-isatty
195
+ case this is written to survive.
196
+
197
+ `streams` exists so this can be tested without reassigning `sys.stdout`,
198
+ which pytest's capture reinstalls between fixture setup and the test call.
199
+ """
200
+ for stream in streams or (sys.stdout, sys.stderr):
201
+ try:
202
+ if not stream.isatty():
203
+ return False
204
+ except (AttributeError, ValueError):
205
+ return False
206
+ return True
207
+
208
+
209
+ def _is_local_install(tool: str) -> bool:
210
+ """A local, editable, or branch-tracking install must never be nagged.
211
+
212
+ Failing closed: anything that cannot be positively identified as a pinned
213
+ release install is treated as local, because a false negative here prints a
214
+ wrong notice on every command in a dev checkout.
215
+ """
216
+ try:
217
+ installation = read_installation(tool)
218
+ except SelfUpdateError:
219
+ return True
220
+ if installation.kind is InstallKind.LOCAL:
221
+ return True
222
+ return installation.kind is InstallKind.GIT and not installation.revision
223
+
224
+
225
+ def _interval(tool: str, override: timedelta | None) -> timedelta:
226
+ if override is not None:
227
+ return override
228
+ for name in (_tool_variable(tool, 'AUTO_UPDATE_INTERVAL'), FLEET_INTERVAL):
229
+ raw = os.environ.get(name)
230
+ if raw:
231
+ parsed = _parse_interval(raw)
232
+ if parsed is not None:
233
+ return parsed
234
+ return DEFAULT_INTERVAL
235
+
236
+
237
+ def _parse_interval(raw: str) -> timedelta | None:
238
+ """Parse `30m`, `24h`, `7d`, or a bare number of seconds."""
239
+ raw = raw.strip().lower()
240
+ if not raw:
241
+ return None
242
+ units = {'s': 1, 'm': 60, 'h': 3600, 'd': 86400}
243
+ multiplier = units.get(raw[-1])
244
+ number = raw[:-1] if multiplier else raw
245
+ try:
246
+ value = float(number)
247
+ except ValueError:
248
+ return None
249
+ if value < 0:
250
+ return None
251
+ return timedelta(seconds=value * (multiplier or 1))
252
+
253
+
254
+ def _is_due(stored: state_module.State, window: timedelta) -> bool:
255
+ if not stored.checked_at_epoch:
256
+ return True
257
+ return time.time() - stored.checked_at_epoch >= window.total_seconds()
258
+
259
+
260
+ def _tool_variable(tool: str, suffix: str) -> str:
261
+ return f'{tool.upper().replace("-", "_")}_{suffix}'
pyselfupdate/py.typed ADDED
File without changes
pyselfupdate/source.py ADDED
@@ -0,0 +1,51 @@
1
+ """Where releases come from.
2
+
3
+ `Source` is the seam that keeps the rest of the package off the network in
4
+ tests, and that lets a caller publish releases somewhere other than GitHub.
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ from dataclasses import dataclass
10
+ from dataclasses import field
11
+ from typing import Protocol
12
+ from typing import runtime_checkable
13
+
14
+
15
+ @dataclass(frozen=True)
16
+ class Release:
17
+ """One published release."""
18
+
19
+ tag: str
20
+ url: str = ''
21
+ notes: str = ''
22
+
23
+ # The reference to install. For a git source this is what goes after `@` in
24
+ # the requirement; it is kept separate from `tag` because a repository
25
+ # publishing several streams tags them with a prefix that the installer has
26
+ # to reproduce exactly while the version shown to a user should not carry it.
27
+ ref: str = ''
28
+ metadata: dict[str, str] = field(default_factory=dict)
29
+
30
+ def install_ref(self) -> str:
31
+ return self.ref or self.tag
32
+
33
+
34
+ @runtime_checkable
35
+ class Source(Protocol):
36
+ """Locates the newest release."""
37
+
38
+ def latest_release(self) -> Release:
39
+ """The newest release, or raise NoReleaseError when there is none."""
40
+ ...
41
+
42
+
43
+ @runtime_checkable
44
+ class Changeloger(Protocol):
45
+ """A source that can describe what changed between two versions.
46
+
47
+ Separate from `Source` because it is optional: a source that cannot produce
48
+ one is not broken, and callers degrade to printing nothing.
49
+ """
50
+
51
+ def changelog(self, from_ref: str, to_ref: str) -> list[str]: ...
pyselfupdate/state.py ADDED
@@ -0,0 +1,103 @@
1
+ """The per-tool state file.
2
+
3
+ One schema, shared byte-for-byte with goselfupdate and bashselfupdate, so that
4
+ any tool can read any other tool's state and a single dashboard can glob
5
+ `~/.local/state/*/autoupdate.json` with no per-tool knowledge.
6
+
7
+ State, not config and not cache: it persists across runs, it is not authored by
8
+ the user, and deleting it changes behaviour rather than merely costing a
9
+ recompute. That is `XDG_STATE_HOME` by the Base Directory specification, and it
10
+ is where `gh` puts the same thing.
11
+ """
12
+
13
+ from __future__ import annotations
14
+
15
+ import json
16
+ import os
17
+ from dataclasses import asdict
18
+ from dataclasses import dataclass
19
+ from datetime import UTC
20
+ from datetime import datetime
21
+ from pathlib import Path
22
+
23
+ SCHEMA = 1
24
+ FILENAME = 'autoupdate.json'
25
+
26
+
27
+ @dataclass
28
+ class State:
29
+ """One tool's record of its last update check."""
30
+
31
+ tool: str
32
+ schema: int = SCHEMA
33
+ checked_at: str = ''
34
+
35
+ # The same instant as `checked_at`, as an integer. Redundant on purpose:
36
+ # BSD `date` cannot parse ISO-8601 without `-j -f` gymnastics, and the bash
37
+ # implementation has to do interval arithmetic with `jq` and `date +%s`
38
+ # alone. One duplicated field buys a portable bash implementation.
39
+ checked_at_epoch: int = 0
40
+
41
+ current_version: str = ''
42
+ latest_version: str = ''
43
+ last_error: str = ''
44
+
45
+ # Why the last run did not check, empty when it did. This is the only trace
46
+ # a silently skipping tool leaves, and the reason a dashboard can explain
47
+ # itself.
48
+ skip: str = ''
49
+
50
+
51
+ def state_home() -> Path:
52
+ override = os.environ.get('XDG_STATE_HOME')
53
+ base = Path(override).expanduser() if override else Path.home() / '.local' / 'state'
54
+ return base
55
+
56
+
57
+ def state_path(tool: str) -> Path:
58
+ return state_home() / tool / FILENAME
59
+
60
+
61
+ def read(tool: str) -> State:
62
+ """A tool's state, or an empty one when it has never been written.
63
+
64
+ A corrupt or unreadable file reads as empty rather than raising: the file is
65
+ a throttle, and failing a user's command because the throttle cannot be read
66
+ would be worse than checking one extra time.
67
+ """
68
+ path = state_path(tool)
69
+ try:
70
+ payload = json.loads(path.read_text(encoding='utf-8'))
71
+ except (OSError, json.JSONDecodeError, ValueError):
72
+ return State(tool=tool)
73
+
74
+ if not isinstance(payload, dict):
75
+ return State(tool=tool)
76
+
77
+ known = {field for field in State.__dataclass_fields__}
78
+ return State(**{key: value for key, value in payload.items() if key in known} | {'tool': tool})
79
+
80
+
81
+ def write(state: State) -> None:
82
+ """Persist a tool's state atomically.
83
+
84
+ Written to a temporary file in the same directory and renamed, so a reader
85
+ sees either the whole previous file or the whole new one. Failures are
86
+ swallowed for the same reason `read` tolerates corruption.
87
+ """
88
+ path = state_path(state.tool)
89
+ try:
90
+ path.parent.mkdir(parents=True, exist_ok=True)
91
+ temporary = path.with_name(f'.{path.name}.tmp')
92
+ temporary.write_text(json.dumps(asdict(state), indent=2) + '\n', encoding='utf-8')
93
+ temporary.replace(path)
94
+ except OSError:
95
+ return
96
+
97
+
98
+ def stamp(state: State, moment: datetime | None = None) -> State:
99
+ """Set both timestamp fields to the same instant."""
100
+ now = moment or datetime.now(UTC)
101
+ state.checked_at = now.strftime('%Y-%m-%dT%H:%M:%SZ')
102
+ state.checked_at_epoch = int(now.timestamp())
103
+ return state
@@ -0,0 +1,86 @@
1
+ """A ready-made `update` command for CLIs built with typer.
2
+
3
+ A separate module, installed with the `typer` extra, so that importing
4
+ pyselfupdate does not impose a CLI framework on a project using argparse,
5
+ click or anything else:
6
+
7
+ uv add "pyselfupdate[typer]"
8
+
9
+ from pyselfupdate import Config
10
+ from pyselfupdate.typercmd import add_update_command
11
+
12
+ config = Config(tool='syncer', owner='datapointchris')
13
+ add_update_command(app, config)
14
+
15
+ Go solves the same problem with module graph pruning, which lets goselfupdate
16
+ keep cobra in a subpackage that a core-only consumer never downloads. Python
17
+ has no equivalent, so the dependency is an extra and this module imports typer
18
+ at the top -- importing it without the extra fails immediately and clearly
19
+ rather than at the first call.
20
+ """
21
+
22
+ from __future__ import annotations
23
+
24
+ import sys
25
+
26
+ import typer
27
+
28
+ from pyselfupdate.config import Config
29
+ from pyselfupdate.errors import SelfUpdateError
30
+ from pyselfupdate.updater import changelog
31
+ from pyselfupdate.updater import check
32
+ from pyselfupdate.updater import update
33
+
34
+
35
+ def add_update_command(app: typer.Typer, config: Config, *, name: str = 'update') -> None:
36
+ """Register `<tool> update` on an existing typer app."""
37
+
38
+ @app.command(name=name, help=f'Update {config.tool} to the latest release')
39
+ def update_command(
40
+ check_only: bool = typer.Option(False, '--check', help='Report whether an update is available without installing it'),
41
+ skip_changelog: bool = typer.Option(False, '--no-changelog', help='Do not list the commits between versions'),
42
+ ) -> None:
43
+ run_update(config, check_only=check_only, skip_changelog=skip_changelog)
44
+
45
+
46
+ def run_update(config: Config, *, check_only: bool = False, skip_changelog: bool = False) -> None:
47
+ """Run an update and report it, exiting non-zero on failure.
48
+
49
+ Split out from the command so a CLI that wants its own flags, or that nests
50
+ the command under a group, does not have to reimplement the reporting. The
51
+ output format is identical to goselfupdate's, because a fleet that reports
52
+ the same thing three different ways is a fleet you have to read carefully.
53
+ """
54
+ tool = config.tool
55
+ try:
56
+ result = check(config) if check_only else update(config)
57
+ except SelfUpdateError as error:
58
+ typer.echo(f'✗ {tool} upgrade failed: {error}', err=True)
59
+ raise typer.Exit(1) from error
60
+
61
+ if not result.update_available:
62
+ typer.echo(f'✓ {tool} already at latest: {result.latest}')
63
+ return
64
+
65
+ if result.applied:
66
+ typer.echo(f'✓ {tool} upgraded: {result.current} → {result.latest}')
67
+ else:
68
+ typer.echo(f'✓ {tool} update available: {result.current} → {result.latest}')
69
+
70
+ if skip_changelog:
71
+ return
72
+
73
+ subjects = changelog(config, result.current, result.latest)
74
+ if not subjects:
75
+ return
76
+
77
+ typer.echo('')
78
+ typer.echo('Changes:')
79
+ for subject in subjects:
80
+ typer.echo(f' • {subject}')
81
+
82
+ # The environment this interpreter is running in has just been replaced.
83
+ # Nothing more may be imported, so the process ends here rather than
84
+ # returning into a CLI that might touch a lazily-loaded module.
85
+ if result.applied:
86
+ sys.stdout.flush()
@@ -0,0 +1,132 @@
1
+ """Checking for and applying updates."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from dataclasses import dataclass
6
+ from dataclasses import field
7
+
8
+ from pyselfupdate import version as semver
9
+ from pyselfupdate.config import Config
10
+ from pyselfupdate.errors import LocalInstallError
11
+ from pyselfupdate.errors import NoReleaseError
12
+ from pyselfupdate.install import Installation
13
+ from pyselfupdate.install import InstallKind
14
+ from pyselfupdate.install import read_installation
15
+ from pyselfupdate.install import reexec
16
+ from pyselfupdate.install import requirement_for
17
+ from pyselfupdate.install import run_install
18
+ from pyselfupdate.source import Changeloger
19
+ from pyselfupdate.source import Release
20
+
21
+
22
+ @dataclass(frozen=True)
23
+ class Result:
24
+ """What an update found, whether or not it installed anything."""
25
+
26
+ # The running version, canonicalised with a leading "v".
27
+ current: str
28
+
29
+ # The version now installed, or the one `update` would install after a
30
+ # `check`. Equals `current` when nothing is newer.
31
+ latest: str
32
+
33
+ applied: bool = False
34
+ release: Release | None = None
35
+ metadata: dict[str, str] = field(default_factory=dict)
36
+
37
+ @property
38
+ def update_available(self) -> bool:
39
+ return self.current != self.latest
40
+
41
+
42
+ def check(config: Config) -> Result:
43
+ """Report whether a newer release exists, without installing anything."""
44
+ resolved = config.resolved()
45
+ current = _current_version(resolved)
46
+
47
+ release = resolved.require_source().latest_release()
48
+ latest = semver.canonical(release.tag)
49
+ if not semver.is_valid(latest):
50
+ raise NoReleaseError(f'tag {release.tag!r} is not a semantic version')
51
+
52
+ if semver.compare(latest, current) <= 0:
53
+ return Result(current=current, latest=current)
54
+
55
+ return Result(current=current, latest=latest, release=release)
56
+
57
+
58
+ def update(config: Config, *, quiet: bool = True) -> Result:
59
+ """Install the latest release over the running one.
60
+
61
+ A no-op returning `applied=False` when already current. Note that on
62
+ success the running interpreter's environment has been rewritten underneath
63
+ it -- see `pyselfupdate.install.reexec`.
64
+ """
65
+ resolved = config.resolved()
66
+ installation = read_installation(resolved.tool)
67
+ _require_updatable(installation)
68
+
69
+ result = check(resolved)
70
+ if not result.update_available or result.release is None:
71
+ return result
72
+
73
+ requirement = requirement_for(installation, result.release.install_ref())
74
+ run_install(requirement, quiet=quiet)
75
+
76
+ return Result(
77
+ current=result.current,
78
+ latest=result.latest,
79
+ applied=True,
80
+ release=result.release,
81
+ )
82
+
83
+
84
+ def update_and_reexec(config: Config, *, quiet: bool = True) -> Result:
85
+ """`update`, then replace this process when anything was installed.
86
+
87
+ Returns normally only when nothing was installed; otherwise it does not
88
+ return at all.
89
+ """
90
+ result = update(config, quiet=quiet)
91
+ if result.applied:
92
+ reexec()
93
+ return result
94
+
95
+
96
+ def changelog(config: Config, from_version: str, to_version: str) -> list[str]:
97
+ """Commit subjects between two versions.
98
+
99
+ Returns an empty list when the source cannot produce one, which is not an
100
+ error: a missing changelog must never fail an update that succeeded.
101
+ """
102
+ source = config.resolved().require_source()
103
+ if not isinstance(source, Changeloger):
104
+ return []
105
+ return source.changelog(from_version, to_version)
106
+
107
+
108
+ def _current_version(config: Config) -> str:
109
+ """The running version, canonicalised, rejecting one that is not a release.
110
+
111
+ An install that tracks a git branch rather than a tag reports whatever
112
+ version was in pyproject.toml when it was built, which says nothing about
113
+ how far behind the checkout is. Comparing it against a tag would claim an
114
+ update is available on every run, or none ever.
115
+ """
116
+ canonical = semver.canonical(config.version)
117
+ if not semver.is_valid(canonical):
118
+ raise LocalInstallError(f'{config.tool} reports version {config.version!r}, which is not a release version')
119
+ return canonical
120
+
121
+
122
+ def _require_updatable(installation: Installation) -> None:
123
+ if installation.kind is InstallKind.LOCAL:
124
+ raise LocalInstallError(
125
+ f'{installation.tool} is installed from {installation.url}; update the checkout instead of reinstalling over it'
126
+ )
127
+ if installation.kind is InstallKind.GIT and not installation.revision:
128
+ raise LocalInstallError(
129
+ f'{installation.tool} is installed from a branch rather than a tag, '
130
+ f'so a release version cannot be compared against it; '
131
+ f'reinstall from a tagged release to enable updates'
132
+ )