mirror of
https://github.com/actions/setup-python.git
synced 2026-11-20 03:33:06 +00:00
Compare commits
1 Commits
3892123fbe
...
dependabot
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
41a839d88b |
26
.github/workflows/test-python.yml
vendored
26
.github/workflows/test-python.yml
vendored
@@ -61,32 +61,6 @@ jobs:
|
||||
- name: Run simple code
|
||||
run: python -c 'import math; print(math.factorial(5))'
|
||||
|
||||
setup-versions-via-mirror-input:
|
||||
name: 'Setup via explicit mirror input: ${{ matrix.os }}'
|
||||
runs-on: ${{ matrix.os }}
|
||||
strategy:
|
||||
fail-fast: false
|
||||
matrix:
|
||||
os: [ubuntu-latest, windows-latest, macos-latest]
|
||||
steps:
|
||||
- name: Checkout
|
||||
uses: actions/checkout@v6
|
||||
|
||||
# The refs/heads/ form serves the same manifest as the default mirror and
|
||||
# exercises the refs/heads/{branch} -> {branch} parsing on the API path.
|
||||
# check-latest forces a manifest fetch even though 3.12 is preinstalled,
|
||||
# so the job actually contacts the mirror instead of short-circuiting on
|
||||
# the tool cache.
|
||||
- name: setup-python with explicit mirror
|
||||
uses: ./
|
||||
with:
|
||||
python-version: 3.12
|
||||
check-latest: true
|
||||
mirror: https://raw.githubusercontent.com/actions/python-versions/refs/heads/main
|
||||
|
||||
- name: Run simple code
|
||||
run: python -c 'import sys; print(sys.version)'
|
||||
|
||||
setup-versions-from-file:
|
||||
name: Setup ${{ matrix.python }} ${{ matrix.os }} version file
|
||||
runs-on: ${{ matrix.os }}
|
||||
|
||||
2
.licenses/npm/undici.dep.yml
generated
2
.licenses/npm/undici.dep.yml
generated
@@ -1,6 +1,6 @@
|
||||
---
|
||||
name: undici
|
||||
version: 6.29.0
|
||||
version: 6.28.0
|
||||
type: npm
|
||||
summary: An HTTP/1.1 client, written from scratch for Node.js
|
||||
homepage: https://undici.nodejs.org
|
||||
|
||||
@@ -1,590 +0,0 @@
|
||||
import {jest, describe, it, expect, beforeEach} from '@jest/globals';
|
||||
|
||||
// Inputs are read lazily by install-python.ts, so each test can set them
|
||||
// before invoking the function under test.
|
||||
const inputs: Record<string, string> = {};
|
||||
|
||||
// Mock @actions/http-client
|
||||
jest.unstable_mockModule('@actions/http-client', () => ({
|
||||
HttpClient: jest.fn().mockImplementation(() => ({
|
||||
getJson: jest.fn()
|
||||
})),
|
||||
HttpClientError: class HttpClientError extends Error {},
|
||||
HttpCodes: {
|
||||
OK: 200,
|
||||
NotFound: 404,
|
||||
InternalServerError: 500
|
||||
}
|
||||
}));
|
||||
|
||||
// Mock @actions/cache (needed transitively by utils.ts)
|
||||
jest.unstable_mockModule('@actions/cache', () => ({
|
||||
saveCache: jest.fn(),
|
||||
restoreCache: jest.fn(),
|
||||
isFeatureAvailable: jest.fn()
|
||||
}));
|
||||
|
||||
// Mock @actions/tool-cache
|
||||
jest.unstable_mockModule('@actions/tool-cache', () => ({
|
||||
getManifestFromRepo: jest.fn(),
|
||||
downloadTool: jest.fn(),
|
||||
extractTar: jest.fn(),
|
||||
extractZip: jest.fn(),
|
||||
HTTPError: class HTTPError extends Error {}
|
||||
}));
|
||||
|
||||
// Mock @actions/core (needed by install-python.ts)
|
||||
jest.unstable_mockModule('@actions/core', () => ({
|
||||
info: jest.fn(),
|
||||
warning: jest.fn(),
|
||||
debug: jest.fn(),
|
||||
error: jest.fn(),
|
||||
notice: jest.fn(),
|
||||
setFailed: jest.fn(),
|
||||
setOutput: jest.fn(),
|
||||
getInput: jest.fn(),
|
||||
getBooleanInput: jest.fn(),
|
||||
getMultilineInput: jest.fn(),
|
||||
addPath: jest.fn(),
|
||||
exportVariable: jest.fn(),
|
||||
saveState: jest.fn(),
|
||||
getState: jest.fn(),
|
||||
setSecret: jest.fn(),
|
||||
isDebug: jest.fn(() => false),
|
||||
startGroup: jest.fn(),
|
||||
endGroup: jest.fn(),
|
||||
group: jest.fn((_name: string, fn: () => Promise<unknown>) => fn()),
|
||||
toPlatformPath: jest.fn((p: string) => p),
|
||||
toWin32Path: jest.fn((p: string) => p),
|
||||
toPosixPath: jest.fn((p: string) => p)
|
||||
}));
|
||||
|
||||
// Mock @actions/exec (needed by install-python.ts)
|
||||
jest.unstable_mockModule('@actions/exec', () => ({
|
||||
exec: jest.fn(),
|
||||
getExecOutput: jest.fn()
|
||||
}));
|
||||
|
||||
// Import real utils BEFORE mock registration to get real function references
|
||||
const realUtils = await import('../src/utils.js');
|
||||
|
||||
// Pin the platform so the download/extract assertions below behave the same
|
||||
// on every runner OS.
|
||||
jest.unstable_mockModule('../src/utils.js', () => ({
|
||||
...realUtils,
|
||||
IS_WINDOWS: false,
|
||||
IS_LINUX: false
|
||||
}));
|
||||
|
||||
// Dynamic imports after mocking
|
||||
const core = await import('@actions/core');
|
||||
const httpm = await import('@actions/http-client');
|
||||
const tc = await import('@actions/tool-cache');
|
||||
const {
|
||||
getManifestUrl,
|
||||
getManifest,
|
||||
getManifestFromRepo,
|
||||
getManifestFromURL,
|
||||
resolveRepoCoords,
|
||||
isMirrorCustomized,
|
||||
installCpythonFromRelease
|
||||
} = await import('../src/install-python.js');
|
||||
|
||||
const DEFAULT_MIRROR =
|
||||
'https://raw.githubusercontent.com/actions/python-versions/main';
|
||||
|
||||
const mockManifest = [
|
||||
{
|
||||
version: '1.0.0',
|
||||
stable: true,
|
||||
files: [
|
||||
{
|
||||
filename: 'tool-v1.0.0-linux-x64.tar.gz',
|
||||
platform: 'linux',
|
||||
arch: 'x64',
|
||||
download_url: 'https://example.com/tool-v1.0.0-linux-x64.tar.gz'
|
||||
}
|
||||
]
|
||||
}
|
||||
];
|
||||
|
||||
function setInputs(values: Record<string, string>) {
|
||||
Object.assign(inputs, values);
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
jest.resetAllMocks();
|
||||
for (const key of Object.keys(inputs)) {
|
||||
delete inputs[key];
|
||||
}
|
||||
(core.getInput as jest.Mock<any>).mockImplementation(
|
||||
(name: string) => inputs[name] ?? ''
|
||||
);
|
||||
});
|
||||
|
||||
describe('getManifestUrl', () => {
|
||||
it('defaults to the actions/python-versions manifest', () => {
|
||||
expect(getManifestUrl()).toBe(`${DEFAULT_MIRROR}/versions-manifest.json`);
|
||||
});
|
||||
|
||||
it('appends versions-manifest.json to a custom mirror', () => {
|
||||
setInputs({mirror: 'https://mirror.example/py'});
|
||||
expect(getManifestUrl()).toBe(
|
||||
'https://mirror.example/py/versions-manifest.json'
|
||||
);
|
||||
});
|
||||
|
||||
it('strips trailing slashes from the mirror', () => {
|
||||
setInputs({mirror: 'https://mirror.example/py///'});
|
||||
expect(getManifestUrl()).toBe(
|
||||
'https://mirror.example/py/versions-manifest.json'
|
||||
);
|
||||
});
|
||||
|
||||
it('throws on a mirror that is not a valid URL', () => {
|
||||
setInputs({mirror: 'not a url'});
|
||||
expect(() => getManifestUrl()).toThrow(/Invalid 'mirror' URL/);
|
||||
});
|
||||
|
||||
it('keeps throwing the same error when called repeatedly', () => {
|
||||
setInputs({mirror: 'not a url'});
|
||||
expect(() => getManifestUrl()).toThrow(/Invalid 'mirror' URL/);
|
||||
// Memoized, so the second call must not silently succeed or change shape —
|
||||
// find-python.ts calls this while building the "version not found" message.
|
||||
expect(() => getManifestUrl()).toThrow(/Invalid 'mirror' URL/);
|
||||
});
|
||||
|
||||
it('treats an invalid mirror as fatal on the auth path too', async () => {
|
||||
// getManifestUrl() throws on a bad mirror; the auth resolution must agree
|
||||
// rather than swallow the error and quietly skip the mirror-token branch.
|
||||
setInputs({'mirror-token': 'MTOK', mirror: 'not a url'});
|
||||
(tc.downloadTool as jest.Mock<any>).mockResolvedValue('/tmp/py.tgz');
|
||||
(tc.extractTar as jest.Mock<any>).mockResolvedValue('/tmp/extracted');
|
||||
|
||||
const release = {
|
||||
version: '3.12.0',
|
||||
stable: true,
|
||||
files: [
|
||||
{
|
||||
filename: 'python-3.12.0-linux-x64.tar.gz',
|
||||
platform: 'linux',
|
||||
arch: 'x64',
|
||||
download_url: 'https://cdn.example/py.tar.gz'
|
||||
}
|
||||
]
|
||||
} as any;
|
||||
|
||||
await expect(installCpythonFromRelease(release)).rejects.toThrow(
|
||||
/Invalid 'mirror' URL/
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
describe('isMirrorCustomized', () => {
|
||||
it('is false when the mirror input is empty', () => {
|
||||
expect(isMirrorCustomized()).toBe(false);
|
||||
});
|
||||
|
||||
it('is false when the mirror input equals the default', () => {
|
||||
// action.yml gives `mirror` this exact default, so getInput() returns it on
|
||||
// every run where the user did not set one. The PyPy/GraalPy warning must
|
||||
// not fire in that case.
|
||||
setInputs({mirror: DEFAULT_MIRROR});
|
||||
expect(isMirrorCustomized()).toBe(false);
|
||||
});
|
||||
|
||||
it('is false when the mirror input is the default with trailing slashes', () => {
|
||||
setInputs({mirror: `${DEFAULT_MIRROR}///`});
|
||||
expect(isMirrorCustomized()).toBe(false);
|
||||
});
|
||||
|
||||
it('is true when the mirror input is a custom URL', () => {
|
||||
setInputs({mirror: 'https://mirror.example/py'});
|
||||
expect(isMirrorCustomized()).toBe(true);
|
||||
});
|
||||
});
|
||||
|
||||
describe('resolveRepoCoords', () => {
|
||||
it('warns and returns null for a raw.githubusercontent.com mirror with a slash in the branch', () => {
|
||||
setInputs({
|
||||
mirror: 'https://raw.githubusercontent.com/foo/bar/feature/riscv'
|
||||
});
|
||||
|
||||
expect(resolveRepoCoords()).toBeNull();
|
||||
expect(core.warning).toHaveBeenCalledWith(
|
||||
expect.stringMatching(/Branch names containing '\/' are not supported/)
|
||||
);
|
||||
});
|
||||
|
||||
it('parses the refs/heads/{branch} form to the bare branch without warning', () => {
|
||||
setInputs({
|
||||
mirror:
|
||||
'https://raw.githubusercontent.com/actions/python-versions/refs/heads/main'
|
||||
});
|
||||
|
||||
expect(resolveRepoCoords()).toEqual({
|
||||
owner: 'actions',
|
||||
repo: 'python-versions',
|
||||
branch: 'main'
|
||||
});
|
||||
// refs/heads/main is a valid single branch, so it must route through the
|
||||
// API path and never hit the slash-branch warning.
|
||||
expect(core.warning).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('does not warn for a non-GitHub mirror', () => {
|
||||
setInputs({mirror: 'https://mirror.example/py'});
|
||||
|
||||
expect(resolveRepoCoords()).toBeNull();
|
||||
expect(core.warning).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
|
||||
describe('getManifestFromRepo mirror resolution', () => {
|
||||
it('resolves the default mirror to actions/python-versions@main with token', async () => {
|
||||
setInputs({token: 'TKN'});
|
||||
(tc.getManifestFromRepo as jest.Mock<any>).mockResolvedValue(mockManifest);
|
||||
|
||||
await getManifestFromRepo();
|
||||
|
||||
expect(tc.getManifestFromRepo).toHaveBeenCalledWith(
|
||||
'actions',
|
||||
'python-versions',
|
||||
'token TKN',
|
||||
'main'
|
||||
);
|
||||
});
|
||||
|
||||
it('extracts owner/repo/branch from a custom raw.githubusercontent.com mirror', async () => {
|
||||
setInputs({
|
||||
token: 'TKN',
|
||||
mirror: 'https://raw.githubusercontent.com/foo/bar/dev'
|
||||
});
|
||||
(tc.getManifestFromRepo as jest.Mock<any>).mockResolvedValue(mockManifest);
|
||||
|
||||
await getManifestFromRepo();
|
||||
|
||||
expect(tc.getManifestFromRepo).toHaveBeenCalledWith(
|
||||
'foo',
|
||||
'bar',
|
||||
'token TKN',
|
||||
'dev'
|
||||
);
|
||||
});
|
||||
|
||||
it('strips a trailing slash before extracting the branch', async () => {
|
||||
setInputs({
|
||||
token: 'TKN',
|
||||
mirror: 'https://raw.githubusercontent.com/foo/bar/main/'
|
||||
});
|
||||
(tc.getManifestFromRepo as jest.Mock<any>).mockResolvedValue(mockManifest);
|
||||
|
||||
await getManifestFromRepo();
|
||||
|
||||
expect(tc.getManifestFromRepo).toHaveBeenCalledWith(
|
||||
'foo',
|
||||
'bar',
|
||||
'token TKN',
|
||||
'main'
|
||||
);
|
||||
});
|
||||
|
||||
it('resolves the refs/heads/{branch} form to the bare branch for the API', async () => {
|
||||
setInputs({
|
||||
token: 'TKN',
|
||||
mirror: 'https://raw.githubusercontent.com/foo/bar/refs/heads/main'
|
||||
});
|
||||
(tc.getManifestFromRepo as jest.Mock<any>).mockResolvedValue(mockManifest);
|
||||
|
||||
await getManifestFromRepo();
|
||||
|
||||
// The GitHub tree API takes a bare branch, so the refs/heads/ prefix must
|
||||
// be stripped rather than passed through as part of the branch name.
|
||||
expect(tc.getManifestFromRepo).toHaveBeenCalledWith(
|
||||
'foo',
|
||||
'bar',
|
||||
'token TKN',
|
||||
'main'
|
||||
);
|
||||
});
|
||||
|
||||
it('returns null for a non-GitHub mirror so the caller uses the raw URL', () => {
|
||||
setInputs({mirror: 'https://mirror.example/py'});
|
||||
expect(resolveRepoCoords()).toBeNull();
|
||||
expect(tc.getManifestFromRepo).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('prefers mirror-token over token for the GitHub API call', async () => {
|
||||
setInputs({
|
||||
token: 'TKN',
|
||||
'mirror-token': 'MTOK',
|
||||
mirror: 'https://raw.githubusercontent.com/foo/bar/main'
|
||||
});
|
||||
(tc.getManifestFromRepo as jest.Mock<any>).mockResolvedValue(mockManifest);
|
||||
|
||||
await getManifestFromRepo();
|
||||
|
||||
// The API requires the `token ` prefix, and naming a repo mirror is explicit intent to
|
||||
// read that repo, so mirror-token is prefixed here even though downloads send it verbatim.
|
||||
expect(tc.getManifestFromRepo).toHaveBeenCalledWith(
|
||||
'foo',
|
||||
'bar',
|
||||
'token MTOK',
|
||||
'main'
|
||||
);
|
||||
});
|
||||
|
||||
it('sends no auth when neither token nor mirror-token is set', async () => {
|
||||
(tc.getManifestFromRepo as jest.Mock<any>).mockResolvedValue(mockManifest);
|
||||
|
||||
await getManifestFromRepo();
|
||||
|
||||
expect(tc.getManifestFromRepo).toHaveBeenCalledWith(
|
||||
'actions',
|
||||
'python-versions',
|
||||
undefined,
|
||||
'main'
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
describe('getManifestFromURL mirror resolution', () => {
|
||||
it('fetches {mirror}/versions-manifest.json without auth when no mirror-token is set', async () => {
|
||||
setInputs({token: 'TKN', mirror: 'https://mirror.example/py'});
|
||||
const getJson = jest.fn(async () => ({result: mockManifest}));
|
||||
(httpm.HttpClient as jest.Mock<any>).mockImplementation(() => ({getJson}));
|
||||
|
||||
await getManifestFromURL();
|
||||
|
||||
// `token` must not reach a non-GitHub mirror.
|
||||
expect(getJson).toHaveBeenCalledWith(
|
||||
'https://mirror.example/py/versions-manifest.json',
|
||||
undefined
|
||||
);
|
||||
});
|
||||
|
||||
it('sends mirror-token verbatim on the manifest fetch', async () => {
|
||||
setInputs({
|
||||
token: 'TKN',
|
||||
'mirror-token': 'Bearer MTOK',
|
||||
mirror: 'https://mirror.example/py'
|
||||
});
|
||||
const getJson = jest.fn(async () => ({result: mockManifest}));
|
||||
(httpm.HttpClient as jest.Mock<any>).mockImplementation(() => ({getJson}));
|
||||
|
||||
await getManifestFromURL();
|
||||
|
||||
expect(getJson).toHaveBeenCalledWith(
|
||||
'https://mirror.example/py/versions-manifest.json',
|
||||
{authorization: 'Bearer MTOK'}
|
||||
);
|
||||
});
|
||||
|
||||
it('sends token as a prefixed header for a GitHub-hosted raw manifest', async () => {
|
||||
// A slash-branch URL genuinely falls to the direct-URL path (it does not
|
||||
// match the {owner}/{repo}/{branch} shape). raw.githubusercontent.com is a
|
||||
// GitHub host, so the token is still attached here — contradicting any
|
||||
// claim that the fallback fetch is anonymous.
|
||||
setInputs({
|
||||
token: 'TKN',
|
||||
mirror: 'https://raw.githubusercontent.com/foo/bar/feature/riscv'
|
||||
});
|
||||
const getJson = jest.fn(async () => ({result: mockManifest}));
|
||||
(httpm.HttpClient as jest.Mock<any>).mockImplementation(() => ({getJson}));
|
||||
|
||||
await getManifestFromURL();
|
||||
|
||||
expect(getJson).toHaveBeenCalledWith(
|
||||
'https://raw.githubusercontent.com/foo/bar/feature/riscv/versions-manifest.json',
|
||||
{authorization: 'token TKN'}
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
describe('getManifest source routing', () => {
|
||||
it('skips the GitHub API entirely for a non-GitHub mirror', async () => {
|
||||
setInputs({mirror: 'https://mirror.example/py'});
|
||||
const getJson = jest.fn(async () => ({result: mockManifest}));
|
||||
(httpm.HttpClient as jest.Mock<any>).mockImplementation(() => ({getJson}));
|
||||
|
||||
await expect(getManifest()).resolves.toEqual(mockManifest);
|
||||
|
||||
// Routing straight to the URL fetch avoids 3 retries with backoff on a
|
||||
// call that could never succeed.
|
||||
expect(tc.getManifestFromRepo).not.toHaveBeenCalled();
|
||||
expect(getJson).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it('uses the GitHub API for a repo mirror without touching the raw URL', async () => {
|
||||
setInputs({token: 'TKN'});
|
||||
(tc.getManifestFromRepo as jest.Mock<any>).mockResolvedValue(mockManifest);
|
||||
const getJson = jest.fn(async () => ({result: mockManifest}));
|
||||
(httpm.HttpClient as jest.Mock<any>).mockImplementation(() => ({getJson}));
|
||||
|
||||
await expect(getManifest()).resolves.toEqual(mockManifest);
|
||||
|
||||
expect(tc.getManifestFromRepo).toHaveBeenCalledTimes(1);
|
||||
expect(getJson).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
|
||||
describe('installCpythonFromRelease auth gating', () => {
|
||||
const makeRelease = (downloadUrl: string) =>
|
||||
({
|
||||
version: '3.12.0',
|
||||
stable: true,
|
||||
release_url: '',
|
||||
files: [
|
||||
{
|
||||
filename: 'python-3.12.0-linux-x64.tar.gz',
|
||||
platform: 'linux',
|
||||
platform_version: '',
|
||||
arch: 'x64',
|
||||
download_url: downloadUrl
|
||||
}
|
||||
]
|
||||
}) as any;
|
||||
|
||||
// Returns the auth argument tc.downloadTool was called with.
|
||||
async function downloadAuthFor(downloadUrl: string) {
|
||||
(tc.downloadTool as jest.Mock<any>).mockResolvedValue('/tmp/py.tgz');
|
||||
(tc.extractTar as jest.Mock<any>).mockResolvedValue('/tmp/extracted');
|
||||
|
||||
await installCpythonFromRelease(makeRelease(downloadUrl));
|
||||
|
||||
const call = (tc.downloadTool as jest.Mock<any>).mock.calls[0];
|
||||
expect(call[0]).toBe(downloadUrl);
|
||||
return call[2];
|
||||
}
|
||||
|
||||
it('forwards token to github.com download URLs', async () => {
|
||||
setInputs({token: 'TKN'});
|
||||
await expect(
|
||||
downloadAuthFor(
|
||||
'https://github.com/actions/python-versions/releases/download/3.12.0-x/python-3.12.0-linux-x64.tar.gz'
|
||||
)
|
||||
).resolves.toBe('token TKN');
|
||||
});
|
||||
|
||||
it('forwards token to api.github.com download URLs', async () => {
|
||||
setInputs({token: 'TKN'});
|
||||
await expect(
|
||||
downloadAuthFor('https://api.github.com/repos/x/y/tarball/main')
|
||||
).resolves.toBe('token TKN');
|
||||
});
|
||||
|
||||
it('forwards token to *.githubusercontent.com download URLs', async () => {
|
||||
setInputs({token: 'TKN'});
|
||||
await expect(
|
||||
downloadAuthFor('https://objects.githubusercontent.com/x/python.tar.gz')
|
||||
).resolves.toBe('token TKN');
|
||||
});
|
||||
|
||||
it('does NOT forward token to a non-GitHub download URL', async () => {
|
||||
setInputs({token: 'TKN', mirror: 'https://cdn.example'});
|
||||
await expect(
|
||||
downloadAuthFor('https://cdn.example/py.tar.gz')
|
||||
).resolves.toBeUndefined();
|
||||
});
|
||||
|
||||
it('does NOT forward token to a lookalike host', async () => {
|
||||
setInputs({token: 'TKN', mirror: 'https://evil-github.com'});
|
||||
await expect(
|
||||
downloadAuthFor('https://evil-github.com/py.tar.gz')
|
||||
).resolves.toBeUndefined();
|
||||
});
|
||||
|
||||
it('forwards mirror-token verbatim to the mirror host', async () => {
|
||||
setInputs({
|
||||
token: 'TKN',
|
||||
'mirror-token': 'Bearer MTOK',
|
||||
mirror: 'https://cdn.example'
|
||||
});
|
||||
await expect(
|
||||
downloadAuthFor('https://cdn.example/py.tar.gz')
|
||||
).resolves.toBe('Bearer MTOK');
|
||||
});
|
||||
|
||||
it('withholds mirror-token from a same-host download URL on a different scheme', async () => {
|
||||
setInputs({
|
||||
'mirror-token': 'Bearer MTOK',
|
||||
mirror: 'https://cdn.example'
|
||||
});
|
||||
// The mirror is https, but the manifest points a download_url at http on
|
||||
// the same host. Matching on origin (scheme + host + port) rather than host
|
||||
// alone keeps the token from going out in cleartext.
|
||||
await expect(
|
||||
downloadAuthFor('http://cdn.example/py.tar.gz')
|
||||
).resolves.toBeUndefined();
|
||||
});
|
||||
|
||||
it('withholds mirror-token from a same-host download URL on a different port', async () => {
|
||||
setInputs({
|
||||
'mirror-token': 'Bearer MTOK',
|
||||
mirror: 'https://cdn.example'
|
||||
});
|
||||
// Different port is a different origin, so the nominated credential must
|
||||
// not follow.
|
||||
await expect(
|
||||
downloadAuthFor('https://cdn.example:8443/py.tar.gz')
|
||||
).resolves.toBeUndefined();
|
||||
});
|
||||
|
||||
it('sends mirror-token to a same-origin download URL on an explicit port', async () => {
|
||||
setInputs({
|
||||
'mirror-token': 'Bearer MTOK',
|
||||
mirror: 'https://cdn.example:8443'
|
||||
});
|
||||
await expect(
|
||||
downloadAuthFor('https://cdn.example:8443/py.tar.gz')
|
||||
).resolves.toBe('Bearer MTOK');
|
||||
});
|
||||
|
||||
it('withholds mirror-token from an incidental GitHub host and uses token there', async () => {
|
||||
setInputs({
|
||||
token: 'TKN',
|
||||
'mirror-token': 'MTOK',
|
||||
mirror: 'https://cdn.example'
|
||||
});
|
||||
// A manifest hosted on the private mirror may still point release assets at
|
||||
// GitHub; the private credential must not follow them there.
|
||||
await expect(
|
||||
downloadAuthFor('https://objects.githubusercontent.com/x/python.tar.gz')
|
||||
).resolves.toBe('token TKN');
|
||||
});
|
||||
|
||||
it('withholds mirror-token from a GitHub host when no token is set', async () => {
|
||||
setInputs({'mirror-token': 'MTOK', mirror: 'https://cdn.example'});
|
||||
await expect(
|
||||
downloadAuthFor('https://objects.githubusercontent.com/x/python.tar.gz')
|
||||
).resolves.toBeUndefined();
|
||||
});
|
||||
|
||||
it('withholds mirror-token from a third host that is neither the mirror nor GitHub', async () => {
|
||||
setInputs({
|
||||
token: 'TKN',
|
||||
'mirror-token': 'MTOK',
|
||||
mirror: 'https://cdn.example'
|
||||
});
|
||||
await expect(
|
||||
downloadAuthFor('https://other.example/py.tar.gz')
|
||||
).resolves.toBeUndefined();
|
||||
});
|
||||
|
||||
it('uses mirror-token for a GitHub mirror host when it is the nominated host', async () => {
|
||||
setInputs({
|
||||
token: 'TKN',
|
||||
'mirror-token': 'token MTOK',
|
||||
mirror: 'https://raw.githubusercontent.com/foo/bar/main'
|
||||
});
|
||||
await expect(
|
||||
downloadAuthFor('https://raw.githubusercontent.com/foo/bar/py.tar.gz')
|
||||
).resolves.toBe('token MTOK');
|
||||
});
|
||||
|
||||
it('sends no auth when no tokens are configured', async () => {
|
||||
await expect(
|
||||
downloadAuthFor('https://github.com/o/r/releases/download/v/py.tar.gz')
|
||||
).resolves.toBeUndefined();
|
||||
});
|
||||
});
|
||||
@@ -16,14 +16,8 @@ inputs:
|
||||
description: "Set this option if you want the action to check for the latest available version that satisfies the version spec."
|
||||
default: false
|
||||
token:
|
||||
description: "The token used to authenticate when fetching Python distributions from https://github.com/actions/python-versions. When running this action on github.com, the default value is sufficient. When running on GHES, you can pass a personal access token for github.com if you are experiencing rate limiting. This token is only sent to GitHub-owned hosts, never to a custom 'mirror'."
|
||||
description: "The token used to authenticate when fetching Python distributions from https://github.com/actions/python-versions. When running this action on github.com, the default value is sufficient. When running on GHES, you can pass a personal access token for github.com if you are experiencing rate limiting."
|
||||
default: ${{ github.server_url == 'https://github.com' && github.token || '' }}
|
||||
mirror:
|
||||
description: "Base URL for downloading Python distributions (only applies to CPython; PyPy and GraalPy are unaffected). Defaults to https://raw.githubusercontent.com/actions/python-versions/main. See docs/advanced-usage.md for details."
|
||||
default: "https://raw.githubusercontent.com/actions/python-versions/main"
|
||||
mirror-token:
|
||||
description: "Token used to authenticate requests to the host named in 'mirror'. Sent verbatim as the Authorization header, so include a scheme if your mirror needs one (e.g. 'Bearer <token>')."
|
||||
required: false
|
||||
cache-dependency-path:
|
||||
description: "Used to specify the path to dependency files. Supports wildcards or a list of file names for caching multiple dependencies."
|
||||
update-environment:
|
||||
|
||||
645
dist/cache-save/index.js
vendored
645
dist/cache-save/index.js
vendored
@@ -15982,77 +15982,11 @@ class Request {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @param {number|null} statusCode
|
||||
* @param {Buffer[]|null} headers
|
||||
* @param {import('node:stream').Duplex} socket
|
||||
* @param {string} [statusText]
|
||||
*/
|
||||
onUpgrade (statusCode, headers, socket, statusText = '') {
|
||||
this.onFinally()
|
||||
|
||||
onUpgrade (statusCode, headers, socket) {
|
||||
assert(!this.aborted)
|
||||
assert(!this.completed)
|
||||
|
||||
if (statusCode !== null) {
|
||||
this.#publishUpgradeHeaders(statusCode, headers, statusText)
|
||||
}
|
||||
|
||||
const result = this[kHandler].onUpgrade(statusCode, headers, socket)
|
||||
|
||||
if (!this.aborted) {
|
||||
this.completed = true
|
||||
if (statusCode !== null) {
|
||||
this.#publishUpgradeTrailers()
|
||||
}
|
||||
}
|
||||
|
||||
return result
|
||||
}
|
||||
|
||||
/**
|
||||
* @param {number} statusCode
|
||||
* @param {import('node:http2').IncomingHttpHeaders} headers
|
||||
* @param {(headers: import('node:http2').IncomingHttpHeaders) => Buffer[]} parseHeaders
|
||||
* @param {string} [statusText]
|
||||
*/
|
||||
onUpgradeResponse (statusCode, headers, parseHeaders, statusText = '') {
|
||||
assert(!this.aborted)
|
||||
assert(this.completed)
|
||||
|
||||
if (channels.headers.hasSubscribers) {
|
||||
this.#publishUpgradeHeaders(statusCode, parseHeaders(headers), statusText)
|
||||
}
|
||||
this.#publishUpgradeTrailers()
|
||||
}
|
||||
|
||||
/**
|
||||
* @param {Error} error
|
||||
*/
|
||||
onUpgradeError (error) {
|
||||
assert(!this.aborted)
|
||||
assert(this.completed)
|
||||
|
||||
if (channels.error.hasSubscribers) {
|
||||
channels.error.publish({ request: this, error })
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @param {number} statusCode
|
||||
* @param {Buffer[]} headers
|
||||
* @param {string} statusText
|
||||
*/
|
||||
#publishUpgradeHeaders (statusCode, headers, statusText) {
|
||||
if (channels.headers.hasSubscribers) {
|
||||
channels.headers.publish({ request: this, response: { statusCode, headers, statusText } })
|
||||
}
|
||||
}
|
||||
|
||||
#publishUpgradeTrailers () {
|
||||
if (channels.trailers.hasSubscribers) {
|
||||
channels.trailers.publish({ request: this, trailers: [] })
|
||||
}
|
||||
return this[kHandler].onUpgrade(statusCode, headers, socket)
|
||||
}
|
||||
|
||||
onComplete (trailers) {
|
||||
@@ -17951,7 +17885,7 @@ class Parser {
|
||||
}
|
||||
|
||||
onUpgrade (head) {
|
||||
const { upgrade, client, socket, headers, statusCode, statusText } = this
|
||||
const { upgrade, client, socket, headers, statusCode } = this
|
||||
|
||||
assert(upgrade)
|
||||
assert(client[kSocket] === socket)
|
||||
@@ -17986,10 +17920,9 @@ class Parser {
|
||||
client.emit('disconnect', client[kUrl], [client], new InformationalError('upgrade'))
|
||||
|
||||
try {
|
||||
request.onUpgrade(statusCode, headers, socket, statusText)
|
||||
} catch (error) {
|
||||
util.errorRequest(client, request, error)
|
||||
util.destroy(socket, error)
|
||||
request.onUpgrade(statusCode, headers, socket)
|
||||
} catch (err) {
|
||||
util.destroy(socket, err)
|
||||
}
|
||||
|
||||
client[kResume]()
|
||||
@@ -18396,7 +18329,7 @@ async function connectH1 (client, socket) {
|
||||
|
||||
function clearIdleSocketValidation (socket) {
|
||||
if (socket[kIdleSocketValidationTimeout]) {
|
||||
clearImmediate(socket[kIdleSocketValidationTimeout])
|
||||
clearTimeout(socket[kIdleSocketValidationTimeout])
|
||||
socket[kIdleSocketValidationTimeout] = null
|
||||
}
|
||||
|
||||
@@ -18405,23 +18338,15 @@ function clearIdleSocketValidation (socket) {
|
||||
|
||||
function scheduleIdleSocketValidation (client, socket) {
|
||||
socket[kIdleSocketValidation] = 1
|
||||
// Yield to the check phase (after poll) so unsolicited bytes / FIN / RST
|
||||
// already pending on this idle keep-alive socket are processed before the
|
||||
// next request is written (GHSA-35p6-xmwp-9g52).
|
||||
//
|
||||
// setTimeout(0) pays Node's ~1ms timer floor on every sequential reuse
|
||||
// (#5493). setImmediate avoids that, but an *unref'd* Immediate lets poll
|
||||
// block for ~500ms when the event loop is otherwise idle (#5600 / #5606).
|
||||
// A ref'd Immediate both keeps the pending request alive and makes poll
|
||||
// return immediately — the hybrid those issues asked for.
|
||||
socket[kIdleSocketValidationTimeout] = setImmediate(() => {
|
||||
socket[kIdleSocketValidationTimeout] = setTimeout(() => {
|
||||
socket[kIdleSocketValidationTimeout] = null
|
||||
socket[kIdleSocketValidation] = 2
|
||||
|
||||
if (client[kSocket] === socket && !socket.destroyed) {
|
||||
client[kResume]()
|
||||
}
|
||||
})
|
||||
}, 0)
|
||||
socket[kIdleSocketValidationTimeout].unref?.()
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -18570,22 +18495,12 @@ function writeH1 (client, request) {
|
||||
const socket = client[kSocket]
|
||||
clearIdleSocketValidation(socket)
|
||||
|
||||
/**
|
||||
* @param {Error} [error]
|
||||
*/
|
||||
const abort = (error) => {
|
||||
if (request.aborted) {
|
||||
const abort = (err) => {
|
||||
if (request.aborted || request.completed) {
|
||||
return
|
||||
}
|
||||
|
||||
if (request.completed) {
|
||||
if (request.upgrade || request.method === 'CONNECT') {
|
||||
util.destroy(socket, new InformationalError('aborted'))
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
util.errorRequest(client, request, error || new RequestAbortedError())
|
||||
util.errorRequest(client, request, err || new RequestAbortedError())
|
||||
|
||||
util.destroy(body)
|
||||
util.destroy(socket, new InformationalError('aborted'))
|
||||
@@ -19042,7 +18957,6 @@ module.exports = connectH1
|
||||
|
||||
|
||||
const assert = __nccwpck_require__(4589)
|
||||
const { errorMonitor } = __nccwpck_require__(8474)
|
||||
const { pipeline } = __nccwpck_require__(7075)
|
||||
const util = __nccwpck_require__(3440)
|
||||
const {
|
||||
@@ -19119,15 +19033,6 @@ function parseH2Headers (headers) {
|
||||
return result
|
||||
}
|
||||
|
||||
/**
|
||||
* @param {import('node:http2').IncomingHttpHeaders} headers
|
||||
* @returns {Buffer[]}
|
||||
*/
|
||||
function parseH2ResponseHeaders (headers) {
|
||||
const { [HTTP2_HEADER_STATUS]: _statusCode, ...realHeaders } = headers
|
||||
return parseH2Headers(realHeaders)
|
||||
}
|
||||
|
||||
async function connectH2 (client, socket) {
|
||||
client[kSocket] = socket
|
||||
|
||||
@@ -19348,32 +19253,22 @@ function writeH2 (client, request) {
|
||||
headers[HTTP2_HEADER_AUTHORITY] = host || `${hostname}${port ? `:${port}` : ''}`
|
||||
headers[HTTP2_HEADER_METHOD] = method
|
||||
|
||||
/**
|
||||
* @param {Error} [error]
|
||||
*/
|
||||
const abort = (error) => {
|
||||
if (request.aborted) {
|
||||
const abort = (err) => {
|
||||
if (request.aborted || request.completed) {
|
||||
return
|
||||
}
|
||||
|
||||
if (request.completed) {
|
||||
if (method === 'CONNECT' && stream != null) {
|
||||
util.destroy(stream, error || new RequestAbortedError())
|
||||
}
|
||||
return
|
||||
}
|
||||
err = err || new RequestAbortedError()
|
||||
|
||||
error = error || new RequestAbortedError()
|
||||
|
||||
util.errorRequest(client, request, error)
|
||||
util.errorRequest(client, request, err)
|
||||
|
||||
if (stream != null) {
|
||||
util.destroy(stream, error)
|
||||
util.destroy(stream, err)
|
||||
}
|
||||
|
||||
// We do not destroy the socket as we can continue using the session
|
||||
// the stream get's destroyed and the session remains to create new streams
|
||||
util.destroy(body, error)
|
||||
util.destroy(body, err)
|
||||
client[kQueue][client[kRunningIdx]++] = null
|
||||
client[kResume]()
|
||||
}
|
||||
@@ -19392,57 +19287,25 @@ function writeH2 (client, request) {
|
||||
|
||||
if (method === 'CONNECT') {
|
||||
session.ref()
|
||||
// We are already connected, streams are pending, first request
|
||||
// will create a new stream. We trigger a request to create the stream and wait until
|
||||
// `ready` event is triggered
|
||||
// We disabled endStream to allow the user to write to the stream
|
||||
stream = session.request(headers, { endStream: false, signal })
|
||||
let upgradeResponseFinished = false
|
||||
|
||||
/**
|
||||
* @param {import('node:http2').IncomingHttpHeaders} headers
|
||||
*/
|
||||
const onResponse = (headers) => {
|
||||
upgradeResponseFinished = true
|
||||
stream.off(errorMonitor, onUpgradeError)
|
||||
request.onUpgradeResponse(Number(headers[HTTP2_HEADER_STATUS]), headers, parseH2ResponseHeaders)
|
||||
}
|
||||
|
||||
/**
|
||||
* @param {Error} error
|
||||
*/
|
||||
const onUpgradeError = (error) => {
|
||||
upgradeResponseFinished = true
|
||||
stream.off('response', onResponse)
|
||||
request.onUpgradeError(error)
|
||||
}
|
||||
|
||||
const onReady = () => {
|
||||
try {
|
||||
request.onUpgrade(null, null, stream)
|
||||
} catch (error) {
|
||||
stream.off('response', onResponse)
|
||||
abort(error)
|
||||
return
|
||||
}
|
||||
|
||||
if (request.aborted) {
|
||||
return
|
||||
}
|
||||
|
||||
stream.off('error', abort)
|
||||
stream.once(errorMonitor, onUpgradeError)
|
||||
if (stream.id && !stream.pending) {
|
||||
request.onUpgrade(null, null, stream)
|
||||
++session[kOpenStreams]
|
||||
client[kQueue][client[kRunningIdx]++] = null
|
||||
} else {
|
||||
stream.once('ready', () => {
|
||||
request.onUpgrade(null, null, stream)
|
||||
++session[kOpenStreams]
|
||||
client[kQueue][client[kRunningIdx]++] = null
|
||||
})
|
||||
}
|
||||
|
||||
stream.once('response', onResponse)
|
||||
stream.once('error', abort)
|
||||
++session[kOpenStreams]
|
||||
onReady()
|
||||
|
||||
stream.once('close', () => {
|
||||
if (!upgradeResponseFinished && request.completed) {
|
||||
stream.off('response', onResponse)
|
||||
stream.off(errorMonitor, onUpgradeError)
|
||||
request.onUpgradeError(new InformationalError(`HTTP/2: "stream error" received - code ${stream.rstCode}`))
|
||||
}
|
||||
session[kOpenStreams] -= 1
|
||||
if (session[kOpenStreams] === 0) session.unref()
|
||||
})
|
||||
@@ -22141,7 +22004,6 @@ class RetryHandler {
|
||||
this.end = null
|
||||
this.etag = null
|
||||
this.resume = null
|
||||
this.headersSent = false
|
||||
|
||||
// Handle possible onConnect duplication
|
||||
this.handler.onConnect(reason => {
|
||||
@@ -22154,20 +22016,6 @@ class RetryHandler {
|
||||
})
|
||||
}
|
||||
|
||||
checkpointResponseEnd (headers, resume) {
|
||||
if (this.end == null && this.opts.method !== 'HEAD') {
|
||||
const contentLength = headers['content-length']
|
||||
this.end = contentLength != null ? Number(contentLength) - 1 : null
|
||||
|
||||
assert(
|
||||
this.end == null || Number.isFinite(this.end),
|
||||
'invalid content-length'
|
||||
)
|
||||
}
|
||||
|
||||
this.resume = this.end != null ? resume : null
|
||||
}
|
||||
|
||||
onRequestSent () {
|
||||
if (this.handler.onRequestSent) {
|
||||
this.handler.onRequestSent()
|
||||
@@ -22256,12 +22104,7 @@ class RetryHandler {
|
||||
this.retryCount += 1
|
||||
|
||||
if (statusCode >= 300) {
|
||||
// Only expose a response if no earlier attempt has reached the caller.
|
||||
// Otherwise abort this attempt so the error settles the existing body
|
||||
// instead of replacing it with a new response.
|
||||
if (!this.headersSent && this.retryOpts.statusCodes.includes(statusCode) === false) {
|
||||
this.headersSent = true
|
||||
this.checkpointResponseEnd(headers, resume)
|
||||
if (this.retryOpts.statusCodes.includes(statusCode) === false) {
|
||||
return this.handler.onHeaders(
|
||||
statusCode,
|
||||
rawHeaders,
|
||||
@@ -22330,15 +22173,8 @@ class RetryHandler {
|
||||
|
||||
const { start, size, end = size - 1 } = contentRange
|
||||
|
||||
if (this.start !== start || (this.end != null && this.end !== end)) {
|
||||
this.abort(
|
||||
new RequestRetryError('Content-Range mismatch', statusCode, {
|
||||
headers,
|
||||
data: { count: this.retryCount }
|
||||
})
|
||||
)
|
||||
return false
|
||||
}
|
||||
assert(this.start === start, 'content-range mismatch')
|
||||
assert(this.end == null || this.end === end, 'content-range mismatch')
|
||||
|
||||
this.resume = resume
|
||||
return true
|
||||
@@ -22350,7 +22186,6 @@ class RetryHandler {
|
||||
const range = parseRangeHeader(headers['content-range'])
|
||||
|
||||
if (range == null) {
|
||||
this.headersSent = true
|
||||
return this.handler.onHeaders(
|
||||
statusCode,
|
||||
rawHeaders,
|
||||
@@ -22389,7 +22224,6 @@ class RetryHandler {
|
||||
)
|
||||
|
||||
this.resume = resume
|
||||
this.headersSent = true
|
||||
this.etag = headers.etag != null ? headers.etag : null
|
||||
|
||||
// Weak etags are not useful for comparison nor cache
|
||||
@@ -22429,7 +22263,7 @@ class RetryHandler {
|
||||
}
|
||||
|
||||
onError (err) {
|
||||
if (this.aborted || isDisturbed(this.opts.body) || (this.headersSent && this.resume == null)) {
|
||||
if (this.aborted || isDisturbed(this.opts.body)) {
|
||||
return this.handler.onError(err)
|
||||
}
|
||||
|
||||
@@ -26887,49 +26721,6 @@ const COLON = 0x3A
|
||||
*/
|
||||
const SPACE = 0x20
|
||||
|
||||
const DATA = Buffer.from('data')
|
||||
const EVENT = Buffer.from('event')
|
||||
const ID = Buffer.from('id')
|
||||
const RETRY = Buffer.from('retry')
|
||||
|
||||
function isASCIINumberBytes (buffer, start) {
|
||||
if (start >= buffer.length) {
|
||||
return false
|
||||
}
|
||||
|
||||
for (let i = start; i < buffer.length; i++) {
|
||||
if (buffer[i] < 0x30 || buffer[i] > 0x39) {
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
return true
|
||||
}
|
||||
|
||||
function isValidLastEventIdBytes (buffer, start) {
|
||||
for (let i = start; i < buffer.length; i++) {
|
||||
if (buffer[i] === 0x00) {
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
return true
|
||||
}
|
||||
|
||||
function isFieldName (line, length, field) {
|
||||
if (length !== field.length) {
|
||||
return false
|
||||
}
|
||||
|
||||
for (let i = 0; i < length; i++) {
|
||||
if (line[i] !== field[i]) {
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
return true
|
||||
}
|
||||
|
||||
/**
|
||||
* @typedef {object} EventSourceStreamEvent
|
||||
* @type {object}
|
||||
@@ -26970,14 +26761,11 @@ class EventSourceStream extends Transform {
|
||||
eventEndCheck = false
|
||||
|
||||
/**
|
||||
* @type {Buffer[]}
|
||||
* @type {Buffer}
|
||||
*/
|
||||
chunks = []
|
||||
buffer = null
|
||||
|
||||
chunkIndex = 0
|
||||
pos = 0
|
||||
lineChunkIndex = 0
|
||||
linePos = 0
|
||||
|
||||
event = {
|
||||
data: undefined,
|
||||
@@ -27016,20 +26804,92 @@ class EventSourceStream extends Transform {
|
||||
return
|
||||
}
|
||||
|
||||
this.chunks.push(chunk)
|
||||
// Cache the chunk in the buffer, as the data might not be complete while
|
||||
// processing it
|
||||
// TODO: Investigate if there is a more performant way to handle
|
||||
// incoming chunks
|
||||
// see: https://github.com/nodejs/undici/issues/2630
|
||||
if (this.buffer) {
|
||||
this.buffer = Buffer.concat([this.buffer, chunk])
|
||||
} else {
|
||||
this.buffer = chunk
|
||||
}
|
||||
|
||||
// Strip leading byte-order-mark if we opened the stream and started
|
||||
// the processing of the incoming data
|
||||
if (this.checkBOM) {
|
||||
if (this.handleBOM()) {
|
||||
callback()
|
||||
return
|
||||
switch (this.buffer.length) {
|
||||
case 1:
|
||||
// Check if the first byte is the same as the first byte of the BOM
|
||||
if (this.buffer[0] === BOM[0]) {
|
||||
// If it is, we need to wait for more data
|
||||
callback()
|
||||
return
|
||||
}
|
||||
// Set the checkBOM flag to false as we don't need to check for the
|
||||
// BOM anymore
|
||||
this.checkBOM = false
|
||||
|
||||
// The buffer only contains one byte so we need to wait for more data
|
||||
callback()
|
||||
return
|
||||
case 2:
|
||||
// Check if the first two bytes are the same as the first two bytes
|
||||
// of the BOM
|
||||
if (
|
||||
this.buffer[0] === BOM[0] &&
|
||||
this.buffer[1] === BOM[1]
|
||||
) {
|
||||
// If it is, we need to wait for more data, because the third byte
|
||||
// is needed to determine if it is the BOM or not
|
||||
callback()
|
||||
return
|
||||
}
|
||||
|
||||
// Set the checkBOM flag to false as we don't need to check for the
|
||||
// BOM anymore
|
||||
this.checkBOM = false
|
||||
break
|
||||
case 3:
|
||||
// Check if the first three bytes are the same as the first three
|
||||
// bytes of the BOM
|
||||
if (
|
||||
this.buffer[0] === BOM[0] &&
|
||||
this.buffer[1] === BOM[1] &&
|
||||
this.buffer[2] === BOM[2]
|
||||
) {
|
||||
// If it is, we can drop the buffered data, as it is only the BOM
|
||||
this.buffer = Buffer.alloc(0)
|
||||
// Set the checkBOM flag to false as we don't need to check for the
|
||||
// BOM anymore
|
||||
this.checkBOM = false
|
||||
|
||||
// Await more data
|
||||
callback()
|
||||
return
|
||||
}
|
||||
// If it is not the BOM, we can start processing the data
|
||||
this.checkBOM = false
|
||||
break
|
||||
default:
|
||||
// The buffer is longer than 3 bytes, so we can drop the BOM if it is
|
||||
// present
|
||||
if (
|
||||
this.buffer[0] === BOM[0] &&
|
||||
this.buffer[1] === BOM[1] &&
|
||||
this.buffer[2] === BOM[2]
|
||||
) {
|
||||
// Remove the BOM from the buffer
|
||||
this.buffer = this.buffer.subarray(3)
|
||||
}
|
||||
|
||||
// Set the checkBOM flag to false as we don't need to check for the
|
||||
this.checkBOM = false
|
||||
break
|
||||
}
|
||||
}
|
||||
|
||||
while (this.hasCurrentByte()) {
|
||||
const byte = this.currentByte()
|
||||
|
||||
while (this.pos < this.buffer.length) {
|
||||
// If the previous line ended with an end-of-line, we need to check
|
||||
// if the next character is also an end-of-line.
|
||||
if (this.eventEndCheck) {
|
||||
@@ -27042,9 +26902,10 @@ class EventSourceStream extends Transform {
|
||||
if (this.crlfCheck) {
|
||||
// If the current character is a line feed, we can remove it
|
||||
// from the buffer and reset the crlfCheck flag
|
||||
if (byte === LF) {
|
||||
if (this.buffer[this.pos] === LF) {
|
||||
this.buffer = this.buffer.subarray(this.pos + 1)
|
||||
this.pos = 0
|
||||
this.crlfCheck = false
|
||||
this.consumeCurrentByte()
|
||||
|
||||
// It is possible that the line feed is not the end of the
|
||||
// event. We need to check if the next character is an
|
||||
@@ -27060,17 +26921,19 @@ class EventSourceStream extends Transform {
|
||||
this.crlfCheck = false
|
||||
}
|
||||
|
||||
if (byte === LF || byte === CR) {
|
||||
if (this.buffer[this.pos] === LF || this.buffer[this.pos] === CR) {
|
||||
// If the current character is a carriage return, we need to
|
||||
// set the crlfCheck flag to true, as we need to check if the
|
||||
// next character is a line feed so we can remove it from the
|
||||
// buffer
|
||||
if (byte === CR) {
|
||||
if (this.buffer[this.pos] === CR) {
|
||||
this.crlfCheck = true
|
||||
}
|
||||
|
||||
this.consumeCurrentByte()
|
||||
if (this.hasPendingEvent()) {
|
||||
this.buffer = this.buffer.subarray(this.pos + 1)
|
||||
this.pos = 0
|
||||
if (
|
||||
this.event.data !== undefined || this.event.event || this.event.id || this.event.retry) {
|
||||
this.processEvent(this.event)
|
||||
}
|
||||
this.clearEvent()
|
||||
@@ -27084,18 +26947,22 @@ class EventSourceStream extends Transform {
|
||||
|
||||
// If the current character is an end-of-line, we can process the
|
||||
// line
|
||||
if (byte === LF || byte === CR) {
|
||||
if (this.buffer[this.pos] === LF || this.buffer[this.pos] === CR) {
|
||||
// If the current character is a carriage return, we need to
|
||||
// set the crlfCheck flag to true, as we need to check if the
|
||||
// next character is a line feed
|
||||
if (byte === CR) {
|
||||
if (this.buffer[this.pos] === CR) {
|
||||
this.crlfCheck = true
|
||||
}
|
||||
|
||||
// In any case, we can process the line as we reached an
|
||||
// end-of-line character
|
||||
this.parseLine(this.readLine(), this.event)
|
||||
this.consumeCurrentByte()
|
||||
this.parseLine(this.buffer.subarray(0, this.pos), this.event)
|
||||
|
||||
// Remove the processed line from the buffer
|
||||
this.buffer = this.buffer.subarray(this.pos + 1)
|
||||
// Reset the position as we removed the processed line from the buffer
|
||||
this.pos = 0
|
||||
// A line was processed and this could be the end of the event. We need
|
||||
// to check if the next line is empty to determine if the event is
|
||||
// finished.
|
||||
@@ -27103,7 +26970,7 @@ class EventSourceStream extends Transform {
|
||||
continue
|
||||
}
|
||||
|
||||
this.advanceCursor()
|
||||
this.pos++
|
||||
}
|
||||
|
||||
callback()
|
||||
@@ -27128,53 +26995,64 @@ class EventSourceStream extends Transform {
|
||||
return
|
||||
}
|
||||
|
||||
let fieldLength = line.length
|
||||
let valueStart = line.length
|
||||
let field = ''
|
||||
let value = ''
|
||||
|
||||
// If the line contains a U+003A COLON character (:)
|
||||
if (colonPosition !== -1) {
|
||||
fieldLength = colonPosition
|
||||
// Collect the characters on the line before the first U+003A COLON
|
||||
// character (:), and let field be that string.
|
||||
// TODO: Investigate if there is a more performant way to extract the
|
||||
// field
|
||||
// see: https://github.com/nodejs/undici/issues/2630
|
||||
field = line.subarray(0, colonPosition).toString('utf8')
|
||||
|
||||
// Collect the characters on the line after the first U+003A COLON
|
||||
// character (:), and let value be that string.
|
||||
// If value starts with a U+0020 SPACE character, remove it from value.
|
||||
valueStart = colonPosition + 1
|
||||
let valueStart = colonPosition + 1
|
||||
if (line[valueStart] === SPACE) {
|
||||
++valueStart
|
||||
}
|
||||
// TODO: Investigate if there is a more performant way to extract the
|
||||
// value
|
||||
// see: https://github.com/nodejs/undici/issues/2630
|
||||
value = line.subarray(valueStart).toString('utf8')
|
||||
|
||||
// Otherwise, the string is not empty but does not contain a U+003A COLON
|
||||
// character (:)
|
||||
} else {
|
||||
// Process the field using the steps described below, using the whole
|
||||
// line as the field name, and the empty string as the field value.
|
||||
field = line.toString('utf8')
|
||||
value = ''
|
||||
}
|
||||
|
||||
if (isFieldName(line, fieldLength, DATA)) {
|
||||
const value = line.toString('utf8', valueStart)
|
||||
|
||||
if (event.data === undefined) {
|
||||
event.data = value
|
||||
} else {
|
||||
event.data += `\n${value}`
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
if (isFieldName(line, fieldLength, RETRY)) {
|
||||
if (isASCIINumberBytes(line, valueStart)) {
|
||||
event.retry = line.toString('utf8', valueStart)
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
if (isFieldName(line, fieldLength, ID)) {
|
||||
if (isValidLastEventIdBytes(line, valueStart)) {
|
||||
event.id = line.toString('utf8', valueStart)
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
if (isFieldName(line, fieldLength, EVENT)) {
|
||||
const value = line.toString('utf8', valueStart)
|
||||
|
||||
if (value.length > 0) {
|
||||
event.event = value
|
||||
}
|
||||
// Modify the event with the field name and value. The value is also
|
||||
// decoded as UTF-8
|
||||
switch (field) {
|
||||
case 'data':
|
||||
if (event[field] === undefined) {
|
||||
event[field] = value
|
||||
} else {
|
||||
event[field] += `\n${value}`
|
||||
}
|
||||
break
|
||||
case 'retry':
|
||||
if (isASCIINumber(value)) {
|
||||
event[field] = value
|
||||
}
|
||||
break
|
||||
case 'id':
|
||||
if (isValidLastEventId(value)) {
|
||||
event[field] = value
|
||||
}
|
||||
break
|
||||
case 'event':
|
||||
if (value.length > 0) {
|
||||
event[field] = value
|
||||
}
|
||||
break
|
||||
}
|
||||
}
|
||||
|
||||
@@ -27204,152 +27082,13 @@ class EventSourceStream extends Transform {
|
||||
}
|
||||
|
||||
clearEvent () {
|
||||
this.event.data = undefined
|
||||
this.event.event = undefined
|
||||
this.event.id = undefined
|
||||
this.event.retry = undefined
|
||||
}
|
||||
|
||||
hasPendingEvent () {
|
||||
return this.event.data !== undefined ||
|
||||
this.event.event !== undefined ||
|
||||
this.event.id !== undefined ||
|
||||
this.event.retry !== undefined
|
||||
}
|
||||
|
||||
hasCurrentByte () {
|
||||
return this.chunkIndex < this.chunks.length &&
|
||||
this.pos < this.chunks[this.chunkIndex].length
|
||||
}
|
||||
|
||||
currentByte () {
|
||||
return this.chunks[this.chunkIndex][this.pos]
|
||||
}
|
||||
|
||||
consumeCurrentByte () {
|
||||
this.advanceCursor()
|
||||
this.syncLineStartToCursor()
|
||||
}
|
||||
|
||||
advanceCursor () {
|
||||
this.pos++
|
||||
|
||||
while (this.chunkIndex < this.chunks.length && this.pos >= this.chunks[this.chunkIndex].length) {
|
||||
this.chunkIndex++
|
||||
this.pos = 0
|
||||
this.event = {
|
||||
data: undefined,
|
||||
event: undefined,
|
||||
id: undefined,
|
||||
retry: undefined
|
||||
}
|
||||
}
|
||||
|
||||
syncLineStartToCursor () {
|
||||
this.lineChunkIndex = this.chunkIndex
|
||||
this.linePos = this.pos
|
||||
this.dropConsumedChunks()
|
||||
}
|
||||
|
||||
dropConsumedChunks () {
|
||||
while (this.lineChunkIndex > 0) {
|
||||
this.chunks.shift()
|
||||
this.lineChunkIndex--
|
||||
this.chunkIndex--
|
||||
}
|
||||
|
||||
if (this.chunkIndex === this.chunks.length) {
|
||||
this.chunks.length = 0
|
||||
this.chunkIndex = 0
|
||||
this.pos = 0
|
||||
this.lineChunkIndex = 0
|
||||
this.linePos = 0
|
||||
}
|
||||
}
|
||||
|
||||
readLine () {
|
||||
if (this.lineChunkIndex === this.chunkIndex) {
|
||||
return this.chunks[this.chunkIndex].subarray(this.linePos, this.pos)
|
||||
}
|
||||
|
||||
const chunks = []
|
||||
let length = 0
|
||||
|
||||
for (let i = this.lineChunkIndex; i <= this.chunkIndex; i++) {
|
||||
const chunk = this.chunks[i]
|
||||
const start = i === this.lineChunkIndex ? this.linePos : 0
|
||||
const end = i === this.chunkIndex ? this.pos : chunk.length
|
||||
const slice = chunk.subarray(start, end)
|
||||
length += slice.length
|
||||
chunks.push(slice)
|
||||
}
|
||||
|
||||
return Buffer.concat(chunks, length)
|
||||
}
|
||||
|
||||
peekBufferedByte (offset) {
|
||||
let chunkIndex = this.lineChunkIndex
|
||||
let pos = this.linePos
|
||||
|
||||
while (chunkIndex < this.chunks.length) {
|
||||
const chunk = this.chunks[chunkIndex]
|
||||
const remaining = chunk.length - pos
|
||||
|
||||
if (offset < remaining) {
|
||||
return chunk[pos + offset]
|
||||
}
|
||||
|
||||
offset -= remaining
|
||||
chunkIndex++
|
||||
pos = 0
|
||||
}
|
||||
}
|
||||
|
||||
discardLeadingBytes (count) {
|
||||
while (count > 0 && this.lineChunkIndex < this.chunks.length) {
|
||||
const chunk = this.chunks[this.lineChunkIndex]
|
||||
const remaining = chunk.length - this.linePos
|
||||
|
||||
if (count < remaining) {
|
||||
this.linePos += count
|
||||
count = 0
|
||||
} else {
|
||||
count -= remaining
|
||||
this.lineChunkIndex++
|
||||
this.linePos = 0
|
||||
}
|
||||
}
|
||||
|
||||
this.chunkIndex = this.lineChunkIndex
|
||||
this.pos = this.linePos
|
||||
this.dropConsumedChunks()
|
||||
}
|
||||
|
||||
handleBOM () {
|
||||
const first = this.peekBufferedByte(0)
|
||||
const second = this.peekBufferedByte(1)
|
||||
const third = this.peekBufferedByte(2)
|
||||
|
||||
if (second === undefined) {
|
||||
if (first === BOM[0]) {
|
||||
return true
|
||||
}
|
||||
|
||||
this.checkBOM = false
|
||||
return true
|
||||
}
|
||||
|
||||
if (third === undefined) {
|
||||
if (first === BOM[0] && second === BOM[1]) {
|
||||
return true
|
||||
}
|
||||
|
||||
this.checkBOM = false
|
||||
return false
|
||||
}
|
||||
|
||||
if (first === BOM[0] && second === BOM[1] && third === BOM[2]) {
|
||||
this.discardLeadingBytes(3)
|
||||
}
|
||||
|
||||
this.checkBOM = false
|
||||
return !this.hasCurrentByte()
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = {
|
||||
@@ -38617,7 +38356,7 @@ function establishWebSocketConnection (url, protocols, client, ws, onEstablish,
|
||||
// is specified, the server needs to include the same field and one of
|
||||
// the selected subprotocol values in its response for the connection to
|
||||
// be established.
|
||||
if (requestProtocols === null || !requestProtocols.includes(secProtocol)) {
|
||||
if (!requestProtocols.includes(secProtocol)) {
|
||||
failWebsocketConnection(ws, 'Protocol was not set in the opening handshake.')
|
||||
return
|
||||
}
|
||||
@@ -39378,12 +39117,7 @@ class PerMessageDeflate {
|
||||
|
||||
if (this.#maxPayloadSize > 0 && this.#inflate[kLength] > this.#maxPayloadSize) {
|
||||
callback(new MessageSizeExceededError())
|
||||
// The inflater may still hold buffered input that can emit a late
|
||||
// zlib error. Remove the data listener, then deterministically stop
|
||||
// the stream so a subsequent 'error' cannot fire without a listener
|
||||
// (which would terminate the process as an unhandled error event).
|
||||
this.#inflate.removeAllListeners()
|
||||
this.#inflate.destroy()
|
||||
this.#inflate = null
|
||||
return
|
||||
}
|
||||
@@ -41688,9 +41422,6 @@ module.exports = /*#__PURE__*/JSON.parse('{"name":"@actions/cache","version":"6.
|
||||
/******/ }
|
||||
/******/
|
||||
/************************************************************************/
|
||||
/******/ /* webpack/runtime/asset-relocator-loader */
|
||||
/******/ if (typeof __nccwpck_require__ !== 'undefined') __nccwpck_require__.ab = decodeURIComponent(new URL('.', import.meta.url).pathname).slice(import.meta.url.match(/^file:\/\/\/\w:/) ? 1 : 0, -1) + "/";
|
||||
/******/
|
||||
/******/ /* webpack/runtime/compat get default export */
|
||||
/******/ (() => {
|
||||
/******/ // getDefaultExport function for compatibility with non-harmony modules
|
||||
@@ -41761,6 +41492,10 @@ module.exports = /*#__PURE__*/JSON.parse('{"name":"@actions/cache","version":"6.
|
||||
/******/ };
|
||||
/******/ })();
|
||||
/******/
|
||||
/******/ /* webpack/runtime/compat */
|
||||
/******/
|
||||
/******/ if (typeof __nccwpck_require__ !== 'undefined') __nccwpck_require__.ab = new URL('.', import.meta.url).pathname.slice(import.meta.url.match(/^file:\/\/\/\w:/) ? 1 : 0, -1) + "/";
|
||||
/******/
|
||||
/************************************************************************/
|
||||
var __webpack_exports__ = {};
|
||||
|
||||
|
||||
841
dist/setup/index.js
vendored
841
dist/setup/index.js
vendored
File diff suppressed because it is too large
Load Diff
@@ -524,46 +524,6 @@ Such a requirement on side-effect could be because you don't want your composite
|
||||
|
||||
>**Note:** Python versions used in this action are generated in the [python-versions](https://github.com/actions/python-versions) repository. For macOS and Ubuntu images, python versions are built from the source code. For Windows, the python-versions repository uses installation executable. For more information please refer to the [python-versions](https://github.com/actions/python-versions) repository.
|
||||
|
||||
#### Using a custom mirror
|
||||
|
||||
The `mirror` input lets you point `setup-python` at a different location for CPython distributions — a personal fork of `actions/python-versions`, an internal mirror, or any server that hosts a `versions-manifest.json` at its root plus the tarballs referenced by that manifest. Default: `https://raw.githubusercontent.com/actions/python-versions/main`.
|
||||
|
||||
The manifest is resolved as follows:
|
||||
|
||||
- If `mirror` matches `https://raw.githubusercontent.com/{owner}/{repo}/{branch}`, the manifest is fetched via the GitHub REST API (giving you the 5000/hr authenticated rate limit when a token is present).
|
||||
- Otherwise, the action fetches `{mirror}/versions-manifest.json` via a direct HTTP GET.
|
||||
|
||||
Authentication is decided by the host of each request, so neither credential reaches a server you did not nominate:
|
||||
|
||||
- Requests to the host named in `mirror` use `mirror-token`, sent **verbatim** as the `Authorization` header. Include a scheme if your mirror expects one — `Bearer <token>`, `Basic <base64>`, or `token <token>` for a GitHub host. This covers both the manifest fetch and the tarball downloads.
|
||||
- Requests to `github.com`, `*.github.com`, or `*.githubusercontent.com` use `token`, sent as `token <token>`. A manifest that points its `download_url` at a GitHub host therefore keeps working without `mirror-token` being leaked to it.
|
||||
- Any other host is requested anonymously.
|
||||
- One exception: when `mirror` is a GitHub repo URL, the manifest is fetched from `api.github.com`, and `mirror-token` is preferred there (with the `token ` prefix the API requires) because naming a repo mirror is an explicit instruction to read that repo.
|
||||
|
||||
Point at a personal fork of `actions/python-versions` (uses the default `token`, fetched via the GitHub API):
|
||||
|
||||
```yaml
|
||||
- uses: actions/setup-python@v6
|
||||
with:
|
||||
python-version: '3.12'
|
||||
mirror: https://raw.githubusercontent.com/my-org/python-versions/main
|
||||
```
|
||||
|
||||
Point at an internal mirror with its own credential:
|
||||
|
||||
```yaml
|
||||
- uses: actions/setup-python@v6
|
||||
with:
|
||||
python-version: '3.12'
|
||||
mirror: https://python-mirror.internal.example
|
||||
mirror-token: ${{ secrets.PYTHON_MIRROR_TOKEN }}
|
||||
```
|
||||
|
||||
Caveats:
|
||||
|
||||
- `mirror` and `mirror-token` apply to **CPython only**. PyPy resolves from `downloads.python.org` and GraalPy from the GitHub releases API; both ignore these inputs, and the action warns if you set `mirror` alongside a `pypy-*` or `graalpy-*` version.
|
||||
- Branch names containing `/` cannot be used with a `raw.githubusercontent.com` mirror, because `.../{owner}/{repo}/feature/riscv` is indistinguishable from a repo path. Such a mirror still works and is still authenticated with your `token` (raw.githubusercontent.com is a GitHub host), but the manifest is fetched directly from the raw URL rather than through the GitHub REST API; the action warns when this happens. Use a branch without a slash to get the REST API path. The `refs/heads/{branch}` form (for example `.../actions/python-versions/refs/heads/main`) is recognized and routes through the REST API.
|
||||
|
||||
### PyPy
|
||||
|
||||
`setup-python` is able to configure **PyPy** from two sources:
|
||||
|
||||
1059
package-lock.json
generated
1059
package-lock.json
generated
File diff suppressed because it is too large
Load Diff
12
package.json
12
package.json
@@ -46,18 +46,18 @@
|
||||
"@eslint/js": "^10.0.1",
|
||||
"@jest/globals": "^30.4.1",
|
||||
"@types/node": "^24.10.1",
|
||||
"@types/semver": "^7.8.0",
|
||||
"@types/semver": "^7.7.0",
|
||||
"@typescript-eslint/eslint-plugin": "^8.62.0",
|
||||
"@typescript-eslint/parser": "^8.70.0",
|
||||
"@vercel/ncc": "^0.45.0",
|
||||
"@typescript-eslint/parser": "^8.62.0",
|
||||
"@vercel/ncc": "^0.44.0",
|
||||
"eslint": "^10.5.0",
|
||||
"eslint-config-prettier": "^10.0.0",
|
||||
"eslint-plugin-jest": "^29.16.6",
|
||||
"eslint-plugin-jest": "^29.15.2",
|
||||
"eslint-plugin-n": "^18.1.0",
|
||||
"globals": "^17.7.0",
|
||||
"jest": "^30.4.2",
|
||||
"prettier": "^3.8.4",
|
||||
"ts-jest": "^29.4.14",
|
||||
"typescript": "^6.0.3"
|
||||
"ts-jest": "^29.4.11",
|
||||
"typescript": "^7.0.2"
|
||||
}
|
||||
}
|
||||
|
||||
@@ -137,7 +137,7 @@ export async function useCpythonVersion(
|
||||
);
|
||||
}
|
||||
msg.push(
|
||||
`The list of all available versions can be found here: ${installer.getManifestUrl()}`
|
||||
`The list of all available versions can be found here: ${installer.MANIFEST_URL}`
|
||||
);
|
||||
throw new Error(msg.join(os.EOL));
|
||||
}
|
||||
|
||||
@@ -9,135 +9,12 @@ import * as semver from 'semver';
|
||||
import {IS_WINDOWS, IS_LINUX, getDownloadFileName} from './utils.js';
|
||||
import {IToolRelease} from '@actions/tool-cache';
|
||||
|
||||
const DEFAULT_REPO_OWNER = 'actions';
|
||||
const DEFAULT_REPO_NAME = 'python-versions';
|
||||
const DEFAULT_REPO_BRANCH = 'main';
|
||||
const DEFAULT_MIRROR = `https://raw.githubusercontent.com/${DEFAULT_REPO_OWNER}/${DEFAULT_REPO_NAME}/${DEFAULT_REPO_BRANCH}`;
|
||||
|
||||
// Matches https://raw.githubusercontent.com/{owner}/{repo}/{branch} and the
|
||||
// equivalent https://raw.githubusercontent.com/{owner}/{repo}/refs/heads/{branch}
|
||||
// form, capturing the bare branch in both. The GitHub tree API wants the bare
|
||||
// branch, so the optional refs/heads/ prefix is consumed, not captured.
|
||||
const REPO_COORDS_RE =
|
||||
/^https:\/\/raw\.githubusercontent\.com\/([^/]+)\/([^/]+)\/(?:refs\/heads\/)?([^/]+)\/?$/;
|
||||
|
||||
function getToken(): string {
|
||||
return core.getInput('token');
|
||||
}
|
||||
|
||||
function getMirrorToken(): string {
|
||||
return core.getInput('mirror-token');
|
||||
}
|
||||
|
||||
// Memoized per raw input value so the mirror is validated once per run rather
|
||||
// than on every call. `getManifestUrl()` is also used to build the "version not
|
||||
// found" message in find-python.ts, where re-validating would replace the real
|
||||
// cause with an invalid-mirror error.
|
||||
const mirrorCache = new Map<string, {url: string} | {error: Error}>();
|
||||
|
||||
function getMirror(): string {
|
||||
const input = core.getInput('mirror') || DEFAULT_MIRROR;
|
||||
let resolved = mirrorCache.get(input);
|
||||
|
||||
if (!resolved) {
|
||||
const url = input.trim().replace(/\/+$/, '');
|
||||
try {
|
||||
new URL(url);
|
||||
resolved = {url};
|
||||
} catch {
|
||||
resolved = {error: new Error(`Invalid 'mirror' URL: "${url}"`)};
|
||||
}
|
||||
mirrorCache.set(input, resolved);
|
||||
}
|
||||
|
||||
if ('error' in resolved) throw resolved.error;
|
||||
return resolved.url;
|
||||
}
|
||||
|
||||
export function getManifestUrl(): string {
|
||||
return `${getMirror()}/versions-manifest.json`;
|
||||
}
|
||||
|
||||
// Whether the user set `mirror` to something other than the built-in default.
|
||||
// action.yml gives `mirror` a default, so core.getInput('mirror') is never
|
||||
// empty; callers that want "did the user opt into a custom mirror" must compare
|
||||
// against DEFAULT_MIRROR rather than test for a falsy input. Normalizes the
|
||||
// same way getMirror() does but never throws, so a warning path can call it
|
||||
// even when the mirror is malformed.
|
||||
export function isMirrorCustomized(): boolean {
|
||||
const input = core.getInput('mirror');
|
||||
if (!input) return false;
|
||||
return input.trim().replace(/\/+$/, '') !== DEFAULT_MIRROR;
|
||||
}
|
||||
|
||||
// Origin (scheme + host + port) of the mirror, so `mirror-token` is matched
|
||||
// against the exact origin the user nominated. Comparing origin rather than
|
||||
// host alone means a manifest served over https that points a download_url at
|
||||
// http://same-host/... does NOT get the token — the scheme must match too.
|
||||
// Deliberately not wrapped in try/catch: an invalid mirror throws here just as
|
||||
// it does in getManifestUrl(), so both agree a bad mirror is fatal.
|
||||
function getMirrorOrigin(): string {
|
||||
return new URL(getMirror()).origin;
|
||||
}
|
||||
|
||||
function isGitHubHost(host: string): boolean {
|
||||
return (
|
||||
host === 'github.com' ||
|
||||
host.endsWith('.github.com') ||
|
||||
host.endsWith('.githubusercontent.com')
|
||||
);
|
||||
}
|
||||
|
||||
// Warned at most once per distinct mirror; resolveRepoCoords() is called from
|
||||
// several paths within a single run.
|
||||
const warnedMirrors = new Set<string>();
|
||||
|
||||
export function resolveRepoCoords(): {
|
||||
owner: string;
|
||||
repo: string;
|
||||
branch: string;
|
||||
} | null {
|
||||
const mirror = getMirror();
|
||||
const m = REPO_COORDS_RE.exec(mirror);
|
||||
if (m) return {owner: m[1], repo: m[2], branch: m[3]};
|
||||
|
||||
// A raw.githubusercontent.com URL that doesn't parse is a branch name
|
||||
// containing a slash (e.g. .../{owner}/{repo}/feature/riscv), which is
|
||||
// indistinguishable from a deeper path. getMirror() succeeded above, so the
|
||||
// URL is well-formed and this parse cannot throw.
|
||||
const isRawGitHub = new URL(mirror).host === 'raw.githubusercontent.com';
|
||||
if (!warnedMirrors.has(mirror) && isRawGitHub) {
|
||||
warnedMirrors.add(mirror);
|
||||
core.warning(
|
||||
`Could not parse owner/repo/branch out of mirror "${mirror}", so the manifest will be fetched directly from the raw URL instead of through the GitHub REST API. ` +
|
||||
`The request is still authenticated with your token, because raw.githubusercontent.com is a GitHub host. ` +
|
||||
`Branch names containing '/' are not supported for the REST API path; use a branch without a slash if you want the manifest fetched through the API.`
|
||||
);
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
// Mirror origin with `mirror-token` set gets the token verbatim, so internal
|
||||
// mirrors can choose their own scheme (Bearer, Basic, ...). GitHub hosts get
|
||||
// `token ${token}`. Anything else is anonymous — neither credential is sent to
|
||||
// a host the user didn't nominate.
|
||||
function authForUrl(url: string): string | undefined {
|
||||
let parsed: URL;
|
||||
try {
|
||||
parsed = new URL(url);
|
||||
} catch {
|
||||
return undefined;
|
||||
}
|
||||
|
||||
const mirrorToken = getMirrorToken();
|
||||
if (mirrorToken && parsed.origin === getMirrorOrigin()) return mirrorToken;
|
||||
|
||||
const token = getToken();
|
||||
if (token && isGitHubHost(parsed.host)) return `token ${token}`;
|
||||
|
||||
return undefined;
|
||||
}
|
||||
const TOKEN = core.getInput('token');
|
||||
const AUTH = !TOKEN ? undefined : `token ${TOKEN}`;
|
||||
const MANIFEST_REPO_OWNER = 'actions';
|
||||
const MANIFEST_REPO_NAME = 'python-versions';
|
||||
const MANIFEST_REPO_BRANCH = 'main';
|
||||
export const MANIFEST_URL = `https://raw.githubusercontent.com/${MANIFEST_REPO_OWNER}/${MANIFEST_REPO_NAME}/${MANIFEST_REPO_BRANCH}/versions-manifest.json`;
|
||||
|
||||
interface LinuxOsRelease {
|
||||
id: string;
|
||||
@@ -328,24 +205,15 @@ async function fetchValidManifest(
|
||||
}
|
||||
|
||||
export async function getManifest(): Promise<tc.IToolRelease[]> {
|
||||
// Only GitHub repo mirrors can be fetched via the API. Checking up front
|
||||
// avoids burning MANIFEST_FETCH_MAX_ATTEMPTS with backoff on a throw that
|
||||
// could never succeed.
|
||||
if (resolveRepoCoords()) {
|
||||
try {
|
||||
return await fetchValidManifest('the GitHub API', getManifestFromRepo);
|
||||
} catch (err) {
|
||||
core.debug('Fetching the manifest via the API failed.');
|
||||
if (err instanceof Error) {
|
||||
core.debug(err.message);
|
||||
} else {
|
||||
core.debug('An unexpected error occurred while fetching the manifest.');
|
||||
}
|
||||
try {
|
||||
return await fetchValidManifest('the GitHub API', getManifestFromRepo);
|
||||
} catch (err) {
|
||||
core.debug('Fetching the manifest via the API failed.');
|
||||
if (err instanceof Error) {
|
||||
core.debug(err.message);
|
||||
} else {
|
||||
core.debug('An unexpected error occurred while fetching the manifest.');
|
||||
}
|
||||
} else {
|
||||
core.debug(
|
||||
`Mirror "${getMirror()}" is not a GitHub repo URL; fetching the manifest by URL.`
|
||||
);
|
||||
}
|
||||
|
||||
try {
|
||||
@@ -361,41 +229,24 @@ export async function getManifest(): Promise<tc.IToolRelease[]> {
|
||||
}
|
||||
|
||||
export function getManifestFromRepo(): Promise<tc.IToolRelease[]> {
|
||||
const coords = resolveRepoCoords();
|
||||
if (!coords) {
|
||||
throw new Error(
|
||||
`Mirror "${getMirror()}" is not a GitHub repo URL; falling back to raw URL fetch.`
|
||||
);
|
||||
}
|
||||
core.debug(
|
||||
`Getting manifest from ${coords.owner}/${coords.repo}@${coords.branch}`
|
||||
`Getting manifest from ${MANIFEST_REPO_OWNER}/${MANIFEST_REPO_NAME}@${MANIFEST_REPO_BRANCH}`
|
||||
);
|
||||
return tc.getManifestFromRepo(
|
||||
MANIFEST_REPO_OWNER,
|
||||
MANIFEST_REPO_NAME,
|
||||
AUTH,
|
||||
MANIFEST_REPO_BRANCH
|
||||
);
|
||||
// This only runs for GitHub repo mirrors, where `mirror-token` is the user's
|
||||
// explicit intent for that repo. The target is always api.github.com, which
|
||||
// requires the `token ` prefix, so the host rule in authForUrl() doesn't
|
||||
// apply here.
|
||||
const token = getToken();
|
||||
const mirrorToken = getMirrorToken();
|
||||
const auth = mirrorToken
|
||||
? `token ${mirrorToken}`
|
||||
: token
|
||||
? `token ${token}`
|
||||
: undefined;
|
||||
return tc.getManifestFromRepo(coords.owner, coords.repo, auth, coords.branch);
|
||||
}
|
||||
|
||||
export async function getManifestFromURL(): Promise<tc.IToolRelease[]> {
|
||||
core.debug('Falling back to fetching the manifest using raw URL.');
|
||||
|
||||
const manifestUrl = getManifestUrl();
|
||||
const http: httpm.HttpClient = new httpm.HttpClient('tool-cache');
|
||||
const auth = authForUrl(manifestUrl);
|
||||
const response = await http.getJson<tc.IToolRelease[]>(
|
||||
manifestUrl,
|
||||
auth ? {authorization: auth} : undefined
|
||||
);
|
||||
const response = await http.getJson<tc.IToolRelease[]>(MANIFEST_URL);
|
||||
if (!response.result) {
|
||||
throw new Error(`Unable to get manifest from ${manifestUrl}`);
|
||||
throw new Error(`Unable to get manifest from ${MANIFEST_URL}`);
|
||||
}
|
||||
return response.result;
|
||||
}
|
||||
@@ -440,11 +291,7 @@ export async function installCpythonFromRelease(release: tc.IToolRelease) {
|
||||
let pythonPath = '';
|
||||
try {
|
||||
const fileName = getDownloadFileName(downloadUrl);
|
||||
pythonPath = await tc.downloadTool(
|
||||
downloadUrl,
|
||||
fileName,
|
||||
authForUrl(downloadUrl)
|
||||
);
|
||||
pythonPath = await tc.downloadTool(downloadUrl, fileName, AUTH);
|
||||
core.info('Extract downloaded archive');
|
||||
let pythonExtractedFolder;
|
||||
if (IS_WINDOWS) {
|
||||
|
||||
@@ -2,7 +2,6 @@ import * as core from '@actions/core';
|
||||
import * as finder from './find-python.js';
|
||||
import * as finderPyPy from './find-pypy.js';
|
||||
import * as finderGraalPy from './find-graalpy.js';
|
||||
import {isMirrorCustomized} from './install-python.js';
|
||||
import * as path from 'path';
|
||||
import * as os from 'os';
|
||||
import {fileURLToPath} from 'url';
|
||||
@@ -24,21 +23,6 @@ function isGraalPyVersion(versionSpec: string) {
|
||||
return versionSpec.startsWith('graalpy');
|
||||
}
|
||||
|
||||
// `mirror` only redirects CPython distributions. PyPy and GraalPy resolve from
|
||||
// downloads.python.org and the GitHub releases API respectively, so warn rather
|
||||
// than let the input look like it applied. Only warns when the user actually
|
||||
// set a custom mirror: action.yml gives `mirror` a default, so a plain
|
||||
// getInput() check would fire on every pypy-*/graalpy-* run.
|
||||
function warnIfMirrorUnsupported(versionSpec: string) {
|
||||
if (!isMirrorCustomized()) {
|
||||
return;
|
||||
}
|
||||
const implementation = isPyPyVersion(versionSpec) ? 'PyPy' : 'GraalPy';
|
||||
core.warning(
|
||||
`The 'mirror' input only applies to CPython distributions and is ignored for ${implementation} ('${versionSpec}'), which is downloaded from its own upstream source.`
|
||||
);
|
||||
}
|
||||
|
||||
async function cacheDependencies(cache: string, pythonVersion: string) {
|
||||
const cacheDependencyPath =
|
||||
core.getInput('cache-dependency-path') || undefined;
|
||||
@@ -118,7 +102,6 @@ async function run() {
|
||||
core.startGroup('Installed versions');
|
||||
for (const version of versions) {
|
||||
if (isPyPyVersion(version)) {
|
||||
warnIfMirrorUnsupported(version);
|
||||
const installed = await finderPyPy.findPyPyVersion(
|
||||
version,
|
||||
arch,
|
||||
@@ -131,7 +114,6 @@ async function run() {
|
||||
`Successfully set up PyPy ${installed.resolvedPyPyVersion} with Python (${installed.resolvedPythonVersion})`
|
||||
);
|
||||
} else if (isGraalPyVersion(version)) {
|
||||
warnIfMirrorUnsupported(version);
|
||||
const installed = await finderGraalPy.findGraalPyVersion(
|
||||
version,
|
||||
arch,
|
||||
|
||||
Reference in New Issue
Block a user