-
Notifications
You must be signed in to change notification settings - Fork 54
Add inline-script interpreter selection helpers (PEP 723 PR 3/16) #1636
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
StellaHuang95
wants to merge
5
commits into
microsoft:main
Choose a base branch
from
StellaHuang95:pep723-pr3-interpreter-selection
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
5 commits
Select commit
Hold shift + click to select a range
484ae9c
feat(inline-scripts): add interpreter selection helpers (PEP 723 PR 3/3)
StellaHuang95 ab2d861
fix(inline-scripts): require consent before installing Python
StellaHuang95 53a1c5a
refactor(inline-scripts): drop leading-v tolerance from interpreter m…
StellaHuang95 a03d0a3
refactor(inline-scripts): share PEP 440 release helpers
StellaHuang95 42c1db0
Merge branch 'main' into pep723-pr3-interpreter-selection
StellaHuang95 File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,196 @@ | ||
| // Copyright (c) Microsoft Corporation. All rights reserved. | ||
| // Licensed under the MIT License. | ||
|
|
||
| import { PythonEnvironment } from '../api'; | ||
| import { matchesPythonVersion } from './inlineScriptMetadata'; | ||
| import { traceWarn } from './logging'; | ||
| import { compareReleaseSegments, parseReleaseSegments } from './utils/pep440Release'; | ||
|
|
||
| /** | ||
| * Pick the newest installed Python that can serve as a base interpreter for | ||
| * a PEP 723 script. Returns `undefined` if no candidate is usable. This | ||
| * result is not user consent to install anything: the caller must use the | ||
| * consent-gated uv install prompt or surface an actionable error. | ||
| * | ||
| * **Caller contract**: `installed` must contain only BASE interpreters | ||
| * (system Pythons, pyenv-installed, uv-installed, conda `base`) — never | ||
| * venvs / conda named envs / poetry / pipenv project envs. This function | ||
| * does not filter derived envs out, and using one as a venv base produces | ||
| * a nested or broken environment. `api.getEnvironments('global')` is the | ||
| * right source (with the caveat that pipenv's `'global'` scope is known | ||
| * to leak derived envs). | ||
| */ | ||
| export function pickCompatibleInterpreter( | ||
| installed: ReadonlyArray<PythonEnvironment>, | ||
| requiresPython: string | undefined, | ||
| ): PythonEnvironment | undefined { | ||
| const constraint = requiresPython && requiresPython.length > 0 ? requiresPython : undefined; | ||
| const candidates = installed.filter((env) => isUsableBaseInterpreter(env, constraint)); | ||
| if (candidates.length === 0) { | ||
| return undefined; | ||
| } | ||
| const sorted = [...candidates].sort((a, b) => compareVersionsDescending(a.version, b.version)); | ||
| return sorted[0]; | ||
| } | ||
|
|
||
| /** | ||
| * Extract a lower-bound version string from a PEP 440 `requires-python` | ||
| * specifier, suitable as the `version` argument to `uv python install`. | ||
| * | ||
| * Examples: | ||
| * ">=3.13" → "3.13" | ||
| * ">=3.11,<3.13" → "3.11" (tightest lower bound across clauses) | ||
| * "~=3.12.4" → "3.12.4" | ||
| * "==3.12.*" → "3.12" | ||
| * "==3.12.7" → "3.12.7" | ||
| * | ||
| * Returns `undefined` for specifiers without a clean lower bound (`<3.13`, | ||
| * `!=3.10`, `>3.12`, `===…`, illegal shapes like `~=3` or `>=3.*`). The | ||
| * caller falls back to the uv default and re-verifies with | ||
| * `matchesPythonVersion` after install. | ||
| */ | ||
| export function extractLowerBoundVersion(requiresPython: string | undefined): string | undefined { | ||
| if (!requiresPython) { | ||
| return undefined; | ||
| } | ||
| const clauses = requiresPython | ||
| .split(',') | ||
| .map((c) => c.trim()) | ||
| .filter((c) => c.length > 0); | ||
| if (clauses.length === 0) { | ||
| return undefined; | ||
| } | ||
|
|
||
| let best: number[] | undefined; | ||
| let bestStr: string | undefined; | ||
| for (const clause of clauses) { | ||
| const lb = lowerBoundForClause(clause); | ||
| if (lb === undefined) { | ||
| continue; | ||
| } | ||
| if (best === undefined || compareReleaseSegments(lb.segments, best) > 0) { | ||
| best = lb.segments; | ||
| bestStr = lb.display; | ||
| } | ||
| } | ||
| return bestStr; | ||
| } | ||
|
|
||
| function isUsableBaseInterpreter(env: PythonEnvironment, requiresPython: string | undefined): boolean { | ||
| if (env.error) { | ||
| return false; | ||
| } | ||
| if (typeof env.version !== 'string' || env.version.length === 0) { | ||
| return false; | ||
| } | ||
| if (parseLeadingMajor(env.version) !== 3) { | ||
| return false; | ||
| } | ||
| if (requiresPython !== undefined && !matchesPythonVersion(requiresPython, env.version)) { | ||
| return false; | ||
| } | ||
| return true; | ||
| } | ||
|
|
||
| function parseLeadingMajor(version: string): number | undefined { | ||
| const m = version.match(/^\s*(\d+)/); | ||
| if (!m) { | ||
| return undefined; | ||
| } | ||
| const n = Number.parseInt(m[1], 10); | ||
| return Number.isNaN(n) ? undefined : n; | ||
| } | ||
|
|
||
| function compareVersionsDescending(a: string, b: string): number { | ||
| const aSeg = parseReleaseSegments(a); | ||
| const bSeg = parseReleaseSegments(b); | ||
| if (aSeg === undefined && bSeg === undefined) { | ||
| return 0; | ||
| } | ||
| if (aSeg === undefined) { | ||
| return 1; | ||
| } | ||
| if (bSeg === undefined) { | ||
| return -1; | ||
| } | ||
| return compareReleaseSegments(bSeg, aSeg); | ||
| } | ||
|
|
||
| const CLAUSE_RE = /^(===|~=|==|!=|>=|<=|>|<)\s*(.+)$/; | ||
|
|
||
| interface LowerBound { | ||
| readonly segments: number[]; | ||
| readonly display: string; | ||
| } | ||
|
|
||
| function lowerBoundForClause(clause: string): LowerBound | undefined { | ||
| const m = clause.match(CLAUSE_RE); | ||
| if (!m) { | ||
| traceWarn(`inline-script interpreter: unrecognized requires-python clause: ${JSON.stringify(clause)}`); | ||
| return undefined; | ||
| } | ||
| const op = m[1]; | ||
| const raw = m[2].trim(); | ||
|
|
||
| switch (op) { | ||
| case '>=': { | ||
| // Per PEP 440 wildcards are only legal with `==` / `!=`. Stay | ||
| // consistent with matchesPythonVersion (which rejects `>=X.*`) | ||
| // so we never hand uv a value the picker will then reject. | ||
| if (raw.endsWith('.*')) { | ||
| traceWarn( | ||
| `inline-script interpreter: wildcards are only valid with '==' / '!=': ${JSON.stringify(clause)}`, | ||
| ); | ||
| return undefined; | ||
| } | ||
| const segments = parseReleaseSegments(raw); | ||
| if (segments === undefined) { | ||
| return undefined; | ||
| } | ||
| return { segments, display: segmentsToString(segments) }; | ||
| } | ||
| case '==': { | ||
| const literal = raw.endsWith('.*') ? raw.slice(0, -2) : raw; | ||
| const segments = parseReleaseSegments(literal); | ||
| if (segments === undefined) { | ||
| return undefined; | ||
| } | ||
| return { segments, display: segmentsToString(segments) }; | ||
| } | ||
| case '~=': { | ||
| // PEP 440 requires at least two release segments and disallows | ||
| // wildcards for `~=`. Both rejections mirror matchesPythonVersion. | ||
| if (raw.endsWith('.*')) { | ||
| traceWarn( | ||
| `inline-script interpreter: wildcards are only valid with '==' / '!=': ${JSON.stringify(clause)}`, | ||
| ); | ||
| return undefined; | ||
| } | ||
| const segments = parseReleaseSegments(raw); | ||
| if (segments === undefined) { | ||
| return undefined; | ||
| } | ||
| if (segments.length < 2) { | ||
| traceWarn( | ||
| `inline-script interpreter: '~=' requires at least two release segments: ${JSON.stringify(clause)}`, | ||
| ); | ||
| return undefined; | ||
| } | ||
| return { segments, display: segmentsToString(segments) }; | ||
| } | ||
| case '>': | ||
| case '<': | ||
| case '<=': | ||
| case '!=': | ||
| case '===': | ||
| // No clean integer floor we can hand to `uv python install`. | ||
| // Caller falls back to uv default and re-verifies post-install. | ||
| return undefined; | ||
| default: | ||
| return undefined; | ||
| } | ||
| } | ||
|
|
||
| function segmentsToString(segments: ReadonlyArray<number>): string { | ||
| return segments.join('.'); | ||
| } | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,45 @@ | ||
| // Copyright (c) Microsoft Corporation. All rights reserved. | ||
| // Licensed under the MIT License. | ||
|
|
||
| /** | ||
| * Parse the release segments from a PEP 440 version string. | ||
| * | ||
| * Release segments are the dotted numeric components of a version, such as | ||
| * `[3, 12, 4]` for `3.12.4`. Leading/trailing whitespace, a leading `v`, and | ||
| * an epoch prefix are ignored. Pre-release, post-release, development, and | ||
| * local-version suffixes are intentionally omitted. | ||
| */ | ||
| export function parseReleaseSegments(version: string): number[] | undefined { | ||
| let normalized = version.trim().replace(/^v/i, ''); | ||
| const epoch = normalized.match(/^\d+!(.*)$/); | ||
| if (epoch) { | ||
| normalized = epoch[1]; | ||
| } | ||
| const match = normalized.match(/^(\d+(?:\.\d+)*)/); | ||
| if (!match) { | ||
| return undefined; | ||
| } | ||
| return match[1].split('.').map((segment) => Number.parseInt(segment, 10)); | ||
| } | ||
|
|
||
| /** | ||
| * Compare two PEP 440 release-segment arrays numerically. | ||
| * | ||
| * Missing trailing segments are treated as zero, so `3.12` and `3.12.0` | ||
| * compare as equal. Returns a negative number when `left` is older, zero when | ||
| * they are equal, and a positive number when `left` is newer. | ||
| */ | ||
| export function compareReleaseSegments(left: readonly number[], right: readonly number[]): number { | ||
| const length = Math.max(left.length, right.length); | ||
| for (let index = 0; index < length; index++) { | ||
| const leftSegment = left[index] ?? 0; | ||
| const rightSegment = right[index] ?? 0; | ||
| if (leftSegment < rightSegment) { | ||
| return -1; | ||
| } | ||
| if (leftSegment > rightSegment) { | ||
| return 1; | ||
| } | ||
| } | ||
| return 0; | ||
| } |
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.