Files
setup-uv/src/version/requirements-file.ts
Kevin Stillhammer d31148d669 Strip environment markers from detected uv dependency pins (#938)
## Summary
- strip PEP 508 environment markers before extracting uv versions from
dependency entries
- cover dependency-group pins with and without whitespace before the
marker
- cover requirements-style pins with markers

Fixes #920

## Validation
- npm ci --ignore-scripts
- npm run all

Refs: pi-session 019f316a-4108-7975-892f-ee5bf8abc7c3
2026-07-05 10:47:17 +02:00

74 lines
2.1 KiB
TypeScript

import fs from "node:fs";
import * as toml from "smol-toml";
export function getUvVersionFromRequirementsFile(
filePath: string,
): string | undefined {
const fileContent = fs.readFileSync(filePath, "utf-8");
if (filePath.endsWith(".txt")) {
return getUvVersionFromRequirementsText(fileContent);
}
return getUvVersionFromPyprojectContent(fileContent);
}
export function getUvVersionFromRequirementsText(
fileContent: string,
): string | undefined {
return getUvVersionFromAllDependencies(fileContent.split("\n"));
}
export function getUvVersionFromParsedPyproject(
pyproject: Pyproject,
): string | undefined {
const dependencies: string[] = pyproject?.project?.dependencies || [];
const optionalDependencies: string[] = Object.values(
pyproject?.project?.["optional-dependencies"] || {},
).flat();
const devDependencies: string[] = Object.values(
pyproject?.["dependency-groups"] || {},
)
.flat()
.filter((item: string | object) => typeof item === "string");
return getUvVersionFromAllDependencies(
dependencies.concat(optionalDependencies, devDependencies),
);
}
export function getUvVersionFromPyprojectContent(
pyprojectContent: string,
): string | undefined {
const pyproject = parsePyprojectContent(pyprojectContent);
return getUvVersionFromParsedPyproject(pyproject);
}
export interface Pyproject {
project?: {
dependencies?: string[];
"optional-dependencies"?: Record<string, string[]>;
};
"dependency-groups"?: Record<string, Array<string | object>>;
tool?: {
uv?: Record<string, string | undefined>;
};
}
export function parsePyprojectContent(pyprojectContent: string): Pyproject {
return toml.parse(pyprojectContent) as Pyproject;
}
function getUvVersionFromAllDependencies(
allDependencies: string[],
): string | undefined {
return allDependencies
.map(getUvVersionFromDependency)
.find((version): version is string => version !== undefined);
}
function getUvVersionFromDependency(dependency: string): string | undefined {
const dependencyWithoutMarker = dependency.split(";", 1)[0]?.trim();
return dependencyWithoutMarker?.match(/^uv([=<>~!]+\S*)/)?.[1].trim();
}