Skip to content

Commit 94bcb44

Browse files
authored
fix(cli): PEP 440 release ordering for package-update; honour uv workspace excludes (#766, #767) (#794)
* fix(cli): PEP 440 release ordering for package-update; honour uv workspace excludes (#766, #767) Claude-Session: https://claude.ai/code/session_01M9neheZZEe3sVpDi2S3zT4 * fix: address code review findings (round 1, pass 1) Skip unparseable version spellings instead of aborting package-update. Claude-Session: https://claude.ai/code/session_01M9neheZZEe3sVpDi2S3zT4 * fix: address code review findings (round 1, pass 1, maintainability) Claude-Session: https://claude.ai/code/session_01M9neheZZEe3sVpDi2S3zT4 * fix: address code review findings (round 1, pass 2) Treat invalid specifier bounds as skips; keep a ~= floor below a pre-release latest. Claude-Session: https://claude.ai/code/session_01M9neheZZEe3sVpDi2S3zT4 * fix: address code review findings (round 1, pass 3) PEP 440 wildcard matching via packaging (epochs, dev/post); drop the dead numeric version_key. Claude-Session: https://claude.ai/code/session_01M9neheZZEe3sVpDi2S3zT4 * test(cli): update docstring after version_key removal Claude-Session: https://claude.ai/code/session_01M9neheZZEe3sVpDi2S3zT4
1 parent 6e2d871 commit 94bcb44

14 files changed

Lines changed: 244 additions & 58 deletions

‎CHANGELOG.md‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -31,6 +31,10 @@ All notable changes to this project are documented in this file. The format is b
3131
`account` or whose `azp` is another client (only `oidc` pins both).
3232

3333
### Fixed
34+
- `smpy package-update` selects the latest release in PEP 440 order and promotes
35+
RC pins to final releases without downgrading existing pins (#766).
36+
- `smpy package-update` respects exact and glob uv workspace exclusions, leaving
37+
excluded project manifests unchanged (#767). No migration.
3438
- **Behaviour change** (`auth`, `oidc`): a generic-OIDC browser session created
3539
before #750 (no authority marker) is adopted only when the issuer recorded in
3640
its `oidc_identity` matches the discovered issuer (#764). A session from a

‎docs/guide/installation.md‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -144,6 +144,7 @@ smpy package-update
144144
Pass `--dry-run` first to preview the diff. The command scans the root and uv
145145
workspace members: project dependencies, every optional-dependency extra and
146146
every dependency group, including workspace roots with only dev groups.
147+
Projects matching `[tool.uv.workspace].exclude` (exact paths or globs) are skipped.
147148
Include-group objects and workspace/local uv sources are left alone; source
148149
names are normalized and member sources override root sources.
149150

@@ -156,6 +157,9 @@ version spellings, unsupported ranges and workspace/file/git/alias references
156157
are reported as skips, and so is every npm pin when the run leaves the Python
157158
`simple_module_core` pin alone (an upper bound or a local source), so npm never
158159
runs ahead of Python. `--include-pre` also applies to core target selection.
160+
Python releases use PEP 440 ordering: RC numbers advance numerically, and a final
161+
release outranks its RCs, so stable-only updates can promote an RC pin to final.
162+
Existing pins never move backwards.
159163

160164
All manifests are parsed and changes planned before any writes. Dry runs write
161165
nothing; JSON indentation and trailing-newline style are preserved. Writes to

‎framework/cli/README.md‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -12,7 +12,7 @@ pipx install simple_module_cli
1212
uvx --from simple_module_cli smpy new my-app
1313
```
1414

15-
The package depends only on `typer` and `tomlkit` — installing it does **not** pull in FastAPI, SQLModel, or any other framework runtime.
15+
The package depends only on `typer`, `tomlkit` and `packaging` — installing it does **not** pull in FastAPI, SQLModel, or any other framework runtime.
1616

1717
## Usage
1818

‎framework/cli/pyproject.toml‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -20,6 +20,7 @@ classifiers = [
2020
"Typing :: Typed",
2121
]
2222
dependencies = [
23+
"packaging>=23.0,<27",
2324
"typer>=0.12,<0.28",
2425
"tomlkit>=0.13,<0.16",
2526
]

‎framework/cli/simple_module_cli/git_versions.py‎

Lines changed: 15 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -5,9 +5,16 @@
55
import re
66
from collections.abc import Iterable
77

8-
from simple_module_cli.requirements import _compatible_band, _matches_wildcard
8+
from packaging.version import InvalidVersion
99

10-
# --- version helpers (no `packaging` dep — CLI depends on typer + tomlkit only) ---
10+
from simple_module_cli.requirements import _compare as _cmp
11+
from simple_module_cli.requirements import (
12+
_compatible_band,
13+
_matches_wildcard,
14+
is_valid_version,
15+
)
16+
17+
# --- version helpers ---
1118

1219

1320
def version_tuple(v: str) -> tuple[int, ...]:
@@ -23,17 +30,6 @@ def version_tuple(v: str) -> tuple[int, ...]:
2330
return tuple(parts)
2431

2532

26-
def _cmp(a: str, b: str) -> int:
27-
ta, tb = version_tuple(a), version_tuple(b)
28-
width = max(len(ta), len(tb))
29-
ta += (0,) * (width - len(ta))
30-
tb += (0,) * (width - len(tb))
31-
if ta != tb:
32-
return (ta > tb) - (ta < tb)
33-
pa, pb = _prerelease_key(a), _prerelease_key(b)
34-
return (pa > pb) - (pa < pb)
35-
36-
3733
def _prerelease_key(version: str) -> tuple[int, int]:
3834
# shortcut: handles Python a/b/rc suffixes; use a full parser for other version schemes.
3935
match = re.search(r"(alpha|beta|a|b|rc)(\d*)$", version, re.IGNORECASE)
@@ -62,7 +58,10 @@ def satisfies(version: str, constraint: str) -> bool:
6258
break
6359
if op == "<" and _excluded_prerelease(version, bound):
6460
return False
65-
c = _cmp(version, bound)
61+
try:
62+
c = _cmp(version, bound)
63+
except InvalidVersion:
64+
return False
6665
if op == "~=":
6766
band = _compatible_band(bound)
6867
if c < 0 or band is None or not _matches_wildcard(version, band):
@@ -106,6 +105,8 @@ def pick_latest_tag(tags: Iterable[str], constraint: str | None) -> str | None:
106105
if not tag.startswith("v") or len(tag) < 2 or not tag[1].isdigit():
107106
continue
108107
ver = tag[1:]
108+
if not is_valid_version(ver):
109+
continue
109110
if constraint and not satisfies(ver, constraint):
110111
continue
111112
if best is None or _cmp(ver, best[1:]) > 0:

‎framework/cli/simple_module_cli/package_update_deps.py‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,7 @@
1111
from tomlkit.items import Array
1212

1313
from simple_module_cli.requirements import parse_requirement, rewrite_requirement
14+
from simple_module_cli.uv_workspace import is_workspace_member
1415

1516

1617
@dataclass(frozen=True)
@@ -72,7 +73,7 @@ def workspace_member_dirs(root_pyproject: Path, doc: tomlkit.TOMLDocument) -> li
7273
out: list[Path] = []
7374
for pattern in members:
7475
for match in sorted(base.glob(str(pattern))):
75-
if (match / "pyproject.toml").is_file():
76+
if (match / "pyproject.toml").is_file() and is_workspace_member(base, match):
7677
out.append(match / "pyproject.toml")
7778
return list(dict.fromkeys(p.resolve() for p in out))
7879

‎framework/cli/simple_module_cli/pypi.py‎

Lines changed: 10 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -14,7 +14,9 @@
1414
from collections.abc import Callable
1515
from typing import Any
1616

17-
from simple_module_cli.requirements import version_key
17+
from packaging.version import Version
18+
19+
from simple_module_cli.requirements import is_valid_version
1820

1921
__all__ = ["PYPI_URL", "Fetcher", "default_fetcher", "fetch_latest"]
2022

@@ -23,8 +25,8 @@
2325
PYPI_URL = "https://pypi.org/pypi/{name}/json"
2426

2527
# PEP 440 release segments contain only digits + dots; any letter signals
26-
# a pre/post/dev release (a, b, rc, post, dev). Coarser than packaging.version
27-
# but `packaging` isn't a CLI dep (see test_no_framework_deps.py).
28+
# a pre/post/dev release (a, b, rc, post, dev). Deliberately stricter than
29+
# ``Version.is_prerelease``, which would let ``.post`` releases through as stable.
2830
_PRE_RELEASE_RE = re.compile(r"[a-zA-Z]")
2931

3032

@@ -43,13 +45,16 @@ def fetch_latest(name: str, *, include_pre: bool, fetcher: Fetcher) -> str | Non
4345
continue
4446
if not include_pre and _PRE_RELEASE_RE.search(version):
4547
continue
48+
if not is_valid_version(version):
49+
continue
4650
candidates.append(version)
4751
if candidates:
48-
return max(candidates, key=version_key)
52+
return max(candidates, key=Version)
4953
if releases:
5054
return None
5155
info = data.get("info") or {}
52-
return info.get("version")
56+
fallback = info.get("version")
57+
return fallback if is_valid_version(fallback) else None
5358

5459

5560
def default_fetcher(url: str) -> dict[str, Any]:

‎framework/cli/simple_module_cli/requirements.py‎

Lines changed: 50 additions & 30 deletions
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,9 @@
1616
import re
1717
from dataclasses import dataclass
1818

19+
from packaging.specifiers import InvalidSpecifier, Specifier
20+
from packaging.version import InvalidVersion, Version
21+
1922
__all__ = ["ParsedRequirement", "RewriteResult", "parse_requirement", "rewrite_requirement"]
2023

2124
# Longest-first: ``===`` must win over ``==``, and ``>=`` over ``>``.
@@ -30,8 +33,8 @@
3033

3134
#: Suffix marking a PEP 440 wildcard (``==1.4.*``, ``!=1.0.*``). These match on
3235
#: a *prefix* of the release segments, so they must never go through the
33-
#: numeric comparison — ``version_key`` maps ``*`` to 0, which would read
34-
#: ``1.0.*`` as ``1.0.0`` and quietly answer the wrong question.
36+
#: numeric comparison — a numeric compare would read ``1.0.*`` as ``1.0.0`` and
37+
#: quietly answer the wrong question.
3538
_WILDCARD = ".*"
3639

3740

@@ -59,29 +62,42 @@ class RewriteResult:
5962
reason: str | None = None
6063

6164

62-
def version_key(version: str) -> tuple[int, ...]:
63-
"""Coarse PEP 440 release-segment ordering.
64-
65-
``packaging`` isn't a CLI dependency (see ``test_no_framework_deps.py``),
66-
so this compares the numeric release segments only. Good enough to answer
67-
"does the latest release trip this upper bound", which is all it's for.
68-
"""
69-
parts: list[int] = []
70-
for part in version.split("."):
71-
digits = re.match(r"\d+", part)
72-
parts.append(int(digits.group()) if digits else 0)
73-
return tuple(parts)
65+
def is_valid_version(version: str | None) -> bool:
66+
"""Is ``version`` a string PEP 440 can order? ``None`` and legacy spellings are not."""
67+
try:
68+
Version(version) # ty: ignore[invalid-argument-type] # None -> TypeError, handled
69+
except (InvalidVersion, TypeError):
70+
return False
71+
return True
7472

7573

7674
def _compare(left: str, right: str) -> int:
77-
"""Three-way compare two versions on their release segments, zero-padded."""
78-
a, b = version_key(left), version_key(right)
79-
width = max(len(a), len(b))
80-
a += (0,) * (width - len(a))
81-
b += (0,) * (width - len(b))
75+
"""Three-way PEP 440 comparison, including pre/dev/post releases."""
76+
a, b = Version(left), Version(right)
8277
return (a > b) - (a < b)
8378

8479

80+
def _unparseable(parsed: ParsedRequirement, latest: str) -> str | None:
81+
"""The first version that is not valid PEP 440, or ``None``.
82+
83+
Legacy spellings (``==1.x``, ``===local-build``) can't be ordered, so the
84+
requirement is reported as a skip instead of aborting the whole run.
85+
"""
86+
for candidate in (
87+
latest,
88+
*(v[: -len(_WILDCARD)] if v.endswith(_WILDCARD) else v for _, v in parsed.clauses),
89+
):
90+
if not is_valid_version(candidate):
91+
return candidate
92+
for op, version in parsed.clauses:
93+
if op in ("<", "<=", "!=") and not version.endswith(_WILDCARD):
94+
try: # a valid Version can still be an invalid bound, e.g. ``<1.0+local``
95+
Specifier(f"{op}{version}")
96+
except InvalidSpecifier:
97+
return version
98+
return None
99+
100+
85101
def parse_requirement(spec: str) -> ParsedRequirement | None:
86102
"""Split a PEP 508 requirement string, or ``None`` if the name is unusable."""
87103
base, sep, marker = spec.partition(";")
@@ -117,9 +133,10 @@ def _render(parsed: ParsedRequirement, clauses: tuple[tuple[str, str], ...]) ->
117133

118134
def _matches_wildcard(version: str, pattern: str) -> bool:
119135
"""Does ``version`` fall under a PEP 440 wildcard like ``1.4.*``?"""
120-
prefix = version_key(pattern[: -len(_WILDCARD)])
121-
release = version_key(version)
122-
return len(release) >= len(prefix) and release[: len(prefix)] == prefix
136+
try:
137+
return Specifier(f"=={pattern}").contains(version, prereleases=True)
138+
except InvalidSpecifier:
139+
return False
123140

124141

125142
def _compatible_band(version: str) -> str | None:
@@ -151,13 +168,8 @@ def _allows(op: str, version: str, latest: str) -> bool:
151168
if op == "~=":
152169
band = _compatible_band(version)
153170
return band is not None and _matches_wildcard(latest, band)
154-
cmp = _compare(latest, version)
155-
if op == "<":
156-
return cmp < 0
157-
if op == "<=":
158-
return cmp <= 0
159-
if op == "!=":
160-
return cmp != 0
171+
if op in ("<", "<=", "!="):
172+
return Specifier(f"{op}{version}").contains(latest, prereleases=True)
161173
# ``>`` — already satisfied by anything newer than the pin.
162174
return True
163175

@@ -193,7 +205,11 @@ def _bump(op: str, version: str, latest: str) -> str:
193205
if len(parts) < segments:
194206
return version
195207
candidate = ".".join(parts[:segments])
196-
return candidate if _compare(candidate, version) > 0 else version
208+
# A pre-release ``latest`` truncates to a release above itself
209+
# (``1.5.0rc1`` -> ``1.5``), which nothing published satisfies yet.
210+
if _compare(candidate, version) > 0 and _compare(candidate, latest) <= 0:
211+
return candidate
212+
return version
197213
if op in _FLOOR_OPS:
198214
return latest if _compare(latest, version) > 0 else version
199215
return version
@@ -217,6 +233,10 @@ def rewrite_requirement(spec: str, latest: str, *, loosen: bool = False) -> Rewr
217233
new = f"{parsed.name}{parsed.extras}>={latest}{parsed.marker}"
218234
return RewriteResult(None) if new == spec.strip() else RewriteResult(new)
219235

236+
bad = _unparseable(parsed, latest)
237+
if bad is not None:
238+
return RewriteResult(None, reason=f"unsupported version spelling {bad!r}")
239+
220240
blocker = _excluded_by(parsed, latest)
221241
if blocker is not None:
222242
return RewriteResult(None, reason=f"{latest} excluded by {blocker}")

‎framework/cli/tests/test_cli_add_spec_parse.py‎

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -122,3 +122,14 @@ def test_prerelease_does_not_satisfy_final_floor(prerelease: str) -> None:
122122
)
123123
def test_pick_latest_tag_orders_prereleases(tags: list[str], expected: str) -> None:
124124
assert pick_latest_tag(tags, None) == expected
125+
126+
127+
@pytest.mark.parametrize("constraint", [None, ">=1.0"])
128+
def test_pick_latest_tag_skips_invalid_versions(constraint: str | None) -> None:
129+
assert pick_latest_tag(["v999.invalid", "v1.0"], constraint) == "v1.0"
130+
131+
132+
def test_satisfies_rejects_unparseable_bound() -> None:
133+
from simple_module_cli.git_versions import satisfies
134+
135+
assert satisfies("1.0", ">=1.x") is False

‎framework/cli/tests/test_cli_package_update_pins.py‎

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -115,10 +115,10 @@ def test_extras_and_markers_survive_the_rewrite(tmp_path: Path, fake_pypi, write
115115

116116

117117
class TestWildcardsAndImplicitCeilings:
118-
"""Wildcards and `~=` carry ceilings `version_key` can't see.
118+
"""Wildcards and `~=` carry ceilings a plain version comparison can't see.
119119
120-
`version_key` maps `*` to 0, so `!=1.0.*` compared numerically reads as
121-
`!=1.0.0` and never fires. That produced `>=1.0.5,!=1.0.*` — a specifier
120+
The old numeric key mapped `*` to 0, so `!=1.0.*` compared numerically read as
121+
`!=1.0.0` and never fired. That produced `>=1.0.5,!=1.0.*` — a specifier
122122
nothing can satisfy, which fails the `uv sync` the tool tells you to run.
123123
"""
124124

0 commit comments

Comments
 (0)