mirror of
https://github.com/astral-sh/setup-uv.git
synced 2026-03-14 17:14:58 +00:00
Compare commits
4 Commits
v7.5.0
...
speed-up-v
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
01149c4575 | ||
|
|
fd8f376b22 | ||
|
|
f9070de1ea | ||
|
|
cadb67bdc9 |
2
.github/workflows/test.yml
vendored
2
.github/workflows/test.yml
vendored
@@ -38,7 +38,7 @@ jobs:
|
||||
npm run all
|
||||
- name: Check all jobs are in all-tests-passed.needs
|
||||
run: |
|
||||
tsc check-all-tests-passed-needs.ts
|
||||
tsc --module nodenext --moduleResolution nodenext --target es2022 check-all-tests-passed-needs.ts
|
||||
node check-all-tests-passed-needs.js
|
||||
working-directory: .github/scripts
|
||||
- name: Make sure no changes from linters are detected
|
||||
|
||||
5
.github/workflows/update-known-checksums.yml
vendored
5
.github/workflows/update-known-checksums.yml
vendored
@@ -20,11 +20,12 @@ jobs:
|
||||
persist-credentials: true
|
||||
- uses: actions/setup-node@53b83947a5a98c8d113130e565377fae1a50d02f # v6.3.0
|
||||
with:
|
||||
node-version: "20"
|
||||
node-version-file: .nvmrc
|
||||
cache: npm
|
||||
- name: Update known checksums
|
||||
id: update-known-checksums
|
||||
run:
|
||||
node dist/update-known-checksums/index.js
|
||||
node dist/update-known-checksums/index.cjs
|
||||
src/download/checksum/known-checksums.ts
|
||||
- name: Check for changes
|
||||
id: changes-exist
|
||||
|
||||
@@ -10,4 +10,9 @@ This repository is a TypeScript-based GitHub Action for installing `uv` in GitHu
|
||||
- User-facing changes are usually multi-file changes. If you add or change inputs, outputs, or behavior, update `action.yml`, the implementation in `src/`, tests in `__tests__/`, relevant docs/README, and then re-package.
|
||||
- The easiest areas to regress are version resolution and caching. When touching them, add or update tests for precedence, cache invalidation, and cross-platform path behavior.
|
||||
- Workflow edits have extra CI-only checks (`actionlint` and `zizmor`); `npm run all` does not cover them.
|
||||
- Source is authored with bundler-friendly TypeScript, but published action artifacts in `dist/` are bundled as CommonJS for maximum GitHub Actions runtime compatibility with `@actions/*` dependencies.
|
||||
- Keep these concerns separate when changing module formats:
|
||||
- `src/` and tests may use modern ESM-friendly TypeScript patterns.
|
||||
- `dist/` should prioritize runtime reliability over format purity.
|
||||
- Do not switch published bundles to ESM without validating the actual committed artifacts under the target Node runtime.
|
||||
- Before finishing, make sure validation does not leave generated or formatting-only diffs behind.
|
||||
|
||||
@@ -1,9 +1,10 @@
|
||||
import { beforeEach, describe, expect, it, jest } from "@jest/globals";
|
||||
import * as semver from "semver";
|
||||
|
||||
const mockInfo = jest.fn();
|
||||
const mockWarning = jest.fn();
|
||||
|
||||
jest.mock("@actions/core", () => ({
|
||||
jest.unstable_mockModule("@actions/core", () => ({
|
||||
debug: jest.fn(),
|
||||
info: mockInfo,
|
||||
warning: mockWarning,
|
||||
@@ -18,20 +19,17 @@ const mockExtractZip = jest.fn<any>();
|
||||
// biome-ignore lint/suspicious/noExplicitAny: Mock requires flexible typing in tests.
|
||||
const mockCacheDir = jest.fn<any>();
|
||||
|
||||
jest.mock("@actions/tool-cache", () => {
|
||||
const actual = jest.requireActual("@actions/tool-cache") as Record<
|
||||
string,
|
||||
unknown
|
||||
>;
|
||||
|
||||
return {
|
||||
...actual,
|
||||
cacheDir: mockCacheDir,
|
||||
downloadTool: mockDownloadTool,
|
||||
extractTar: mockExtractTar,
|
||||
extractZip: mockExtractZip,
|
||||
};
|
||||
});
|
||||
jest.unstable_mockModule("@actions/tool-cache", () => ({
|
||||
cacheDir: mockCacheDir,
|
||||
downloadTool: mockDownloadTool,
|
||||
evaluateVersions: (versions: string[], range: string) =>
|
||||
semver.maxSatisfying(versions, range) ?? "",
|
||||
extractTar: mockExtractTar,
|
||||
extractZip: mockExtractZip,
|
||||
find: () => "",
|
||||
findAllVersions: () => [],
|
||||
isExplicitVersion: (version: string) => semver.valid(version) !== null,
|
||||
}));
|
||||
|
||||
// biome-ignore lint/suspicious/noExplicitAny: Mock requires flexible typing in tests.
|
||||
const mockGetLatestVersionFromNdjson = jest.fn<any>();
|
||||
@@ -39,10 +37,13 @@ const mockGetLatestVersionFromNdjson = jest.fn<any>();
|
||||
const mockGetAllVersionsFromNdjson = jest.fn<any>();
|
||||
// biome-ignore lint/suspicious/noExplicitAny: Mock requires flexible typing in tests.
|
||||
const mockGetArtifactFromNdjson = jest.fn<any>();
|
||||
// biome-ignore lint/suspicious/noExplicitAny: Mock requires flexible typing in tests.
|
||||
const mockGetHighestSatisfyingVersionFromNdjson = jest.fn<any>();
|
||||
|
||||
jest.mock("../../src/download/versions-client", () => ({
|
||||
jest.unstable_mockModule("../../src/download/versions-client", () => ({
|
||||
getAllVersions: mockGetAllVersionsFromNdjson,
|
||||
getArtifact: mockGetArtifactFromNdjson,
|
||||
getHighestSatisfyingVersion: mockGetHighestSatisfyingVersionFromNdjson,
|
||||
getLatestVersion: mockGetLatestVersionFromNdjson,
|
||||
}));
|
||||
|
||||
@@ -53,7 +54,7 @@ const mockGetLatestVersionInManifest = jest.fn<any>();
|
||||
// biome-ignore lint/suspicious/noExplicitAny: Mock requires flexible typing in tests.
|
||||
const mockGetManifestArtifact = jest.fn<any>();
|
||||
|
||||
jest.mock("../../src/download/version-manifest", () => ({
|
||||
jest.unstable_mockModule("../../src/download/version-manifest", () => ({
|
||||
getAllVersions: mockGetAllManifestVersions,
|
||||
getLatestKnownVersion: mockGetLatestVersionInManifest,
|
||||
getManifestArtifact: mockGetManifestArtifact,
|
||||
@@ -62,15 +63,15 @@ jest.mock("../../src/download/version-manifest", () => ({
|
||||
// biome-ignore lint/suspicious/noExplicitAny: Mock requires flexible typing in tests.
|
||||
const mockValidateChecksum = jest.fn<any>();
|
||||
|
||||
jest.mock("../../src/download/checksum/checksum", () => ({
|
||||
jest.unstable_mockModule("../../src/download/checksum/checksum", () => ({
|
||||
validateChecksum: mockValidateChecksum,
|
||||
}));
|
||||
|
||||
import {
|
||||
const {
|
||||
downloadVersionFromManifest,
|
||||
downloadVersionFromNdjson,
|
||||
resolveVersion,
|
||||
} from "../../src/download/download-version";
|
||||
} = await import("../../src/download/download-version");
|
||||
|
||||
describe("download-version", () => {
|
||||
beforeEach(() => {
|
||||
@@ -83,6 +84,7 @@ describe("download-version", () => {
|
||||
mockGetLatestVersionFromNdjson.mockReset();
|
||||
mockGetAllVersionsFromNdjson.mockReset();
|
||||
mockGetArtifactFromNdjson.mockReset();
|
||||
mockGetHighestSatisfyingVersionFromNdjson.mockReset();
|
||||
mockGetAllManifestVersions.mockReset();
|
||||
mockGetLatestVersionInManifest.mockReset();
|
||||
mockGetManifestArtifact.mockReset();
|
||||
@@ -104,13 +106,26 @@ describe("download-version", () => {
|
||||
expect(mockGetLatestVersionFromNdjson).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it("uses astral-sh/versions to resolve available versions", async () => {
|
||||
mockGetAllVersionsFromNdjson.mockResolvedValue(["0.9.26", "0.9.25"]);
|
||||
it("streams astral-sh/versions to resolve the highest matching version", async () => {
|
||||
mockGetHighestSatisfyingVersionFromNdjson.mockResolvedValue("0.9.26");
|
||||
|
||||
const version = await resolveVersion("^0.9.0", undefined);
|
||||
|
||||
expect(version).toBe("0.9.26");
|
||||
expect(mockGetHighestSatisfyingVersionFromNdjson).toHaveBeenCalledWith(
|
||||
"^0.9.0",
|
||||
);
|
||||
expect(mockGetAllVersionsFromNdjson).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("still loads all versions when resolving the lowest matching version", async () => {
|
||||
mockGetAllVersionsFromNdjson.mockResolvedValue(["0.9.26", "0.9.25"]);
|
||||
|
||||
const version = await resolveVersion("^0.9.0", undefined, "lowest");
|
||||
|
||||
expect(version).toBe("0.9.25");
|
||||
expect(mockGetAllVersionsFromNdjson).toHaveBeenCalledTimes(1);
|
||||
expect(mockGetHighestSatisfyingVersionFromNdjson).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("does not fall back when astral-sh/versions fails", async () => {
|
||||
|
||||
@@ -2,7 +2,7 @@ import { beforeEach, describe, expect, it, jest } from "@jest/globals";
|
||||
|
||||
const mockWarning = jest.fn();
|
||||
|
||||
jest.mock("@actions/core", () => ({
|
||||
jest.unstable_mockModule("@actions/core", () => ({
|
||||
debug: jest.fn(),
|
||||
info: jest.fn(),
|
||||
warning: mockWarning,
|
||||
@@ -10,16 +10,16 @@ jest.mock("@actions/core", () => ({
|
||||
|
||||
// biome-ignore lint/suspicious/noExplicitAny: Mock requires flexible typing in tests.
|
||||
const mockFetch = jest.fn<any>();
|
||||
jest.mock("../../src/utils/fetch", () => ({
|
||||
jest.unstable_mockModule("../../src/utils/fetch", () => ({
|
||||
fetch: mockFetch,
|
||||
}));
|
||||
|
||||
import {
|
||||
const {
|
||||
clearManifestCache,
|
||||
getAllVersions,
|
||||
getLatestKnownVersion,
|
||||
getManifestArtifact,
|
||||
} from "../../src/download/version-manifest";
|
||||
} = await import("../../src/download/version-manifest");
|
||||
|
||||
const legacyManifestResponse = JSON.stringify([
|
||||
{
|
||||
|
||||
@@ -2,31 +2,48 @@ import { beforeEach, describe, expect, it, jest } from "@jest/globals";
|
||||
|
||||
// biome-ignore lint/suspicious/noExplicitAny: Mock requires flexible typing in tests.
|
||||
const mockFetch = jest.fn<any>();
|
||||
jest.mock("../../src/utils/fetch", () => ({
|
||||
|
||||
jest.unstable_mockModule("../../src/utils/fetch", () => ({
|
||||
fetch: mockFetch,
|
||||
}));
|
||||
|
||||
import {
|
||||
const {
|
||||
clearCache,
|
||||
fetchVersionData,
|
||||
getAllVersions,
|
||||
getArtifact,
|
||||
getHighestSatisfyingVersion,
|
||||
getLatestVersion,
|
||||
parseVersionData,
|
||||
} from "../../src/download/versions-client";
|
||||
} = await import("../../src/download/versions-client");
|
||||
|
||||
const sampleNdjsonResponse = `{"version":"0.9.26","artifacts":[{"platform":"aarch64-apple-darwin","variant":"default","url":"https://github.com/astral-sh/uv/releases/download/0.9.26/uv-aarch64-apple-darwin.tar.gz","archive_format":"tar.gz","sha256":"fcf0a9ea6599c6ae28a4c854ac6da76f2c889354d7c36ce136ef071f7ab9721f"},{"platform":"x86_64-pc-windows-msvc","variant":"default","url":"https://github.com/astral-sh/uv/releases/download/0.9.26/uv-x86_64-pc-windows-msvc.zip","archive_format":"zip","sha256":"eb02fd95d8e0eed462b4a67ecdd320d865b38c560bffcda9a0b87ec944bdf036"}]}
|
||||
{"version":"0.9.25","artifacts":[{"platform":"aarch64-apple-darwin","variant":"default","url":"https://github.com/astral-sh/uv/releases/download/0.9.25/uv-aarch64-apple-darwin.tar.gz","archive_format":"tar.gz","sha256":"606b3c6949d971709f2526fa0d9f0fd23ccf60e09f117999b406b424af18a6a6"}]}`;
|
||||
|
||||
const multiVariantNdjsonResponse = `{"version":"0.9.26","artifacts":[{"platform":"aarch64-apple-darwin","variant":"python-managed","url":"https://github.com/astral-sh/uv/releases/download/0.9.26/uv-aarch64-apple-darwin-managed.tar.gz","archive_format":"tar.gz","sha256":"managed-checksum"},{"platform":"aarch64-apple-darwin","variant":"default","url":"https://github.com/astral-sh/uv/releases/download/0.9.26/uv-aarch64-apple-darwin.zip","archive_format":"zip","sha256":"default-checksum"}]}`;
|
||||
|
||||
function createMockStream(chunks: string[]): ReadableStream<Uint8Array> {
|
||||
const encoder = new TextEncoder();
|
||||
|
||||
return new ReadableStream<Uint8Array>({
|
||||
start(controller) {
|
||||
for (const chunk of chunks) {
|
||||
controller.enqueue(encoder.encode(chunk));
|
||||
}
|
||||
controller.close();
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
function createMockResponse(
|
||||
ok: boolean,
|
||||
status: number,
|
||||
statusText: string,
|
||||
data: string,
|
||||
chunks: string[] = [data],
|
||||
) {
|
||||
return {
|
||||
body: createMockStream(chunks),
|
||||
ok,
|
||||
status,
|
||||
statusText,
|
||||
@@ -85,6 +102,22 @@ describe("versions-client", () => {
|
||||
|
||||
expect(latest).toBe("0.9.26");
|
||||
});
|
||||
|
||||
it("should stop after the first record when resolving latest", async () => {
|
||||
mockFetch.mockResolvedValue(
|
||||
createMockResponse(
|
||||
true,
|
||||
200,
|
||||
"OK",
|
||||
`${sampleNdjsonResponse}\n{"version":`,
|
||||
[`${sampleNdjsonResponse.split("\n")[0]}\n`, '{"version":'],
|
||||
),
|
||||
);
|
||||
|
||||
const latest = await getLatestVersion();
|
||||
|
||||
expect(latest).toBe("0.9.26");
|
||||
});
|
||||
});
|
||||
|
||||
describe("getAllVersions", () => {
|
||||
@@ -99,6 +132,24 @@ describe("versions-client", () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe("getHighestSatisfyingVersion", () => {
|
||||
it("should return the first matching version from the stream", async () => {
|
||||
mockFetch.mockResolvedValue(
|
||||
createMockResponse(
|
||||
true,
|
||||
200,
|
||||
"OK",
|
||||
`${sampleNdjsonResponse}\n{"version":`,
|
||||
[`${sampleNdjsonResponse.split("\n")[0]}\n`, '{"version":'],
|
||||
),
|
||||
);
|
||||
|
||||
const version = await getHighestSatisfyingVersion("^0.9.0");
|
||||
|
||||
expect(version).toBe("0.9.26");
|
||||
});
|
||||
});
|
||||
|
||||
describe("getArtifact", () => {
|
||||
beforeEach(() => {
|
||||
mockFetch.mockResolvedValue(
|
||||
@@ -117,6 +168,27 @@ describe("versions-client", () => {
|
||||
});
|
||||
});
|
||||
|
||||
it("should stop once the requested version is found", async () => {
|
||||
mockFetch.mockResolvedValue(
|
||||
createMockResponse(
|
||||
true,
|
||||
200,
|
||||
"OK",
|
||||
`${sampleNdjsonResponse}\n{"version":`,
|
||||
[`${sampleNdjsonResponse.split("\n")[0]}\n`, '{"version":'],
|
||||
),
|
||||
);
|
||||
|
||||
const artifact = await getArtifact("0.9.26", "aarch64", "apple-darwin");
|
||||
|
||||
expect(artifact).toEqual({
|
||||
archiveFormat: "tar.gz",
|
||||
sha256:
|
||||
"fcf0a9ea6599c6ae28a4c854ac6da76f2c889354d7c36ce136ef071f7ab9721f",
|
||||
url: "https://github.com/astral-sh/uv/releases/download/0.9.26/uv-aarch64-apple-darwin.tar.gz",
|
||||
});
|
||||
});
|
||||
|
||||
it("should find windows artifact", async () => {
|
||||
const artifact = await getArtifact("0.9.26", "x86_64", "pc-windows-msvc");
|
||||
|
||||
|
||||
@@ -1,14 +1,3 @@
|
||||
jest.mock("@actions/core", () => {
|
||||
return {
|
||||
debug: jest.fn(),
|
||||
getBooleanInput: jest.fn(
|
||||
(name: string) => (mockInputs[name] ?? "") === "true",
|
||||
),
|
||||
getInput: jest.fn((name: string) => mockInputs[name] ?? ""),
|
||||
warning: jest.fn(),
|
||||
};
|
||||
});
|
||||
|
||||
import {
|
||||
afterEach,
|
||||
beforeEach,
|
||||
@@ -22,6 +11,26 @@ import {
|
||||
let mockInputs: Record<string, string> = {};
|
||||
const ORIGINAL_HOME = process.env.HOME;
|
||||
|
||||
const mockDebug = jest.fn();
|
||||
const mockGetBooleanInput = jest.fn(
|
||||
(name: string) => (mockInputs[name] ?? "") === "true",
|
||||
);
|
||||
const mockGetInput = jest.fn((name: string) => mockInputs[name] ?? "");
|
||||
const mockInfo = jest.fn();
|
||||
const mockWarning = jest.fn();
|
||||
|
||||
jest.unstable_mockModule("@actions/core", () => ({
|
||||
debug: mockDebug,
|
||||
getBooleanInput: mockGetBooleanInput,
|
||||
getInput: mockGetInput,
|
||||
info: mockInfo,
|
||||
warning: mockWarning,
|
||||
}));
|
||||
|
||||
async function importInputsModule() {
|
||||
return await import("../../src/utils/inputs");
|
||||
}
|
||||
|
||||
describe("cacheDependencyGlob", () => {
|
||||
beforeEach(() => {
|
||||
jest.resetModules();
|
||||
@@ -36,21 +45,21 @@ describe("cacheDependencyGlob", () => {
|
||||
|
||||
it("returns empty string when input not provided", async () => {
|
||||
mockInputs["working-directory"] = "/workspace";
|
||||
const { cacheDependencyGlob } = await import("../../src/utils/inputs");
|
||||
const { cacheDependencyGlob } = await importInputsModule();
|
||||
expect(cacheDependencyGlob).toBe("");
|
||||
});
|
||||
|
||||
it("resolves a single relative path", async () => {
|
||||
mockInputs["working-directory"] = "/workspace";
|
||||
mockInputs["cache-dependency-glob"] = "requirements.txt";
|
||||
const { cacheDependencyGlob } = await import("../../src/utils/inputs");
|
||||
const { cacheDependencyGlob } = await importInputsModule();
|
||||
expect(cacheDependencyGlob).toBe("/workspace/requirements.txt");
|
||||
});
|
||||
|
||||
it("strips leading ./ from relative path", async () => {
|
||||
mockInputs["working-directory"] = "/workspace";
|
||||
mockInputs["cache-dependency-glob"] = "./uv.lock";
|
||||
const { cacheDependencyGlob } = await import("../../src/utils/inputs");
|
||||
const { cacheDependencyGlob } = await importInputsModule();
|
||||
expect(cacheDependencyGlob).toBe("/workspace/uv.lock");
|
||||
});
|
||||
|
||||
@@ -58,7 +67,7 @@ describe("cacheDependencyGlob", () => {
|
||||
mockInputs["working-directory"] = "/workspace";
|
||||
mockInputs["cache-dependency-glob"] =
|
||||
" ~/.cache/file1\n ./rel/file2 \nfile3.txt";
|
||||
const { cacheDependencyGlob } = await import("../../src/utils/inputs");
|
||||
const { cacheDependencyGlob } = await importInputsModule();
|
||||
expect(cacheDependencyGlob).toBe(
|
||||
[
|
||||
"/home/testuser/.cache/file1", // expanded tilde, absolute path unchanged
|
||||
@@ -71,7 +80,7 @@ describe("cacheDependencyGlob", () => {
|
||||
it("keeps absolute path unchanged in multiline input", async () => {
|
||||
mockInputs["working-directory"] = "/workspace";
|
||||
mockInputs["cache-dependency-glob"] = "/abs/path.lock\nrelative.lock";
|
||||
const { cacheDependencyGlob } = await import("../../src/utils/inputs");
|
||||
const { cacheDependencyGlob } = await importInputsModule();
|
||||
expect(cacheDependencyGlob).toBe(
|
||||
["/abs/path.lock", "/workspace/relative.lock"].join("\n"),
|
||||
);
|
||||
@@ -80,7 +89,7 @@ describe("cacheDependencyGlob", () => {
|
||||
it("handles exclusions in relative paths correct", async () => {
|
||||
mockInputs["working-directory"] = "/workspace";
|
||||
mockInputs["cache-dependency-glob"] = "!/abs/path.lock\n!relative.lock";
|
||||
const { cacheDependencyGlob } = await import("../../src/utils/inputs");
|
||||
const { cacheDependencyGlob } = await importInputsModule();
|
||||
expect(cacheDependencyGlob).toBe(
|
||||
["!/abs/path.lock", "!/workspace/relative.lock"].join("\n"),
|
||||
);
|
||||
@@ -104,7 +113,7 @@ describe("tool directories", () => {
|
||||
mockInputs["tool-bin-dir"] = "~/tool-bin-dir";
|
||||
mockInputs["tool-dir"] = "~/tool-dir";
|
||||
|
||||
const { toolBinDir, toolDir } = await import("../../src/utils/inputs");
|
||||
const { toolBinDir, toolDir } = await importInputsModule();
|
||||
|
||||
expect(toolBinDir).toBe("/home/testuser/tool-bin-dir");
|
||||
expect(toolDir).toBe("/home/testuser/tool-dir");
|
||||
@@ -127,9 +136,7 @@ describe("cacheLocalPath", () => {
|
||||
mockInputs["working-directory"] = "/workspace";
|
||||
mockInputs["cache-local-path"] = "~/uv-cache/cache-local-path";
|
||||
|
||||
const { CacheLocalSource, cacheLocalPath } = await import(
|
||||
"../../src/utils/inputs"
|
||||
);
|
||||
const { CacheLocalSource, cacheLocalPath } = await importInputsModule();
|
||||
|
||||
expect(cacheLocalPath).toEqual({
|
||||
path: "/home/testuser/uv-cache/cache-local-path",
|
||||
@@ -152,7 +159,7 @@ describe("venvPath", () => {
|
||||
|
||||
it("defaults to .venv in the working directory", async () => {
|
||||
mockInputs["working-directory"] = "/workspace";
|
||||
const { venvPath } = await import("../../src/utils/inputs");
|
||||
const { venvPath } = await importInputsModule();
|
||||
expect(venvPath).toBe("/workspace/.venv");
|
||||
});
|
||||
|
||||
@@ -160,7 +167,7 @@ describe("venvPath", () => {
|
||||
mockInputs["working-directory"] = "/workspace";
|
||||
mockInputs["activate-environment"] = "true";
|
||||
mockInputs["venv-path"] = "custom-venv";
|
||||
const { venvPath } = await import("../../src/utils/inputs");
|
||||
const { venvPath } = await importInputsModule();
|
||||
expect(venvPath).toBe("/workspace/custom-venv");
|
||||
});
|
||||
|
||||
@@ -168,7 +175,7 @@ describe("venvPath", () => {
|
||||
mockInputs["working-directory"] = "/workspace";
|
||||
mockInputs["activate-environment"] = "true";
|
||||
mockInputs["venv-path"] = "custom-venv/";
|
||||
const { venvPath } = await import("../../src/utils/inputs");
|
||||
const { venvPath } = await importInputsModule();
|
||||
expect(venvPath).toBe("/workspace/custom-venv");
|
||||
});
|
||||
|
||||
@@ -176,7 +183,7 @@ describe("venvPath", () => {
|
||||
mockInputs["working-directory"] = "/workspace";
|
||||
mockInputs["activate-environment"] = "true";
|
||||
mockInputs["venv-path"] = "/tmp/custom-venv";
|
||||
const { venvPath } = await import("../../src/utils/inputs");
|
||||
const { venvPath } = await importInputsModule();
|
||||
expect(venvPath).toBe("/tmp/custom-venv");
|
||||
});
|
||||
|
||||
@@ -184,7 +191,7 @@ describe("venvPath", () => {
|
||||
mockInputs["working-directory"] = "/workspace";
|
||||
mockInputs["activate-environment"] = "true";
|
||||
mockInputs["venv-path"] = "~/.venv";
|
||||
const { venvPath } = await import("../../src/utils/inputs");
|
||||
const { venvPath } = await importInputsModule();
|
||||
expect(venvPath).toBe("/home/testuser/.venv");
|
||||
});
|
||||
|
||||
@@ -192,18 +199,11 @@ describe("venvPath", () => {
|
||||
mockInputs["working-directory"] = "/workspace";
|
||||
mockInputs["venv-path"] = "custom-venv";
|
||||
|
||||
const { activateEnvironment, venvPath } = await import(
|
||||
"../../src/utils/inputs"
|
||||
);
|
||||
const { activateEnvironment, venvPath } = await importInputsModule();
|
||||
|
||||
expect(activateEnvironment).toBe(false);
|
||||
expect(venvPath).toBe("/workspace/custom-venv");
|
||||
|
||||
const mockedCore = jest.requireMock("@actions/core") as {
|
||||
warning: jest.Mock;
|
||||
};
|
||||
|
||||
expect(mockedCore.warning).toHaveBeenCalledWith(
|
||||
expect(mockWarning).toHaveBeenCalledWith(
|
||||
"venv-path is only used when activate-environment is true",
|
||||
);
|
||||
});
|
||||
|
||||
@@ -1,113 +1,121 @@
|
||||
jest.mock("node:fs");
|
||||
jest.mock("@actions/core", () => ({
|
||||
warning: jest.fn(),
|
||||
import { beforeEach, describe, expect, it, jest } from "@jest/globals";
|
||||
|
||||
const mockReadFileSync = jest.fn();
|
||||
const mockWarning = jest.fn();
|
||||
|
||||
jest.unstable_mockModule("node:fs", () => ({
|
||||
default: {
|
||||
readFileSync: mockReadFileSync,
|
||||
},
|
||||
}));
|
||||
|
||||
import fs from "node:fs";
|
||||
import * as core from "@actions/core";
|
||||
import { beforeEach, describe, expect, it, jest } from "@jest/globals";
|
||||
import { getUvVersionFromToolVersions } from "../../src/version/tool-versions-file";
|
||||
jest.unstable_mockModule("@actions/core", () => ({
|
||||
warning: mockWarning,
|
||||
}));
|
||||
|
||||
const mockedFs = fs as jest.Mocked<typeof fs>;
|
||||
const mockedCore = core as jest.Mocked<typeof core>;
|
||||
async function getVersionFromToolVersions(filePath: string) {
|
||||
const { getUvVersionFromToolVersions } = await import(
|
||||
"../../src/version/tool-versions-file"
|
||||
);
|
||||
|
||||
return getUvVersionFromToolVersions(filePath);
|
||||
}
|
||||
|
||||
describe("getUvVersionFromToolVersions", () => {
|
||||
beforeEach(() => {
|
||||
jest.resetModules();
|
||||
jest.clearAllMocks();
|
||||
});
|
||||
|
||||
it("should return undefined for non-.tool-versions files", () => {
|
||||
const result = getUvVersionFromToolVersions("package.json");
|
||||
it("should return undefined for non-.tool-versions files", async () => {
|
||||
const result = await getVersionFromToolVersions("package.json");
|
||||
expect(result).toBeUndefined();
|
||||
expect(mockedFs.readFileSync).not.toHaveBeenCalled();
|
||||
expect(mockReadFileSync).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("should return version for valid uv entry", () => {
|
||||
it("should return version for valid uv entry", async () => {
|
||||
const fileContent = "python 3.11.0\nuv 0.1.0\nnodejs 18.0.0";
|
||||
mockedFs.readFileSync.mockReturnValue(fileContent);
|
||||
mockReadFileSync.mockReturnValue(fileContent);
|
||||
|
||||
const result = getUvVersionFromToolVersions(".tool-versions");
|
||||
const result = await getVersionFromToolVersions(".tool-versions");
|
||||
|
||||
expect(result).toBe("0.1.0");
|
||||
expect(mockedFs.readFileSync).toHaveBeenCalledWith(
|
||||
".tool-versions",
|
||||
"utf8",
|
||||
);
|
||||
expect(mockReadFileSync).toHaveBeenCalledWith(".tool-versions", "utf8");
|
||||
});
|
||||
|
||||
it("should return version for uv entry with v prefix", () => {
|
||||
it("should return version for uv entry with v prefix", async () => {
|
||||
const fileContent = "uv v0.2.0";
|
||||
mockedFs.readFileSync.mockReturnValue(fileContent);
|
||||
mockReadFileSync.mockReturnValue(fileContent);
|
||||
|
||||
const result = getUvVersionFromToolVersions(".tool-versions");
|
||||
const result = await getVersionFromToolVersions(".tool-versions");
|
||||
|
||||
expect(result).toBe("0.2.0");
|
||||
});
|
||||
|
||||
it("should handle whitespace around uv entry", () => {
|
||||
it("should handle whitespace around uv entry", async () => {
|
||||
const fileContent = " uv 0.3.0 ";
|
||||
mockedFs.readFileSync.mockReturnValue(fileContent);
|
||||
mockReadFileSync.mockReturnValue(fileContent);
|
||||
|
||||
const result = getUvVersionFromToolVersions(".tool-versions");
|
||||
const result = await getVersionFromToolVersions(".tool-versions");
|
||||
|
||||
expect(result).toBe("0.3.0");
|
||||
});
|
||||
|
||||
it("should skip commented lines", () => {
|
||||
it("should skip commented lines", async () => {
|
||||
const fileContent = "# uv 0.1.0\npython 3.11.0\nuv 0.2.0";
|
||||
mockedFs.readFileSync.mockReturnValue(fileContent);
|
||||
mockReadFileSync.mockReturnValue(fileContent);
|
||||
|
||||
const result = getUvVersionFromToolVersions(".tool-versions");
|
||||
const result = await getVersionFromToolVersions(".tool-versions");
|
||||
|
||||
expect(result).toBe("0.2.0");
|
||||
});
|
||||
|
||||
it("should return first matching uv version", () => {
|
||||
it("should return first matching uv version", async () => {
|
||||
const fileContent = "uv 0.1.0\npython 3.11.0\nuv 0.2.0";
|
||||
mockedFs.readFileSync.mockReturnValue(fileContent);
|
||||
mockReadFileSync.mockReturnValue(fileContent);
|
||||
|
||||
const result = getUvVersionFromToolVersions(".tool-versions");
|
||||
const result = await getVersionFromToolVersions(".tool-versions");
|
||||
|
||||
expect(result).toBe("0.1.0");
|
||||
});
|
||||
|
||||
it("should return undefined when no uv entry found", () => {
|
||||
it("should return undefined when no uv entry found", async () => {
|
||||
const fileContent = "python 3.11.0\nnodejs 18.0.0";
|
||||
mockedFs.readFileSync.mockReturnValue(fileContent);
|
||||
mockReadFileSync.mockReturnValue(fileContent);
|
||||
|
||||
const result = getUvVersionFromToolVersions(".tool-versions");
|
||||
const result = await getVersionFromToolVersions(".tool-versions");
|
||||
|
||||
expect(result).toBeUndefined();
|
||||
});
|
||||
|
||||
it("should return undefined for empty file", () => {
|
||||
mockedFs.readFileSync.mockReturnValue("");
|
||||
it("should return undefined for empty file", async () => {
|
||||
mockReadFileSync.mockReturnValue("");
|
||||
|
||||
const result = getUvVersionFromToolVersions(".tool-versions");
|
||||
const result = await getVersionFromToolVersions(".tool-versions");
|
||||
|
||||
expect(result).toBeUndefined();
|
||||
});
|
||||
|
||||
it("should warn and return undefined for ref syntax", () => {
|
||||
it("should warn and return undefined for ref syntax", async () => {
|
||||
const fileContent = "uv ref:main";
|
||||
mockedFs.readFileSync.mockReturnValue(fileContent);
|
||||
mockReadFileSync.mockReturnValue(fileContent);
|
||||
|
||||
const result = getUvVersionFromToolVersions(".tool-versions");
|
||||
const result = await getVersionFromToolVersions(".tool-versions");
|
||||
|
||||
expect(result).toBeUndefined();
|
||||
expect(mockedCore.warning).toHaveBeenCalledWith(
|
||||
expect(mockWarning).toHaveBeenCalledWith(
|
||||
"The ref syntax of .tool-versions is not supported. Please use a released version instead.",
|
||||
);
|
||||
});
|
||||
|
||||
it("should handle file path with .tool-versions extension", () => {
|
||||
it("should handle file path with .tool-versions extension", async () => {
|
||||
const fileContent = "uv 0.1.0";
|
||||
mockedFs.readFileSync.mockReturnValue(fileContent);
|
||||
mockReadFileSync.mockReturnValue(fileContent);
|
||||
|
||||
const result = getUvVersionFromToolVersions("path/to/.tool-versions");
|
||||
const result = await getVersionFromToolVersions("path/to/.tool-versions");
|
||||
|
||||
expect(result).toBe("0.1.0");
|
||||
expect(mockedFs.readFileSync).toHaveBeenCalledWith(
|
||||
expect(mockReadFileSync).toHaveBeenCalledWith(
|
||||
"path/to/.tool-versions",
|
||||
"utf8",
|
||||
);
|
||||
|
||||
@@ -102,8 +102,8 @@ outputs:
|
||||
description: "A boolean value to indicate the Python cache entry was found"
|
||||
runs:
|
||||
using: "node24"
|
||||
main: "dist/setup/index.js"
|
||||
post: "dist/save-cache/index.js"
|
||||
main: "dist/setup/index.cjs"
|
||||
post: "dist/save-cache/index.cjs"
|
||||
post-if: success()
|
||||
branding:
|
||||
icon: "package"
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
{
|
||||
"$schema": "https://biomejs.dev/schemas/2.3.7/schema.json",
|
||||
"$schema": "https://biomejs.dev/schemas/2.4.7/schema.json",
|
||||
"assist": {
|
||||
"actions": {
|
||||
"source": {
|
||||
|
||||
63325
dist/save-cache/index.cjs
generated
vendored
Normal file
63325
dist/save-cache/index.cjs
generated
vendored
Normal file
File diff suppressed because one or more lines are too long
94304
dist/save-cache/index.js
generated
vendored
94304
dist/save-cache/index.js
generated
vendored
File diff suppressed because one or more lines are too long
97307
dist/setup/index.cjs
generated
vendored
Normal file
97307
dist/setup/index.cjs
generated
vendored
Normal file
File diff suppressed because one or more lines are too long
100695
dist/setup/index.js
generated
vendored
100695
dist/setup/index.js
generated
vendored
File diff suppressed because one or more lines are too long
50290
dist/update-known-checksums/index.cjs
generated
vendored
Normal file
50290
dist/update-known-checksums/index.cjs
generated
vendored
Normal file
File diff suppressed because one or more lines are too long
33985
dist/update-known-checksums/index.js
generated
vendored
33985
dist/update-known-checksums/index.js
generated
vendored
File diff suppressed because one or more lines are too long
@@ -1,9 +0,0 @@
|
||||
module.exports = {
|
||||
clearMocks: true,
|
||||
moduleFileExtensions: ["js", "ts"],
|
||||
testMatch: ["**/*.test.ts"],
|
||||
transform: {
|
||||
"^.+\\.ts$": "ts-jest",
|
||||
},
|
||||
verbose: true,
|
||||
};
|
||||
14
jest.config.mjs
Normal file
14
jest.config.mjs
Normal file
@@ -0,0 +1,14 @@
|
||||
import { createDefaultEsmPreset } from "ts-jest";
|
||||
|
||||
const esmPreset = createDefaultEsmPreset({
|
||||
tsconfig: "./tsconfig.json",
|
||||
});
|
||||
|
||||
export default {
|
||||
...esmPreset,
|
||||
clearMocks: true,
|
||||
moduleFileExtensions: ["js", "mjs", "ts"],
|
||||
testEnvironment: "node",
|
||||
testMatch: ["**/*.test.ts"],
|
||||
verbose: true,
|
||||
};
|
||||
4170
package-lock.json
generated
4170
package-lock.json
generated
File diff suppressed because it is too large
Load Diff
42
package.json
42
package.json
@@ -2,16 +2,19 @@
|
||||
"name": "setup-uv",
|
||||
"version": "1.0.0",
|
||||
"private": true,
|
||||
"type": "module",
|
||||
"description": "Set up your GitHub Actions workflow with a specific version of uv",
|
||||
"main": "dist/index.js",
|
||||
"main": "dist/setup/index.cjs",
|
||||
"scripts": {
|
||||
"build": "tsc",
|
||||
"build": "tsc --noEmit",
|
||||
"check": "biome check --write",
|
||||
"package": "ncc build -o dist/setup src/setup-uv.ts && ncc build -o dist/save-cache src/save-cache.ts && ncc build -o dist/update-known-checksums src/update-known-checksums.ts",
|
||||
"test": "jest",
|
||||
"package": "node scripts/build-dist.mjs",
|
||||
"bench:versions": "node scripts/bench-versions-client.mjs",
|
||||
"test:unit": "node --experimental-vm-modules ./node_modules/jest/bin/jest.js",
|
||||
"test": "npm run build && npm run test:unit",
|
||||
"act": "act pull_request -W .github/workflows/test.yml --container-architecture linux/amd64 -s GITHUB_TOKEN=\"$(gh auth token)\"",
|
||||
"update-known-checksums": "RUNNER_TEMP=known_versions node dist/update-known-checksums/index.js src/download/checksum/known-checksums.ts",
|
||||
"all": "npm run build && npm run check && npm run package && npm test"
|
||||
"update-known-checksums": "RUNNER_TEMP=known_versions node dist/update-known-checksums/index.cjs src/download/checksum/known-checksums.ts",
|
||||
"all": "npm run build && npm run check && npm run package && npm run test:unit"
|
||||
},
|
||||
"repository": {
|
||||
"type": "git",
|
||||
@@ -26,25 +29,26 @@
|
||||
"author": "@eifinger",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"@actions/cache": "^4.1.0",
|
||||
"@actions/core": "^1.11.1",
|
||||
"@actions/exec": "^1.1.1",
|
||||
"@actions/glob": "^0.5.0",
|
||||
"@actions/io": "^1.1.3",
|
||||
"@actions/tool-cache": "^2.0.2",
|
||||
"@renovatebot/pep440": "^4.2.1",
|
||||
"@actions/cache": "^6.0.0",
|
||||
"@actions/core": "^3.0.0",
|
||||
"@actions/exec": "^3.0.0",
|
||||
"@actions/glob": "^0.6.1",
|
||||
"@actions/io": "^3.0.2",
|
||||
"@actions/tool-cache": "^4.0.0",
|
||||
"@renovatebot/pep440": "^4.2.2",
|
||||
"smol-toml": "^1.6.0",
|
||||
"undici": "5.28.5"
|
||||
"undici": "^7.24.2"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@biomejs/biome": "2.3.8",
|
||||
"@biomejs/biome": "^2.4.7",
|
||||
"@types/js-yaml": "^4.0.9",
|
||||
"@types/node": "^24.10.1",
|
||||
"@types/node": "^25.5.0",
|
||||
"@types/semver": "^7.7.1",
|
||||
"@vercel/ncc": "^0.38.4",
|
||||
"jest": "^30.2.0",
|
||||
"js-yaml": "^4.1.0",
|
||||
"ts-jest": "^29.4.5",
|
||||
"esbuild": "^0.27.4",
|
||||
"jest": "^30.3.0",
|
||||
"js-yaml": "^4.1.1",
|
||||
"ts-jest": "^29.4.6",
|
||||
"typescript": "^5.9.3"
|
||||
}
|
||||
}
|
||||
|
||||
483
scripts/bench-versions-client.mjs
Normal file
483
scripts/bench-versions-client.mjs
Normal file
@@ -0,0 +1,483 @@
|
||||
import { performance } from "node:perf_hooks";
|
||||
import * as pep440 from "@renovatebot/pep440";
|
||||
import * as semver from "semver";
|
||||
import { ProxyAgent, fetch as undiciFetch } from "undici";
|
||||
|
||||
const DEFAULT_URL =
|
||||
"https://raw.githubusercontent.com/astral-sh/versions/main/v1/uv.ndjson";
|
||||
const DEFAULT_ITERATIONS = 100;
|
||||
const DEFAULT_ARCH = "aarch64";
|
||||
const DEFAULT_PLATFORM = "apple-darwin";
|
||||
|
||||
function getProxyAgent() {
|
||||
const httpProxy = process.env.HTTP_PROXY || process.env.http_proxy;
|
||||
if (httpProxy) {
|
||||
return new ProxyAgent(httpProxy);
|
||||
}
|
||||
|
||||
const httpsProxy = process.env.HTTPS_PROXY || process.env.https_proxy;
|
||||
if (httpsProxy) {
|
||||
return new ProxyAgent(httpsProxy);
|
||||
}
|
||||
|
||||
return undefined;
|
||||
}
|
||||
|
||||
async function fetch(url) {
|
||||
return await undiciFetch(url, {
|
||||
dispatcher: getProxyAgent(),
|
||||
});
|
||||
}
|
||||
|
||||
function parseArgs(argv) {
|
||||
const options = {
|
||||
arch: DEFAULT_ARCH,
|
||||
iterations: DEFAULT_ITERATIONS,
|
||||
platform: DEFAULT_PLATFORM,
|
||||
url: DEFAULT_URL,
|
||||
};
|
||||
|
||||
for (let index = 0; index < argv.length; index += 1) {
|
||||
const arg = argv[index];
|
||||
const next = argv[index + 1];
|
||||
|
||||
if (arg === "--iterations" && next !== undefined) {
|
||||
options.iterations = Number.parseInt(next, 10);
|
||||
index += 1;
|
||||
continue;
|
||||
}
|
||||
|
||||
if (arg === "--url" && next !== undefined) {
|
||||
options.url = next;
|
||||
index += 1;
|
||||
continue;
|
||||
}
|
||||
|
||||
if (arg === "--arch" && next !== undefined) {
|
||||
options.arch = next;
|
||||
index += 1;
|
||||
continue;
|
||||
}
|
||||
|
||||
if (arg === "--platform" && next !== undefined) {
|
||||
options.platform = next;
|
||||
index += 1;
|
||||
}
|
||||
}
|
||||
|
||||
if (!Number.isInteger(options.iterations) || options.iterations <= 0) {
|
||||
throw new Error("--iterations must be a positive integer");
|
||||
}
|
||||
|
||||
return options;
|
||||
}
|
||||
|
||||
function parseVersionLine(line, sourceDescription, lineNumber) {
|
||||
let parsed;
|
||||
try {
|
||||
parsed = JSON.parse(line);
|
||||
} catch (error) {
|
||||
throw new Error(
|
||||
`Failed to parse version data from ${sourceDescription} at line ${lineNumber}: ${error.message}`,
|
||||
);
|
||||
}
|
||||
|
||||
if (
|
||||
typeof parsed !== "object" ||
|
||||
parsed === null ||
|
||||
typeof parsed.version !== "string" ||
|
||||
!Array.isArray(parsed.artifacts)
|
||||
) {
|
||||
throw new Error(
|
||||
`Invalid NDJSON record in ${sourceDescription} at line ${lineNumber}.`,
|
||||
);
|
||||
}
|
||||
|
||||
return parsed;
|
||||
}
|
||||
|
||||
function parseVersionData(data, sourceDescription) {
|
||||
const versions = [];
|
||||
|
||||
for (const [index, line] of data.split("\n").entries()) {
|
||||
const trimmed = line.trim();
|
||||
if (trimmed === "") {
|
||||
continue;
|
||||
}
|
||||
|
||||
versions.push(parseVersionLine(trimmed, sourceDescription, index + 1));
|
||||
}
|
||||
|
||||
if (versions.length === 0) {
|
||||
throw new Error(`No version data found in ${sourceDescription}.`);
|
||||
}
|
||||
|
||||
return versions;
|
||||
}
|
||||
|
||||
async function readEntireResponse(response) {
|
||||
if (response.body === null) {
|
||||
const text = await response.text();
|
||||
return {
|
||||
bytesRead: Buffer.byteLength(text, "utf8"),
|
||||
text,
|
||||
};
|
||||
}
|
||||
|
||||
const reader = response.body.getReader();
|
||||
const decoder = new TextDecoder();
|
||||
const chunks = [];
|
||||
let bytesRead = 0;
|
||||
|
||||
while (true) {
|
||||
const { done, value } = await reader.read();
|
||||
if (done) {
|
||||
chunks.push(decoder.decode());
|
||||
break;
|
||||
}
|
||||
|
||||
bytesRead += value.byteLength;
|
||||
chunks.push(decoder.decode(value, { stream: true }));
|
||||
}
|
||||
|
||||
return {
|
||||
bytesRead,
|
||||
text: chunks.join(""),
|
||||
};
|
||||
}
|
||||
|
||||
async function fetchAllVersions(url) {
|
||||
const response = await fetch(url);
|
||||
if (!response.ok) {
|
||||
throw new Error(
|
||||
`Failed to fetch version data: ${response.status} ${response.statusText}`,
|
||||
);
|
||||
}
|
||||
|
||||
const { bytesRead, text } = await readEntireResponse(response);
|
||||
return {
|
||||
bytesRead,
|
||||
versions: parseVersionData(text, url),
|
||||
};
|
||||
}
|
||||
|
||||
async function streamUntil(url, predicate) {
|
||||
const response = await fetch(url);
|
||||
if (!response.ok) {
|
||||
throw new Error(
|
||||
`Failed to fetch version data: ${response.status} ${response.statusText}`,
|
||||
);
|
||||
}
|
||||
|
||||
if (response.body === null) {
|
||||
const { bytesRead, versions } = await fetchAllVersions(url);
|
||||
return {
|
||||
bytesRead,
|
||||
matchedVersion: versions.find(predicate),
|
||||
};
|
||||
}
|
||||
|
||||
const reader = response.body.getReader();
|
||||
const decoder = new TextDecoder();
|
||||
let bytesRead = 0;
|
||||
let buffer = "";
|
||||
let lineNumber = 0;
|
||||
|
||||
while (true) {
|
||||
const { done, value } = await reader.read();
|
||||
if (done) {
|
||||
buffer += decoder.decode();
|
||||
break;
|
||||
}
|
||||
|
||||
bytesRead += value.byteLength;
|
||||
buffer += decoder.decode(value, { stream: true });
|
||||
|
||||
let newlineIndex = buffer.indexOf("\n");
|
||||
while (newlineIndex !== -1) {
|
||||
const line = buffer.slice(0, newlineIndex);
|
||||
buffer = buffer.slice(newlineIndex + 1);
|
||||
const trimmed = line.trim();
|
||||
|
||||
if (trimmed !== "") {
|
||||
lineNumber += 1;
|
||||
const versionData = parseVersionLine(trimmed, url, lineNumber);
|
||||
if (predicate(versionData)) {
|
||||
await reader.cancel();
|
||||
return { bytesRead, matchedVersion: versionData };
|
||||
}
|
||||
}
|
||||
|
||||
newlineIndex = buffer.indexOf("\n");
|
||||
}
|
||||
}
|
||||
|
||||
if (buffer.trim() !== "") {
|
||||
lineNumber += 1;
|
||||
const versionData = parseVersionLine(buffer.trim(), url, lineNumber);
|
||||
if (predicate(versionData)) {
|
||||
return { bytesRead, matchedVersion: versionData };
|
||||
}
|
||||
}
|
||||
|
||||
return { bytesRead, matchedVersion: undefined };
|
||||
}
|
||||
|
||||
function versionSatisfies(version, versionSpecifier) {
|
||||
return (
|
||||
semver.satisfies(version, versionSpecifier) ||
|
||||
pep440.satisfies(version, versionSpecifier)
|
||||
);
|
||||
}
|
||||
|
||||
function maxSatisfying(versions, versionSpecifier) {
|
||||
const semverMatch = semver.maxSatisfying(versions, versionSpecifier);
|
||||
if (semverMatch !== null) {
|
||||
return semverMatch;
|
||||
}
|
||||
|
||||
return pep440.maxSatisfying(versions, versionSpecifier) ?? undefined;
|
||||
}
|
||||
|
||||
function selectArtifact(artifacts) {
|
||||
if (artifacts.length === 1) {
|
||||
return artifacts[0];
|
||||
}
|
||||
|
||||
const defaultVariant = artifacts.find(
|
||||
(candidate) => candidate.variant === "default",
|
||||
);
|
||||
if (defaultVariant !== undefined) {
|
||||
return defaultVariant;
|
||||
}
|
||||
|
||||
return artifacts[0];
|
||||
}
|
||||
|
||||
async function benchmarkCase(name, expected, implementations, iterations) {
|
||||
const results = {
|
||||
name,
|
||||
new: [],
|
||||
old: [],
|
||||
};
|
||||
|
||||
for (let iteration = 0; iteration < iterations; iteration += 1) {
|
||||
const order = iteration % 2 === 0 ? ["old", "new"] : ["new", "old"];
|
||||
|
||||
for (const label of order) {
|
||||
const implementation = implementations[label];
|
||||
const startedAt = performance.now();
|
||||
const outcome = await implementation.run();
|
||||
const durationMs = performance.now() - startedAt;
|
||||
|
||||
if (outcome.value !== expected) {
|
||||
throw new Error(
|
||||
`${name} ${label} produced ${JSON.stringify(outcome.value)}; expected ${JSON.stringify(expected)}`,
|
||||
);
|
||||
}
|
||||
|
||||
results[label].push({
|
||||
bytesRead: outcome.bytesRead,
|
||||
durationMs,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
return results;
|
||||
}
|
||||
|
||||
function summarize(samples) {
|
||||
const durations = samples
|
||||
.map((sample) => sample.durationMs)
|
||||
.sort((left, right) => left - right);
|
||||
const bytes = samples
|
||||
.map((sample) => sample.bytesRead)
|
||||
.sort((left, right) => left - right);
|
||||
|
||||
const sum = (values) => values.reduce((total, value) => total + value, 0);
|
||||
const percentile = (values, ratio) => {
|
||||
const index = Math.min(
|
||||
values.length - 1,
|
||||
Math.max(0, Math.ceil(values.length * ratio) - 1),
|
||||
);
|
||||
return values[index];
|
||||
};
|
||||
|
||||
return {
|
||||
avgBytes: sum(bytes) / bytes.length,
|
||||
avgMs: sum(durations) / durations.length,
|
||||
maxMs: durations[durations.length - 1],
|
||||
medianMs: percentile(durations, 0.5),
|
||||
minMs: durations[0],
|
||||
p95Ms: percentile(durations, 0.95),
|
||||
};
|
||||
}
|
||||
|
||||
function formatNumber(value, digits = 2) {
|
||||
return value.toFixed(digits);
|
||||
}
|
||||
|
||||
function formatSummary(name, oldSummary, newSummary) {
|
||||
const speedup = oldSummary.avgMs / newSummary.avgMs;
|
||||
const timeReduction =
|
||||
((oldSummary.avgMs - newSummary.avgMs) / oldSummary.avgMs) * 100;
|
||||
const byteReduction =
|
||||
((oldSummary.avgBytes - newSummary.avgBytes) / oldSummary.avgBytes) * 100;
|
||||
|
||||
return [
|
||||
`Scenario: ${name}`,
|
||||
` old avg: ${formatNumber(oldSummary.avgMs)} ms | median: ${formatNumber(oldSummary.medianMs)} ms | p95: ${formatNumber(oldSummary.p95Ms)} ms | avg bytes: ${Math.round(oldSummary.avgBytes)}`,
|
||||
` new avg: ${formatNumber(newSummary.avgMs)} ms | median: ${formatNumber(newSummary.medianMs)} ms | p95: ${formatNumber(newSummary.p95Ms)} ms | avg bytes: ${Math.round(newSummary.avgBytes)}`,
|
||||
` delta: ${formatNumber(timeReduction)}% faster | ${formatNumber(speedup)}x speedup | ${formatNumber(byteReduction)}% fewer bytes read`,
|
||||
].join("\n");
|
||||
}
|
||||
|
||||
async function main() {
|
||||
const options = parseArgs(process.argv.slice(2));
|
||||
console.log(`Preparing benchmark data from ${options.url}`);
|
||||
const baseline = await fetchAllVersions(options.url);
|
||||
const latestVersion = baseline.versions[0]?.version;
|
||||
if (!latestVersion) {
|
||||
throw new Error("No versions found in NDJSON data");
|
||||
}
|
||||
|
||||
const latestArtifact = selectArtifact(
|
||||
baseline.versions[0].artifacts.filter(
|
||||
(candidate) =>
|
||||
candidate.platform === `${options.arch}-${options.platform}`,
|
||||
),
|
||||
);
|
||||
if (!latestArtifact) {
|
||||
throw new Error(
|
||||
`No artifact found for ${options.arch}-${options.platform} in ${latestVersion}`,
|
||||
);
|
||||
}
|
||||
|
||||
const rangeSpecifier = `^${latestVersion.split(".")[0]}.${latestVersion.split(".")[1]}.0`;
|
||||
|
||||
console.log(
|
||||
`Running ${options.iterations} iterations per scenario against ${options.url}`,
|
||||
);
|
||||
console.log(`Latest version: ${latestVersion}`);
|
||||
console.log(`Range benchmark: ${rangeSpecifier}`);
|
||||
console.log(`Artifact benchmark: ${options.arch}-${options.platform}`);
|
||||
console.log("");
|
||||
|
||||
const scenarios = [
|
||||
await benchmarkCase(
|
||||
"latest version",
|
||||
latestVersion,
|
||||
{
|
||||
new: {
|
||||
run: async () => {
|
||||
const { bytesRead, matchedVersion } = await streamUntil(
|
||||
options.url,
|
||||
() => true,
|
||||
);
|
||||
return {
|
||||
bytesRead,
|
||||
value: matchedVersion?.version,
|
||||
};
|
||||
},
|
||||
},
|
||||
old: {
|
||||
run: async () => {
|
||||
const { bytesRead, versions } = await fetchAllVersions(options.url);
|
||||
return {
|
||||
bytesRead,
|
||||
value: versions[0]?.version,
|
||||
};
|
||||
},
|
||||
},
|
||||
},
|
||||
options.iterations,
|
||||
),
|
||||
await benchmarkCase(
|
||||
"highest satisfying range",
|
||||
latestVersion,
|
||||
{
|
||||
new: {
|
||||
run: async () => {
|
||||
const { bytesRead, matchedVersion } = await streamUntil(
|
||||
options.url,
|
||||
(candidate) =>
|
||||
versionSatisfies(candidate.version, rangeSpecifier),
|
||||
);
|
||||
return {
|
||||
bytesRead,
|
||||
value: matchedVersion?.version,
|
||||
};
|
||||
},
|
||||
},
|
||||
old: {
|
||||
run: async () => {
|
||||
const { bytesRead, versions } = await fetchAllVersions(options.url);
|
||||
return {
|
||||
bytesRead,
|
||||
value: maxSatisfying(
|
||||
versions.map((versionData) => versionData.version),
|
||||
rangeSpecifier,
|
||||
),
|
||||
};
|
||||
},
|
||||
},
|
||||
},
|
||||
options.iterations,
|
||||
),
|
||||
await benchmarkCase(
|
||||
"exact version artifact",
|
||||
latestArtifact.url,
|
||||
{
|
||||
new: {
|
||||
run: async () => {
|
||||
const { bytesRead, matchedVersion } = await streamUntil(
|
||||
options.url,
|
||||
(candidate) => candidate.version === latestVersion,
|
||||
);
|
||||
const artifact = matchedVersion
|
||||
? selectArtifact(
|
||||
matchedVersion.artifacts.filter(
|
||||
(candidate) =>
|
||||
candidate.platform ===
|
||||
`${options.arch}-${options.platform}`,
|
||||
),
|
||||
)
|
||||
: undefined;
|
||||
return {
|
||||
bytesRead,
|
||||
value: artifact?.url,
|
||||
};
|
||||
},
|
||||
},
|
||||
old: {
|
||||
run: async () => {
|
||||
const { bytesRead, versions } = await fetchAllVersions(options.url);
|
||||
const versionData = versions.find(
|
||||
(candidate) => candidate.version === latestVersion,
|
||||
);
|
||||
const artifact = selectArtifact(
|
||||
versionData.artifacts.filter(
|
||||
(candidate) =>
|
||||
candidate.platform === `${options.arch}-${options.platform}`,
|
||||
),
|
||||
);
|
||||
return {
|
||||
bytesRead,
|
||||
value: artifact?.url,
|
||||
};
|
||||
},
|
||||
},
|
||||
},
|
||||
options.iterations,
|
||||
),
|
||||
];
|
||||
|
||||
for (const scenario of scenarios) {
|
||||
const oldSummary = summarize(scenario.old);
|
||||
const newSummary = summarize(scenario.new);
|
||||
console.log(formatSummary(scenario.name, oldSummary, newSummary));
|
||||
console.log("");
|
||||
}
|
||||
}
|
||||
|
||||
await main();
|
||||
33
scripts/build-dist.mjs
Normal file
33
scripts/build-dist.mjs
Normal file
@@ -0,0 +1,33 @@
|
||||
import { rm } from "node:fs/promises";
|
||||
import { build } from "esbuild";
|
||||
|
||||
const builds = [
|
||||
{
|
||||
entryPoints: ["src/setup-uv.ts"],
|
||||
outfile: "dist/setup/index.cjs",
|
||||
staleOutfiles: ["dist/setup/index.mjs"],
|
||||
},
|
||||
{
|
||||
entryPoints: ["src/save-cache.ts"],
|
||||
outfile: "dist/save-cache/index.cjs",
|
||||
staleOutfiles: ["dist/save-cache/index.mjs"],
|
||||
},
|
||||
{
|
||||
entryPoints: ["src/update-known-checksums.ts"],
|
||||
outfile: "dist/update-known-checksums/index.cjs",
|
||||
staleOutfiles: ["dist/update-known-checksums/index.mjs"],
|
||||
},
|
||||
];
|
||||
|
||||
for (const { staleOutfiles, ...options } of builds) {
|
||||
await Promise.all(
|
||||
staleOutfiles.map((outfile) => rm(outfile, { force: true })),
|
||||
);
|
||||
await build({
|
||||
bundle: true,
|
||||
format: "cjs",
|
||||
platform: "node",
|
||||
target: "node24",
|
||||
...options,
|
||||
});
|
||||
}
|
||||
@@ -1,5 +1,39 @@
|
||||
// AUTOGENERATED_DO_NOT_EDIT
|
||||
export const KNOWN_CHECKSUMS: { [key: string]: string } = {
|
||||
"aarch64-apple-darwin-0.10.10":
|
||||
"8a09f0ef51ee7f7170731b4cb8bde5bf9ba6da5304f49a7df6cdab42a1f37b5d",
|
||||
"aarch64-pc-windows-msvc-0.10.10":
|
||||
"2c6fe113f14574bc27f085751c68d3485589fcc3c3c64ed85dd1eecc2f87cffc",
|
||||
"aarch64-unknown-linux-gnu-0.10.10":
|
||||
"2b80457b950deda12e8d5dc3b9b7494ac143eae47f1fb11b1c6e5a8495a6421e",
|
||||
"aarch64-unknown-linux-musl-0.10.10":
|
||||
"d08c08b82cdcaf2bd3d928ffe844d3558dda53f90066db6ef9174157cc763252",
|
||||
"arm-unknown-linux-musleabihf-0.10.10":
|
||||
"ccc3c4dd5eeea4b2be829ef9bc0b8d9882389c0f303f7ec5ba668065d57e2673",
|
||||
"armv7-unknown-linux-gnueabihf-0.10.10":
|
||||
"032786622b52f8d0232b5ad16e25342a64f9e43576652db7bf607231021902f3",
|
||||
"armv7-unknown-linux-musleabihf-0.10.10":
|
||||
"f6f67b190eb28b473917c97210f89fd11d9b9393d774acd093ea738fcee68864",
|
||||
"i686-pc-windows-msvc-0.10.10":
|
||||
"980d7ea368cc4883f572bb85c285a647eddfc23539064d2bfaf8fbfefcc2112b",
|
||||
"i686-unknown-linux-gnu-0.10.10":
|
||||
"5260fbef838f8cfec44697064a5cfae08a27c6ab7ed7feab7fc946827e896952",
|
||||
"i686-unknown-linux-musl-0.10.10":
|
||||
"a6683ade964f8d8623098ca0c96b4311d8388b44a56a386cd795974f39fb5bd2",
|
||||
"powerpc64le-unknown-linux-gnu-0.10.10":
|
||||
"78939dc4fc905aca8af4be19b6c6ecc306f04c6ca9f98d144372595d9397fd0d",
|
||||
"riscv64gc-unknown-linux-gnu-0.10.10":
|
||||
"5eff670bf80fce9d9e50df5b4d46c415a9c0324eadf7059d97c76f89ffc33c3f",
|
||||
"s390x-unknown-linux-gnu-0.10.10":
|
||||
"a32d2be5600f7f42f82596ffe9d3115f020974ca7fb4f15251c5625c5481ea5e",
|
||||
"x86_64-apple-darwin-0.10.10":
|
||||
"dd18420591d625f9b4ca2b57a7a6fe3cce43910f02e02d90e47a4101428de14a",
|
||||
"x86_64-pc-windows-msvc-0.10.10":
|
||||
"d31a30f1dfb96e630a08d5a9b3f3f551254b7ed6e9b7e495f46a4232661c7252",
|
||||
"x86_64-unknown-linux-gnu-0.10.10":
|
||||
"3e1027f26ce8c7e4c32e2277a7fed2cb410f2f1f9320d3df97653d40e21f415b",
|
||||
"x86_64-unknown-linux-musl-0.10.10":
|
||||
"74544e8755fbc27559e22e29fd561bdc48f91b8bd8323e760a1130f32433bea4",
|
||||
"aarch64-apple-darwin-0.10.9":
|
||||
"a92f61e9ac9b0f29668c15f56152e4a60143fca148ff5bfadb86718472c3f376",
|
||||
"aarch64-pc-windows-msvc-0.10.9":
|
||||
|
||||
@@ -15,6 +15,7 @@ import {
|
||||
import {
|
||||
getAllVersions as getAllVersionsFromNdjson,
|
||||
getArtifact as getArtifactFromNdjson,
|
||||
getHighestSatisfyingVersion as getHighestSatisfyingVersionFromNdjson,
|
||||
getLatestVersion as getLatestVersionFromNdjson,
|
||||
} from "./versions-client";
|
||||
|
||||
@@ -187,6 +188,17 @@ export async function resolveVersion(
|
||||
return version;
|
||||
}
|
||||
|
||||
if (manifestUrl === undefined && resolutionStrategy === "highest") {
|
||||
const resolvedVersion =
|
||||
await getHighestSatisfyingVersionFromNdjson(version);
|
||||
if (resolvedVersion !== undefined) {
|
||||
core.debug(`Resolved version from NDJSON stream: ${resolvedVersion}`);
|
||||
return resolvedVersion;
|
||||
}
|
||||
|
||||
throw new Error(`No version found for ${version}`);
|
||||
}
|
||||
|
||||
const availableVersions = await getAvailableVersions(manifestUrl);
|
||||
core.debug(`Available versions: ${availableVersions}`);
|
||||
const resolvedVersion =
|
||||
|
||||
@@ -1,4 +1,6 @@
|
||||
import * as core from "@actions/core";
|
||||
import * as pep440 from "@renovatebot/pep440";
|
||||
import * as semver from "semver";
|
||||
import { VERSIONS_NDJSON_URL } from "../utils/constants";
|
||||
import { fetch } from "../utils/fetch";
|
||||
import { selectDefaultVariant } from "./variant-selection";
|
||||
@@ -23,6 +25,8 @@ export interface ArtifactResult {
|
||||
}
|
||||
|
||||
const cachedVersionData = new Map<string, NdjsonVersion[]>();
|
||||
const cachedLatestVersionData = new Map<string, NdjsonVersion>();
|
||||
const cachedVersionLookup = new Map<string, Map<string, NdjsonVersion>>();
|
||||
|
||||
export async function fetchVersionData(
|
||||
url: string = VERSIONS_NDJSON_URL,
|
||||
@@ -34,16 +38,8 @@ export async function fetchVersionData(
|
||||
}
|
||||
|
||||
core.info(`Fetching version data from ${url} ...`);
|
||||
const response = await fetch(url, {});
|
||||
if (!response.ok) {
|
||||
throw new Error(
|
||||
`Failed to fetch version data: ${response.status} ${response.statusText}`,
|
||||
);
|
||||
}
|
||||
|
||||
const body = await response.text();
|
||||
const versions = parseVersionData(body, url);
|
||||
cachedVersionData.set(url, versions);
|
||||
const { versions } = await readVersionData(url);
|
||||
cacheCompleteVersionData(url, versions);
|
||||
return versions;
|
||||
}
|
||||
|
||||
@@ -59,22 +55,7 @@ export function parseVersionData(
|
||||
continue;
|
||||
}
|
||||
|
||||
let parsed: unknown;
|
||||
try {
|
||||
parsed = JSON.parse(trimmed);
|
||||
} catch (error) {
|
||||
throw new Error(
|
||||
`Failed to parse version data from ${sourceDescription} at line ${index + 1}: ${(error as Error).message}`,
|
||||
);
|
||||
}
|
||||
|
||||
if (!isNdjsonVersion(parsed)) {
|
||||
throw new Error(
|
||||
`Invalid NDJSON record in ${sourceDescription} at line ${index + 1}.`,
|
||||
);
|
||||
}
|
||||
|
||||
versions.push(parsed);
|
||||
versions.push(parseVersionLine(trimmed, sourceDescription, index + 1));
|
||||
}
|
||||
|
||||
if (versions.length === 0) {
|
||||
@@ -85,14 +66,23 @@ export function parseVersionData(
|
||||
}
|
||||
|
||||
export async function getLatestVersion(): Promise<string> {
|
||||
const versions = await fetchVersionData();
|
||||
const latestVersion = versions[0]?.version;
|
||||
const cachedVersions = cachedVersionData.get(VERSIONS_NDJSON_URL);
|
||||
const cachedLatestVersion =
|
||||
cachedVersions?.[0] ?? cachedLatestVersionData.get(VERSIONS_NDJSON_URL);
|
||||
if (cachedLatestVersion !== undefined) {
|
||||
core.debug(
|
||||
`Latest version from NDJSON cache: ${cachedLatestVersion.version}`,
|
||||
);
|
||||
return cachedLatestVersion.version;
|
||||
}
|
||||
|
||||
const latestVersion = await findVersionData(() => true);
|
||||
if (!latestVersion) {
|
||||
throw new Error("No versions found in NDJSON data");
|
||||
}
|
||||
|
||||
core.debug(`Latest version from NDJSON: ${latestVersion}`);
|
||||
return latestVersion;
|
||||
core.debug(`Latest version from NDJSON: ${latestVersion.version}`);
|
||||
return latestVersion.version;
|
||||
}
|
||||
|
||||
export async function getAllVersions(): Promise<string[]> {
|
||||
@@ -100,15 +90,24 @@ export async function getAllVersions(): Promise<string[]> {
|
||||
return versions.map((versionData) => versionData.version);
|
||||
}
|
||||
|
||||
export async function getHighestSatisfyingVersion(
|
||||
versionSpecifier: string,
|
||||
url: string = VERSIONS_NDJSON_URL,
|
||||
): Promise<string | undefined> {
|
||||
const matchedVersion = await findVersionData(
|
||||
(candidate) => versionSatisfies(candidate.version, versionSpecifier),
|
||||
url,
|
||||
);
|
||||
|
||||
return matchedVersion?.version;
|
||||
}
|
||||
|
||||
export async function getArtifact(
|
||||
version: string,
|
||||
arch: string,
|
||||
platform: string,
|
||||
): Promise<ArtifactResult | undefined> {
|
||||
const versions = await fetchVersionData();
|
||||
const versionData = versions.find(
|
||||
(candidate) => candidate.version === version,
|
||||
);
|
||||
const versionData = await getVersionData(version);
|
||||
if (!versionData) {
|
||||
core.debug(`Version ${version} not found in NDJSON data`);
|
||||
return undefined;
|
||||
@@ -140,10 +139,14 @@ export async function getArtifact(
|
||||
export function clearCache(url?: string): void {
|
||||
if (url === undefined) {
|
||||
cachedVersionData.clear();
|
||||
cachedLatestVersionData.clear();
|
||||
cachedVersionLookup.clear();
|
||||
return;
|
||||
}
|
||||
|
||||
cachedVersionData.delete(url);
|
||||
cachedLatestVersionData.delete(url);
|
||||
cachedVersionLookup.delete(url);
|
||||
}
|
||||
|
||||
function selectArtifact(
|
||||
@@ -157,6 +160,192 @@ function selectArtifact(
|
||||
);
|
||||
}
|
||||
|
||||
async function getVersionData(
|
||||
version: string,
|
||||
url: string = VERSIONS_NDJSON_URL,
|
||||
): Promise<NdjsonVersion | undefined> {
|
||||
const cachedVersions = cachedVersionData.get(url);
|
||||
if (cachedVersions !== undefined) {
|
||||
return cachedVersions.find((candidate) => candidate.version === version);
|
||||
}
|
||||
|
||||
const cachedVersion = cachedVersionLookup.get(url)?.get(version);
|
||||
if (cachedVersion !== undefined) {
|
||||
return cachedVersion;
|
||||
}
|
||||
|
||||
return await findVersionData(
|
||||
(candidate) => candidate.version === version,
|
||||
url,
|
||||
);
|
||||
}
|
||||
|
||||
async function findVersionData(
|
||||
predicate: (versionData: NdjsonVersion) => boolean,
|
||||
url: string = VERSIONS_NDJSON_URL,
|
||||
): Promise<NdjsonVersion | undefined> {
|
||||
const cachedVersions = cachedVersionData.get(url);
|
||||
if (cachedVersions !== undefined) {
|
||||
return cachedVersions.find(predicate);
|
||||
}
|
||||
|
||||
const { matchedVersion, versions, complete } = await readVersionData(
|
||||
url,
|
||||
predicate,
|
||||
);
|
||||
|
||||
if (complete) {
|
||||
cacheCompleteVersionData(url, versions);
|
||||
}
|
||||
|
||||
return matchedVersion;
|
||||
}
|
||||
|
||||
async function readVersionData(
|
||||
url: string,
|
||||
stopWhen?: (versionData: NdjsonVersion) => boolean,
|
||||
): Promise<{
|
||||
complete: boolean;
|
||||
matchedVersion: NdjsonVersion | undefined;
|
||||
versions: NdjsonVersion[];
|
||||
}> {
|
||||
const response = await fetch(url, {});
|
||||
if (!response.ok) {
|
||||
throw new Error(
|
||||
`Failed to fetch version data: ${response.status} ${response.statusText}`,
|
||||
);
|
||||
}
|
||||
|
||||
if (response.body === null) {
|
||||
const body = await response.text();
|
||||
const versions = parseVersionData(body, url);
|
||||
const matchedVersion = stopWhen
|
||||
? versions.find((candidate) => stopWhen(candidate))
|
||||
: undefined;
|
||||
return { complete: true, matchedVersion, versions };
|
||||
}
|
||||
|
||||
const versions: NdjsonVersion[] = [];
|
||||
let lineNumber = 0;
|
||||
let matchedVersion: NdjsonVersion | undefined;
|
||||
let buffer = "";
|
||||
const decoder = new TextDecoder();
|
||||
const reader = response.body.getReader();
|
||||
|
||||
const processLine = (line: string): boolean => {
|
||||
const trimmed = line.trim();
|
||||
if (trimmed === "") {
|
||||
return false;
|
||||
}
|
||||
|
||||
lineNumber += 1;
|
||||
const versionData = parseVersionLine(trimmed, url, lineNumber);
|
||||
if (versions.length === 0) {
|
||||
cachedLatestVersionData.set(url, versionData);
|
||||
}
|
||||
|
||||
versions.push(versionData);
|
||||
cacheVersion(url, versionData);
|
||||
|
||||
if (stopWhen?.(versionData) === true) {
|
||||
matchedVersion = versionData;
|
||||
return true;
|
||||
}
|
||||
|
||||
return false;
|
||||
};
|
||||
|
||||
while (true) {
|
||||
const { done, value } = await reader.read();
|
||||
if (done) {
|
||||
buffer += decoder.decode();
|
||||
break;
|
||||
}
|
||||
|
||||
buffer += decoder.decode(value, { stream: true });
|
||||
let newlineIndex = buffer.indexOf("\n");
|
||||
while (newlineIndex !== -1) {
|
||||
const line = buffer.slice(0, newlineIndex);
|
||||
buffer = buffer.slice(newlineIndex + 1);
|
||||
|
||||
if (processLine(line)) {
|
||||
await reader.cancel();
|
||||
return { complete: false, matchedVersion, versions };
|
||||
}
|
||||
|
||||
newlineIndex = buffer.indexOf("\n");
|
||||
}
|
||||
}
|
||||
|
||||
if (buffer.trim() !== "" && processLine(buffer)) {
|
||||
return { complete: true, matchedVersion, versions };
|
||||
}
|
||||
|
||||
if (versions.length === 0) {
|
||||
throw new Error(`No version data found in ${url}.`);
|
||||
}
|
||||
|
||||
return { complete: true, matchedVersion, versions };
|
||||
}
|
||||
|
||||
function cacheCompleteVersionData(
|
||||
url: string,
|
||||
versions: NdjsonVersion[],
|
||||
): void {
|
||||
cachedVersionData.set(url, versions);
|
||||
|
||||
if (versions[0] !== undefined) {
|
||||
cachedLatestVersionData.set(url, versions[0]);
|
||||
}
|
||||
|
||||
const versionLookup = new Map<string, NdjsonVersion>();
|
||||
for (const versionData of versions) {
|
||||
versionLookup.set(versionData.version, versionData);
|
||||
}
|
||||
|
||||
cachedVersionLookup.set(url, versionLookup);
|
||||
}
|
||||
|
||||
function cacheVersion(url: string, versionData: NdjsonVersion): void {
|
||||
let versionLookup = cachedVersionLookup.get(url);
|
||||
if (versionLookup === undefined) {
|
||||
versionLookup = new Map<string, NdjsonVersion>();
|
||||
cachedVersionLookup.set(url, versionLookup);
|
||||
}
|
||||
|
||||
versionLookup.set(versionData.version, versionData);
|
||||
}
|
||||
|
||||
function parseVersionLine(
|
||||
line: string,
|
||||
sourceDescription: string,
|
||||
lineNumber: number,
|
||||
): NdjsonVersion {
|
||||
let parsed: unknown;
|
||||
try {
|
||||
parsed = JSON.parse(line);
|
||||
} catch (error) {
|
||||
throw new Error(
|
||||
`Failed to parse version data from ${sourceDescription} at line ${lineNumber}: ${(error as Error).message}`,
|
||||
);
|
||||
}
|
||||
|
||||
if (!isNdjsonVersion(parsed)) {
|
||||
throw new Error(
|
||||
`Invalid NDJSON record in ${sourceDescription} at line ${lineNumber}.`,
|
||||
);
|
||||
}
|
||||
|
||||
return parsed;
|
||||
}
|
||||
|
||||
function versionSatisfies(version: string, versionSpecifier: string): boolean {
|
||||
return (
|
||||
semver.satisfies(version, versionSpecifier) ||
|
||||
pep440.satisfies(version, versionSpecifier)
|
||||
);
|
||||
}
|
||||
|
||||
function isNdjsonVersion(value: unknown): value is NdjsonVersion {
|
||||
if (!isRecord(value)) {
|
||||
return false;
|
||||
|
||||
@@ -38,6 +38,8 @@ import {
|
||||
} from "./utils/platforms";
|
||||
import { getUvVersionFromFile } from "./version/resolve";
|
||||
|
||||
const sourceDir = __dirname;
|
||||
|
||||
async function getPythonVersion(): Promise<string> {
|
||||
if (pythonVersion !== "") {
|
||||
return pythonVersion;
|
||||
@@ -308,7 +310,7 @@ function setCacheDir(): void {
|
||||
|
||||
function addMatchers(): void {
|
||||
if (addProblemMatchers) {
|
||||
const matchersPath = path.join(__dirname, `..${path.sep}..`, ".github");
|
||||
const matchersPath = path.join(sourceDir, "..", "..", ".github");
|
||||
core.info(`##[add-matcher]${path.join(matchersPath, "python.json")}`);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -18,7 +18,7 @@ async function run(): Promise<void> {
|
||||
const checksumFilePath = process.argv.slice(2)[0];
|
||||
if (!checksumFilePath) {
|
||||
throw new Error(
|
||||
"Missing checksum file path. Usage: node dist/update-known-checksums/index.js <checksum-file-path>",
|
||||
"Missing checksum file path. Usage: node dist/update-known-checksums/index.cjs <checksum-file-path>",
|
||||
);
|
||||
}
|
||||
|
||||
|
||||
@@ -1,12 +1,12 @@
|
||||
{
|
||||
"compilerOptions": {
|
||||
"esModuleInterop": true /* Enables emit interoperability between CommonJS and ES Modules via creation of namespace objects for all imports. Implies 'allowSyntheticDefaultImports'. */,
|
||||
"module": "nodenext" /* Specify module code generation: 'none', 'commonjs', 'amd', 'system', 'umd', 'es2015', or 'ESNext'. */,
|
||||
"noImplicitAny": true /* Raise error on expressions and declarations with an implied 'any' type. */,
|
||||
"outDir": "./lib" /* Redirect output structure to the directory. */,
|
||||
"rootDir": "./src" /* Specify the root directory of input files. Use to control the output directory structure with --outDir. */,
|
||||
"strict": true /* Enable all strict type-checking options. */,
|
||||
"target": "ES2022" /* Specify ECMAScript target version: 'ES3' (default), 'ES5', 'ES2015', 'ES2016', 'ES2017', 'ES2018', 'ES2019' or 'ESNEXT'. */
|
||||
"esModuleInterop": true,
|
||||
"isolatedModules": true,
|
||||
"module": "esnext",
|
||||
"moduleResolution": "bundler",
|
||||
"noImplicitAny": true,
|
||||
"strict": true,
|
||||
"target": "ES2022"
|
||||
},
|
||||
"exclude": ["node_modules", "**/*.test.ts"]
|
||||
"include": ["src/**/*.ts"]
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user