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,176 @@
1
+ """Semantic version comparison.
2
+
3
+ Implemented here rather than taken from `packaging` so that this package has no
4
+ third-party dependencies. `packaging` also implements PEP 440, whose precedence
5
+ rules differ from semver's in ways that matter: it normalises `1.0.0-rc.1` to
6
+ `1.0.0rc1` and orders `1.0.0.post1` above `1.0.0`, neither of which describes a
7
+ git tag.
8
+
9
+ Precedence follows https://semver.org section 11, and is byte-for-byte the same
10
+ behaviour as goselfupdate's semver.go so that the two libraries never disagree
11
+ about which of two releases is newer.
12
+ """
13
+
14
+ from __future__ import annotations
15
+
16
+ import re
17
+ from dataclasses import dataclass
18
+
19
+ IDENTIFIER_PATTERN = re.compile(r'^[0-9A-Za-z-]+$')
20
+ NUMERIC_PATTERN = re.compile(r'^[0-9]+$')
21
+
22
+
23
+ @dataclass(frozen=True)
24
+ class Version:
25
+ major: int
26
+ minor: int
27
+ patch: int
28
+ prerelease: str
29
+
30
+
31
+ def parse(text: str) -> Version | None:
32
+ """Parse a version, or None when the text is not one.
33
+
34
+ Accepts an optional leading `v` and one to three numeric components, so
35
+ `v1`, `1.2` and `v1.2.3-rc.1+build` all parse. Absent components are zero.
36
+ """
37
+ text = text.removeprefix('v')
38
+ if not text:
39
+ return None
40
+
41
+ # Build metadata is ignored entirely for precedence.
42
+ plus = text.find('+')
43
+ if plus >= 0:
44
+ text = text[:plus]
45
+
46
+ prerelease = ''
47
+ dash = text.find('-')
48
+ if dash >= 0:
49
+ prerelease = text[dash + 1 :]
50
+ text = text[:dash]
51
+ if not is_valid_prerelease(prerelease):
52
+ return None
53
+
54
+ fields = text.split('.')
55
+ if len(fields) > 3:
56
+ return None
57
+
58
+ numbers = []
59
+ for field in fields:
60
+ number = parse_numeric(field)
61
+ if number is None:
62
+ return None
63
+ numbers.append(number)
64
+ numbers.extend([0] * (3 - len(numbers)))
65
+
66
+ return Version(numbers[0], numbers[1], numbers[2], prerelease)
67
+
68
+
69
+ def parse_numeric(field: str) -> int | None:
70
+ """A numeric component, rejecting the leading zeros the spec disallows."""
71
+ if not NUMERIC_PATTERN.match(field):
72
+ return None
73
+ if len(field) > 1 and field[0] == '0':
74
+ return None
75
+ return int(field)
76
+
77
+
78
+ def is_valid_prerelease(prerelease: str) -> bool:
79
+ if not prerelease:
80
+ return False
81
+ for identifier in prerelease.split('.'):
82
+ if not IDENTIFIER_PATTERN.match(identifier):
83
+ return False
84
+ # A numeric identifier may not carry leading zeros.
85
+ if NUMERIC_PATTERN.match(identifier) and len(identifier) > 1 and identifier[0] == '0':
86
+ return False
87
+ return True
88
+
89
+
90
+ def is_valid(text: str) -> bool:
91
+ return parse(text) is not None
92
+
93
+
94
+ def canonical(text: str) -> str:
95
+ """Add the leading `v` this package prints versions with.
96
+
97
+ Tags carry one and `importlib.metadata` does not, so both forms reach this
98
+ package and have to be reported the same way.
99
+ """
100
+ if not text or text.startswith('v'):
101
+ return text
102
+ return f'v{text}'
103
+
104
+
105
+ def compare(a: str, b: str) -> int:
106
+ """Return -1, 0 or 1 as `a` is less than, equal to, or greater than `b`.
107
+
108
+ Invalid versions sort below valid ones.
109
+ """
110
+ left = parse(a)
111
+ right = parse(b)
112
+ if left is right is None:
113
+ return 0
114
+ if left is None:
115
+ return -1
116
+ if right is None:
117
+ return 1
118
+
119
+ left_core = (left.major, left.minor, left.patch)
120
+ right_core = (right.major, right.minor, right.patch)
121
+ if left_core != right_core:
122
+ return -1 if left_core < right_core else 1
123
+
124
+ return compare_prerelease(left.prerelease, right.prerelease)
125
+
126
+
127
+ def compare_prerelease(a: str, b: str) -> int:
128
+ """Precedence for pre-release identifiers.
129
+
130
+ A version with a pre-release ranks below the same version without one,
131
+ numeric identifiers compare numerically and rank below alphanumeric ones,
132
+ and where all preceding identifiers are equal the longer list wins.
133
+ """
134
+ if a == b:
135
+ return 0
136
+ if not a:
137
+ return 1
138
+ if not b:
139
+ return -1
140
+
141
+ left = a.split('.')
142
+ right = b.split('.')
143
+
144
+ # Indexed rather than zipped because the lists are allowed to differ in
145
+ # length -- the shorter one losing is the rule implemented just below -- and
146
+ # every spelling of that with zip fails a linter: bare zip trips ruff's
147
+ # B905, strict=True is wrong, and strict=False trips refurb's FURB120. This
148
+ # also mirrors goselfupdate's loop exactly.
149
+ for index in range(min(len(left), len(right))):
150
+ result = compare_identifier(left[index], right[index])
151
+ if result != 0:
152
+ return result
153
+
154
+ if len(left) == len(right):
155
+ return 0
156
+ return -1 if len(left) < len(right) else 1
157
+
158
+
159
+ def compare_identifier(a: str, b: str) -> int:
160
+ a_numeric = bool(NUMERIC_PATTERN.match(a))
161
+ b_numeric = bool(NUMERIC_PATTERN.match(b))
162
+
163
+ if a_numeric and b_numeric:
164
+ # Compared as integers rather than strings so that 2 ranks below 11.
165
+ left = int(a)
166
+ right = int(b)
167
+ if left == right:
168
+ return 0
169
+ return -1 if left < right else 1
170
+ if a_numeric:
171
+ return -1
172
+ if b_numeric:
173
+ return 1
174
+ if a == b:
175
+ return 0
176
+ return -1 if a < b else 1
@@ -0,0 +1,203 @@
1
+ Metadata-Version: 2.3
2
+ Name: pyselfupdate
3
+ Version: 0.1.0
4
+ Summary: Self-update and update notification for Python CLIs installed with uv tool
5
+ Keywords: uv,cli,self-update,update-notifier,release
6
+ Author: Chris Birch
7
+ Author-email: Chris Birch <datapointchris@gmail.com>
8
+ License: MIT
9
+ Classifier: Development Status :: 4 - Beta
10
+ Classifier: Environment :: Console
11
+ Classifier: Intended Audience :: Developers
12
+ Classifier: License :: OSI Approved :: MIT License
13
+ Classifier: Programming Language :: Python :: 3 :: Only
14
+ Classifier: Topic :: Software Development :: Libraries
15
+ Classifier: Topic :: System :: Software Distribution
16
+ Classifier: Typing :: Typed
17
+ Requires-Dist: typer>=0.12.0 ; extra == 'typer'
18
+ Requires-Python: >=3.11
19
+ Project-URL: Repository, https://github.com/datapointchris/pyselfupdate
20
+ Project-URL: Issues, https://github.com/datapointchris/pyselfupdate/issues
21
+ Project-URL: Changelog, https://github.com/datapointchris/pyselfupdate/blob/main/CHANGELOG.md
22
+ Provides-Extra: typer
23
+ Description-Content-Type: text/markdown
24
+
25
+ # pyselfupdate
26
+
27
+ Self-update and update notification for Python CLIs installed with `uv tool`.
28
+
29
+ Two things, used independently: tell the user once a day that a newer release
30
+ exists, and install it when they ask. No runtime dependencies.
31
+
32
+ ```python
33
+ from pyselfupdate import Config, notify, update
34
+
35
+ config = Config(tool='mytool', owner='you')
36
+
37
+ notify(config) # once a day, one line if behind. Never raises.
38
+ update(config) # install the latest release. Raises on failure.
39
+ ```
40
+
41
+ ## Install
42
+
43
+ ```bash
44
+ uv add pyselfupdate
45
+
46
+ # with the ready-made typer command
47
+ uv add "pyselfupdate[typer]"
48
+ ```
49
+
50
+ Requires Python 3.11+.
51
+
52
+ ## Why
53
+
54
+ A CLI distributed with `uv tool install` has no way to tell its user a newer
55
+ version exists, so it silently drifts. The usual fix drags an HTTP client, a
56
+ TOML parser and a version library into a tool that had none of them.
57
+
58
+ This package has zero runtime dependencies — `urllib` for the network,
59
+ `tomllib` for uv's receipt, and its own semver implementation — and CI enforces
60
+ that by importing every module into a virtual environment containing nothing
61
+ else.
62
+
63
+ ## notify
64
+
65
+ Put it in your CLI's root callback and ignore the result:
66
+
67
+ ```python
68
+ import typer
69
+ from pyselfupdate import Config, notify
70
+
71
+ app = typer.Typer()
72
+ CONFIG = Config(tool='mytool', owner='you')
73
+
74
+
75
+ @app.callback()
76
+ def main() -> None:
77
+ notify(CONFIG)
78
+ ```
79
+
80
+ Once per 24 hours, if a newer release exists, one line goes to stderr **after**
81
+ your command's own output:
82
+
83
+ ```text
84
+ mytool v1.4.0 available (running v1.3.2) — run `mytool update`
85
+ ```
86
+
87
+ It never raises, never installs anything, and never prints an error. A failed
88
+ check is recorded in the state file and swallowed, because an update notice
89
+ must not be able to break the command the user actually typed.
90
+
91
+ Nothing is printed when any of these hold:
92
+
93
+ | Condition | Why |
94
+ | --- | --- |
95
+ | `NO_AUTO_UPDATE` or `MYTOOL_NO_AUTO_UPDATE` is set | Opted out |
96
+ | `CI`, `BUILD_NUMBER`, `RUN_ID`, `GITHUB_ACTIONS`, `CODESPACES` | Not a human |
97
+ | stdout or stderr is not a terminal | `mytool list > out 2>&1` must stay clean |
98
+ | Installed from a local path, an editable checkout, or a branch | Nothing to compare against |
99
+ | Checked within the interval | One request per day, not per invocation |
100
+
101
+ Presence-only, any value: `NO_AUTO_UPDATE=0` disables it, the same way
102
+ [`NO_COLOR`](https://no-color.org) works. Set the interval separately with
103
+ `AUTO_UPDATE_INTERVAL=6h` or `MYTOOL_AUTO_UPDATE_INTERVAL=30m`.
104
+
105
+ ## update
106
+
107
+ ```python
108
+ from pyselfupdate import Config, check, update
109
+
110
+ result = check(config) # no filesystem, no install
111
+ if result.update_available:
112
+ print(result.current, '->', result.latest)
113
+
114
+ result = update(config) # installs, raises on failure
115
+ ```
116
+
117
+ Or take the whole command:
118
+
119
+ ```python
120
+ from pyselfupdate.typercmd import add_update_command
121
+
122
+ add_update_command(app, CONFIG) # gives you `mytool update [--check]`
123
+ ```
124
+
125
+ `update` runs `uv tool install --force`, which **rebuilds the virtual
126
+ environment the running interpreter lives in**. Unlike replacing a Unix binary
127
+ — where the process holds an inode and is untouched — this pulls modules out
128
+ from under a live process, so anything imported afterwards may fail in ways
129
+ that are hard to read. Make it the last thing your process does, or use
130
+ `update_and_reexec` to replace the process with the new version immediately.
131
+
132
+ ## What will not be updated
133
+
134
+ Read from uv's own receipt, written at install time, rather than guessed at
135
+ runtime:
136
+
137
+ | Receipt | Result |
138
+ | --- | --- |
139
+ | `git = "...git?rev=v1.2.3"` | Updatable |
140
+ | `name = "mytool"` (from an index) | Updatable |
141
+ | `git = "...git"` with no `rev` | Refused — tracks a branch, so its version says nothing about how far behind it is |
142
+ | `directory` / `path` / `editable` | Refused — reinstalling would discard a working copy |
143
+
144
+ A tool that cannot be identified at all is treated as local and left alone.
145
+
146
+ ## Configuration
147
+
148
+ ```python
149
+ Config(
150
+ tool='mytool', # required: uv tool name, state dir, env prefix
151
+ owner='you', # GitHub owner
152
+ repo='mytool', # defaults to tool
153
+ package='mytool', # distribution name, defaults to tool
154
+ version='1.2.3', # defaults to the installed distribution's metadata
155
+ token='', # defaults to $GITHUB_TOKEN, then $GH_TOKEN
156
+ tag_prefix='', # e.g. 'cli/' for tags like cli/v1.2.3
157
+ allow_prerelease=False,
158
+ source=None, # a custom Source; anything with latest_release()
159
+ )
160
+ ```
161
+
162
+ Without a token, GitHub allows 60 API requests per hour per IP and rejects
163
+ private repositories outright. One check per day per tool is far inside that; a
164
+ shared egress address is not.
165
+
166
+ ## State
167
+
168
+ `${XDG_STATE_HOME:-~/.local/state}/<tool>/autoupdate.json`, written atomically:
169
+
170
+ ```json
171
+ {
172
+ "schema": 1,
173
+ "tool": "mytool",
174
+ "checked_at": "2026-07-26T15:07:15Z",
175
+ "checked_at_epoch": 1785078435,
176
+ "current_version": "v1.3.2",
177
+ "latest_version": "v1.4.0",
178
+ "last_error": "",
179
+ "skip": ""
180
+ }
181
+ ```
182
+
183
+ State, not config and not cache: it persists across runs, it is not authored by
184
+ the user, and deleting it changes behaviour rather than merely costing a
185
+ recompute. That is `XDG_STATE_HOME` by the Base Directory specification, and it
186
+ is where `gh` puts the same thing.
187
+
188
+ The timestamp is written **before** the network call. `gh` stamps only on
189
+ success, so a rate-limited or offline user re-hits the API on every invocation
190
+ until the window resets; an interval exists to bound the request rate, and only
191
+ this ordering actually does that.
192
+
193
+ ## Siblings
194
+
195
+ The same design in two other languages, sharing the state schema and the
196
+ environment-variable contract:
197
+
198
+ - [goselfupdate](https://github.com/datapointchris/goselfupdate) — replaces a Go binary
199
+ - [bashselfupdate](https://github.com/datapointchris/bashselfupdate) — moves a git checkout to its newest tag
200
+
201
+ ## Licence
202
+
203
+ MIT
@@ -0,0 +1,15 @@
1
+ pyselfupdate/__init__.py,sha256=7jtKyTIfBQTcBzqgZV8NEuxR4gOR3YqmCjlJJVw5SEw,2308
2
+ pyselfupdate/config.py,sha256=U4mdTYNUfTY2DzoMVtHd424GBT7d-U0IcBcWU4UBFm8,3266
3
+ pyselfupdate/errors.py,sha256=F3C8zIK7DSqRLwj2nF-H1s6EeyfWuAamStDKFHMY7xI,1194
4
+ pyselfupdate/github.py,sha256=oxsirX6d-OXm5WFo8o5jbYVXbSteB-JmPfYGxDEiYmA,7672
5
+ pyselfupdate/install.py,sha256=PUI6I0T8yzmzNYxkmGOsLTeTEomXgeD5rdi4kKHwtXE,6337
6
+ pyselfupdate/notifier.py,sha256=9QEwRaH_6OoXQJPzgs-Alq8itbFLzwQx3rlQ7WM7cdM,8625
7
+ pyselfupdate/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
8
+ pyselfupdate/source.py,sha256=GlzCNNs6HuEV0JvwExHzuYm94dBNKMIFcdgJDBb7VRU,1501
9
+ pyselfupdate/state.py,sha256=yyzwcTe-c66D8kqYhILL9L_d0D29T15o8D74id1-qNM,3425
10
+ pyselfupdate/typercmd.py,sha256=G3GrFbcFBI0sjpZn-Yy-V49arUxqoq9Gb_2DEseq00U,3254
11
+ pyselfupdate/updater.py,sha256=sEYtM7O9CvnfFXe3GmY-MdjYndBgtKtjSTHwJ4dcU4U,4693
12
+ pyselfupdate/version.py,sha256=hA3G4ZsFMYsngjcrADc3ZWifPgwWfxTS-mq-xoeE9l4,5147
13
+ pyselfupdate-0.1.0.dist-info/WHEEL,sha256=l3MmIxu8qaet7ng2J9fFoJnYGj8IREj7jXTbgsuzmy4,81
14
+ pyselfupdate-0.1.0.dist-info/METADATA,sha256=bsiADiR9vgLM2PKuHFRpYw_elW0xbFGLqutL3FS_37I,6776
15
+ pyselfupdate-0.1.0.dist-info/RECORD,,
@@ -0,0 +1,4 @@
1
+ Wheel-Version: 1.0
2
+ Generator: uv 0.11.32
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any