Skip to content

Commit 1f527ae

Browse files
authored
Properly handle -dev suffix on tags and ranges. (#436)
Also formalises our handling of tags so that they are interpreted consistently throughout. This may cause some scenarios to change behaviour slightly, but unlikely to affect any python.org releases, which are likely the only ones to worry about right now. Fixes #428
1 parent 8ac72d5 commit 1f527ae

15 files changed

Lines changed: 989 additions & 197 deletions

‎ruff.toml‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@
44
# check for actual incorrect code.
55
ignore = [
66
"B006",
7+
"B008",
78
"BLE001",
89
"C401",
910
"C408",
@@ -12,6 +13,7 @@ ignore = [
1213
"I001",
1314
"PIE808",
1415
"PLC",
16+
"PLR0206",
1517
"PLR1730",
1618
"RUF012",
1719
"RUF015",

‎scripts/repartition-index.py‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -75,9 +75,9 @@ def _number_sortkey(self, k):
7575
return tuple(bits)
7676

7777
def _sort_key(self, v):
78-
from manage.tagutils import _CompanyKey, _DescendingVersion
78+
from manage.tagutils import _CompanyKey, DescendingVersion
7979
return (
80-
_DescendingVersion(v["sort-version"]),
80+
DescendingVersion(v["sort-version"]),
8181
_CompanyKey(v["company"]),
8282
self._number_sortkey(v["id"]),
8383
)

‎src/manage/indexutils.py‎

Lines changed: 30 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -204,8 +204,8 @@ def __init__(self, source_url, d):
204204
raise InvalidFeedError(feed_url=source_url) from ex
205205
self.source_url = source_url
206206
self.next_url = validated.get("next")
207-
versions = [_patch(source_url, v) for v in validated["versions"]]
208-
self.versions = sorted(versions, key=lambda v: v["sort-version"], reverse=True)
207+
# Feed order is retained intentionally for package selection.
208+
self.versions = [_patch(source_url, v) for v in validated["versions"]]
209209

210210
def __repr__(self):
211211
return "<Index({!r}, next={!r}, versions=[...{} entries])>".format(
@@ -214,7 +214,7 @@ def __repr__(self):
214214
len(self.versions),
215215
)
216216

217-
def find_all(self, tags, *, seen_ids=None, loose_company=False, with_prerelease=False):
217+
def find_all(self, tags, *, seen_ids=None, with_prerelease=False):
218218
filters = []
219219
for tag in tags:
220220
try:
@@ -226,20 +226,38 @@ def find_all(self, tags, *, seen_ids=None, loose_company=False, with_prerelease=
226226
if i["id"].casefold() in seen_ids:
227227
continue
228228
if with_prerelease or not i["sort-version"].is_prerelease:
229-
if not filters or install_matches_any(i, filters, loose_company=loose_company):
229+
if not filters or install_matches_any(i, filters):
230230
if seen_ids is not None:
231231
seen_ids.add(i["id"].casefold())
232232
yield i
233233

234-
def find_to_install(self, tag, *, loose_company=False, prefer_prerelease=False):
235-
tag_list = [tag] if tag else []
234+
def find_to_install(self, tag, *, prefer_prerelease=None):
235+
tag_list = [tag_or_range(tag)] if tag else []
236236
LOGGER.debug("Finding %s to install", tag_list)
237-
for i in self.find_all(tag_list, loose_company=loose_company, with_prerelease=prefer_prerelease):
238-
return {**i, "source": self.source_url}
239-
if not loose_company:
240-
return self.find_to_install(tag, loose_company=True, prefer_prerelease=prefer_prerelease)
241-
if not prefer_prerelease:
242-
for i in self.find_all(tag_list, loose_company=loose_company, with_prerelease=True):
237+
if prefer_prerelease is None:
238+
prefer_prerelease = any(t.prefers_prerelease for t in tag_list)
239+
# We prioritise a full company name match (find_all only filters using
240+
# the prefix) and stable releases (unless prefer_prerelease is True).
241+
# The feed order is authoritative though, so we store our fallback
242+
# options
243+
fallback = []
244+
for i in self.find_all(tag_list, with_prerelease=True):
245+
if not prefer_prerelease and i["sort-version"].is_prerelease:
246+
# It's a matching prerelease, but we prefer stable releases
247+
fallback.append(i)
248+
elif any(not t.matches_company_exactly(i["company"]) for t in tag_list):
249+
# It's a prefix match, not a full match, so save it for later
250+
fallback.append(i)
251+
else:
252+
# This is a perfect match, so let's return immediately
243253
return {**i, "source": self.source_url}
254+
if not prefer_prerelease:
255+
# Need to use a fallback, so let's first look for a company prefix match
256+
for i in fallback:
257+
if not i["sort-version"].is_prerelease:
258+
return {**i, "source": self.source_url}
259+
# Return the first fallback (if any)
260+
for i in fallback:
261+
return {**i, "source": self.source_url}
244262
LOGGER.debug("No install found for %s", tag_list)
245263
raise LookupError(tag)

‎src/manage/installs.py‎

Lines changed: 44 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,7 @@
33
from .exceptions import NoInstallFoundError, NoInstallsError
44
from .logging import DEBUG, LOGGER
55
from .pathutils import Path
6-
from .tagutils import CompanyTag, tag_or_range, companies_match, split_platform
6+
from .tagutils import CompanyTag, tag_or_range, companies_match, split_platform, DescendingVersion
77
from .verutils import Version
88

99

@@ -14,6 +14,16 @@ def _make_sort_key(install):
1414
0 if not Version(install["sort-version"]).is_prerelease else 1,
1515
# Order by descending tags
1616
CompanyTag(install.get("company"), install.get("tag")),
17+
# Disambiguate by sort version where necessary
18+
DescendingVersion(install["sort-version"]),
19+
)
20+
21+
22+
def make_sort_key_ignore_pre(install):
23+
# Alternate sort key for "-dev" that treats prerelease as equal to release
24+
return (
25+
CompanyTag(install.get("company"), install.get("tag")),
26+
DescendingVersion(install["sort-version"]),
1727
)
1828

1929

@@ -186,6 +196,8 @@ def get_install_alias_names(aliases, friendly=True, windowed=True, default_platf
186196
aliases = [a for a in aliases if not a.get("windowed")]
187197
if not friendly:
188198
return sorted(a["name"] for a in aliases)
199+
if default_platform:
200+
default_platform = default_platform.casefold()
189201

190202
seen = {}
191203
has_w = {}
@@ -217,11 +229,11 @@ def _patch_install_to_run(i, run_for):
217229

218230

219231
def get_matching_install_tags(
220-
installs,
221-
tag,
222-
windowed=None,
223-
default_platform=None,
224-
single_tag=False,
232+
installs, # previously loaded from disk
233+
tag, # provided by user
234+
windowed=None, # inferred from context (e.g. launched via pyw.exe)
235+
default_platform=None, # from config
236+
single_tag=False, # "get the single best result for this tag"
225237
):
226238
exact_matches = []
227239
core_matches = []
@@ -258,8 +270,6 @@ def get_matching_install_tags(
258270
else:
259271
matches.append((i, t))
260272
matched_any = True
261-
if single_tag and matched_any:
262-
break
263273
if LOGGER.would_log_to_console(DEBUG):
264274
# Don't bother listing all installs unless the user has asked
265275
# for console output.
@@ -298,19 +308,30 @@ def get_matching_install_tags(
298308
# If none or only prereleases, keep them all
299309
if default_platform:
300310
default_platform = default_platform.casefold()
311+
# Remember whether all source versions were prereleases, so we don't
312+
# reset our results if all post-filter versions are prereleases.
301313
all_pre = all(Version(i["sort-version"]).is_prerelease for i, t in best)
302314
best2 = best
303315
best = [(i, t) for i, t in best
304316
if i.get("__any-platform")
305317
or t["tag"].casefold().endswith(default_platform)]
306318
LOGGER.debug("default_platform '%s' matched %s %s", default_platform,
307319
len(best), "install" if len(best) == 1 else "installs")
308-
if (
309-
not best or
310-
(not all_pre and all(Version(i["sort-version"]).is_prerelease for i, t in best))
311-
):
312-
LOGGER.debug("Reusing unfiltered list")
320+
if not best:
321+
LOGGER.debug("Reusing unfiltered list because all candidates were "
322+
"excluded")
313323
best = best2
324+
elif (not all_pre
325+
and (not tag or not tag.prefers_prerelease)
326+
and all(Version(i["sort-version"]).is_prerelease for i, t in best)):
327+
LOGGER.debug("Reusing unfiltered list because all candidates were "
328+
"prereleases")
329+
best = best2
330+
331+
if best and single_tag:
332+
if tag and tag.prefers_prerelease:
333+
best = sorted(best, key=lambda i_t: make_sort_key_ignore_pre(i_t[0]))
334+
return best[:1]
314335

315336
return best
316337

@@ -323,19 +344,22 @@ def get_install_to_run(
323344
windowed=False,
324345
virtual_env=None,
325346
default_platform=None,
347+
*,
348+
installs=None,
326349
):
327350
"""Returns the first install matching 'tag'.
328351
"""
329-
installs = get_installs(
330-
install_dir,
331-
include_unmanaged=include_unmanaged,
332-
virtual_env=virtual_env,
333-
)
352+
if installs is None:
353+
installs = get_installs(
354+
install_dir,
355+
include_unmanaged=include_unmanaged,
356+
virtual_env=virtual_env,
357+
)
334358

335359
if not installs:
336360
raise NoInstallsError
337361

338-
if not tag or tag.casefold() == "default".casefold():
362+
if not tag or (isinstance(tag, str) and tag.casefold() == "default".casefold()):
339363
# We know we want default, so try filtering first. If any are explicitly
340364
# tagged (e.g. active venv), they will be the only candidates.
341365
# Otherwise, we'll do a regular search as if 'default_tag' was provided.
@@ -355,6 +379,7 @@ def get_install_to_run(
355379
tag,
356380
windowed=windowed,
357381
default_platform=default_platform,
382+
single_tag=True,
358383
)
359384

360385
if best:

‎src/manage/list_command.py‎

Lines changed: 47 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
import json
22

33
from . import logging
4-
from .exceptions import ArgumentError
4+
from .exceptions import ArgumentError, NoInstallFoundError, NoInstallsError
55

66
LOGGER = logging.LOGGER
77

@@ -22,8 +22,9 @@ def _format_alias(cmd, i, seen):
2222
def _format_tag_with_co(cmd, i):
2323
t = i["tag"]
2424
# Show the default platform as optional when configured.
25-
if cmd and cmd.default_platform and t.endswith(cmd.default_platform):
26-
t = t.removesuffix(cmd.default_platform) + f"[{cmd.default_platform}]"
25+
if cmd and cmd.default_platform and t.casefold().endswith(cmd.default_platform.casefold()):
26+
n = len(cmd.default_platform)
27+
t = f"{t[:-n]}[{t[-n:]}]"
2728
if i["company"].casefold() in ("PythonCore".casefold(), "---", ""):
2829
return t
2930
return rf"{i['company']}\{t}"
@@ -331,6 +332,9 @@ def execute(cmd):
331332
plat = plat or cmd.default_platform
332333

333334
if cmd.source:
335+
# When listing online packages, we filter by install-for tags to better
336+
# match 'py install <tag>' behaviour
337+
334338
from .indexutils import Index
335339
from .urlutils import IndexDownloader
336340
installs = []
@@ -354,36 +358,61 @@ def execute(cmd):
354358
if first_exc:
355359
raise SystemExit(1) from first_exc
356360
if cmd.one:
357-
# Pick the first non-prerelease that'll install for our platform
358361
best = [i for i in installs
359-
if any(t.endswith(plat) for t in i.get("install-for", []))]
360-
for i in best:
361-
if not i["sort-version"].is_prerelease:
362-
installs = [i]
363-
break
364-
else:
362+
if any(t.casefold().endswith(plat.casefold()) for t in i.get("install-for", []))]
363+
if any(t.prefers_prerelease for t in tags):
364+
# Prefer the first platform match in feed order.
365365
installs = best[:1] or installs
366+
else:
367+
# Pick the first non-prerelease that'll install for our platform
368+
for i in best:
369+
if not i["sort-version"].is_prerelease:
370+
installs = [i]
371+
break
372+
else:
373+
installs = best[:1] or installs
366374
elif cmd.install_dir:
375+
# When listing installed runtimes, we filter based on their run-for tags
376+
# to represent 'py exec -V:<tag>' behaviour.
377+
367378
try:
368379
installs = cmd.get_installs(include_unmanaged=cmd.unmanaged)
369380
except OSError:
370381
LOGGER.debug("Unable to read installs", exc_info=True)
371382
installs = []
372383

373-
if tags:
374-
LOGGER.debug("Filtering to following items")
375-
for t in tags:
376-
LOGGER.debug("* %r", t)
377-
installs = [i for i in installs if install_matches_any(i, tags, loose_company=True)]
384+
if tags and installs:
385+
LOGGER.debug("Filtering to following items: %r", tags)
386+
installs = [i for i in installs
387+
if install_matches_any(i, tags, for_run=True)]
388+
if any(t.prefers_prerelease for t in tags):
389+
from .installs import make_sort_key_ignore_pre
390+
installs.sort(key=make_sort_key_ignore_pre)
378391

379-
if not cmd.unmanaged:
392+
if not cmd.unmanaged and installs:
380393
# Just in case any leak through (e.g. active venv)
381394
installs = [i for i in installs if not i.get("unmanaged")]
395+
396+
if cmd.one and installs:
397+
# Use the filtered list and select the best option for each tag.
398+
# Then return the best of those including prereleases
399+
from .installs import get_install_to_run, make_sort_key_ignore_pre
400+
best = []
401+
for t in (tags or [None]):
402+
try:
403+
best.append(get_install_to_run(
404+
cmd.install_dir,
405+
cmd.default_tag,
406+
t,
407+
default_platform=cmd.default_platform,
408+
installs=installs,
409+
))
410+
except (NoInstallFoundError, NoInstallsError):
411+
continue
412+
installs = sorted(best or installs, key=make_sort_key_ignore_pre)[:1]
382413
else:
383414
raise ArgumentError("Configuration file does not specify install directory.")
384415

385-
if cmd.one:
386-
installs = [i for i in installs if i.get("default")][:1] or installs[:1]
387416
formatter(cmd, installs)
388417

389418
LOGGER.debug("END list_command.execute")

‎src/manage/scriptutils.py‎

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -322,7 +322,6 @@ def _maybe_quote(a):
322322
bits.append(b)
323323
if b[-1:] == "\\":
324324
bits.append("\\" * (len(b) - len(b.rstrip("\\"))))
325-
print(a.split('"'), bits)
326325
a = ''.join(bits)
327326
return f'"{a}"' if ' ' in a else a
328327

0 commit comments

Comments
 (0)