Compare commits

..

2 Commits

Author SHA1 Message Date
1264885983 Enhance cache-dependency-path handling to support files outside the workspace root (#1128)
* ehnace cache dependency path handling

* logic update

* npm run format-check

* update cacheDependencies tests to cover resolved paths and copy edge cases

* check failure fix

* depricate-windows-2019

* refactored the code

* Check failure fix
2025-06-24 23:40:44 -05:00
e9c40fbc2b Add support for pip-version (#1129)
* Add pip-version input

* Update workflow files

* Add documentation

* Update workflow files
2025-06-19 22:09:35 -05:00
12 changed files with 427 additions and 11 deletions

View File

@ -162,3 +162,60 @@ jobs:
run: curl https://raw.githubusercontent.com/pypa/pipenv/master/get-pipenv.py | python
- name: Install dependencies
run: pipenv install requests
python-pip-dependencies-caching-with-pip-version:
name: Test pip (Python ${{ matrix.python-version}}, ${{ matrix.os }})
runs-on: ${{ matrix.os }}
strategy:
fail-fast: false
matrix:
os:
[
ubuntu-latest,
ubuntu-22.04,
ubuntu-24.04-arm,
ubuntu-22.04-arm,
windows-latest,
macos-latest,
macos-13
]
python-version: [3.13.0t, 3.13.1t, 3.13.2t]
steps:
- uses: actions/checkout@v4
- name: Setup Python
uses: ./
with:
python-version: ${{ matrix.python-version }}
cache: 'pip'
pip-version: '25.0.1'
- name: Install dependencies
run: pip install numpy pandas requests
python-pip-dependencies-caching-path-with-pip-version:
name: Test pip (Python ${{ matrix.python-version}}, ${{ matrix.os }}, caching path)
runs-on: ${{ matrix.os }}
strategy:
fail-fast: false
matrix:
os:
[
ubuntu-latest,
ubuntu-22.04,
ubuntu-24.04-arm,
ubuntu-22.04-arm,
windows-latest,
macos-latest,
macos-13
]
python-version: [3.13.0t, 3.13.1t, 3.13.2t]
steps:
- uses: actions/checkout@v4
- name: Setup Python
uses: ./
with:
python-version: ${{ matrix.python-version }}
cache: 'pip'
cache-dependency-path: __tests__/data/requirements.txt
pip-version: '25.0.1'
- name: Install dependencies
run: pip install numpy pandas requests

View File

@ -249,3 +249,60 @@ jobs:
}
- name: Run Python Script
run: pipenv run python test-pipenv.py
python-pip-dependencies-caching-with-pip-version:
name: Test pip (Python ${{ matrix.python-version}}, ${{ matrix.os }})
runs-on: ${{ matrix.os }}
strategy:
fail-fast: false
matrix:
os:
[
ubuntu-latest,
ubuntu-24.04-arm,
ubuntu-22.04,
ubuntu-22.04-arm,
windows-latest,
macos-latest,
macos-13
]
python-version: ['3.9', '3.10', '3.11', '3.12', '3.13']
steps:
- uses: actions/checkout@v4
- name: Setup Python
uses: ./
with:
python-version: ${{ matrix.python-version }}
cache: 'pip'
pip-version: '25.0.1'
- name: Install dependencies
run: pip install numpy pandas requests
python-pip-dependencies-caching-path-with-pip-version:
name: Test pip (Python ${{ matrix.python-version}}, ${{ matrix.os }}, caching path)
runs-on: ${{ matrix.os }}
strategy:
fail-fast: false
matrix:
os:
[
ubuntu-latest,
ubuntu-24.04-arm,
ubuntu-22.04,
ubuntu-22.04-arm,
windows-latest,
macos-latest,
macos-13
]
python-version: ['3.9', '3.10', '3.11', '3.12', '3.13']
steps:
- uses: actions/checkout@v4
- name: Setup Python
uses: ./
with:
python-version: ${{ matrix.python-version }}
cache: 'pip'
cache-dependency-path: __tests__/data/requirements.txt
pip-version: '25.0.1'
- name: Install dependencies
run: pip install numpy pandas requests

View File

@ -88,7 +88,6 @@ jobs:
- macos-13
- macos-14
- macos-15
- windows-2019
- windows-2022
- windows-2025
- ubuntu-22.04

View File

@ -108,6 +108,7 @@ See examples of using `cache` and `cache-dependency-path` for `pipenv` and `poet
- [Using `setup-python` with a self-hosted runner](docs/advanced-usage.md#using-setup-python-with-a-self-hosted-runner)
- [Using `setup-python` on GHES](docs/advanced-usage.md#using-setup-python-on-ghes)
- [Allow pre-releases](docs/advanced-usage.md#allow-pre-releases)
- [Using the pip-version input](docs/advanced-usage.md#using-the-pip-version-input)
## Recommended permissions

View File

@ -0,0 +1,149 @@
import * as core from '@actions/core';
import * as fs from 'fs';
import * as path from 'path';
import {cacheDependencies} from '../src/setup-python';
import {getCacheDistributor} from '../src/cache-distributions/cache-factory';
jest.mock('fs', () => {
const actualFs = jest.requireActual('fs');
return {
...actualFs,
promises: {
access: jest.fn(),
mkdir: jest.fn(),
copyFile: jest.fn(),
writeFile: jest.fn(),
appendFile: jest.fn()
}
};
});
jest.mock('@actions/core');
jest.mock('../src/cache-distributions/cache-factory');
const mockedFsPromises = fs.promises as jest.Mocked<typeof fs.promises>;
const mockedCore = core as jest.Mocked<typeof core>;
const mockedGetCacheDistributor = getCacheDistributor as jest.Mock;
describe('cacheDependencies', () => {
const mockRestoreCache = jest.fn();
beforeEach(() => {
jest.clearAllMocks();
process.env.GITHUB_ACTION_PATH = '/github/action';
process.env.GITHUB_WORKSPACE = '/github/workspace';
mockedCore.getInput.mockReturnValue('nested/deps.lock');
// Simulate file exists by resolving access without error
mockedFsPromises.access.mockImplementation(async p => {
const pathStr = typeof p === 'string' ? p : p.toString();
if (pathStr === '/github/action/nested/deps.lock') {
return Promise.resolve();
}
// Simulate directory doesn't exist to test mkdir
if (pathStr === path.dirname('/github/workspace/nested/deps.lock')) {
return Promise.reject(new Error('no dir'));
}
return Promise.resolve();
});
// Simulate mkdir success
mockedFsPromises.mkdir.mockResolvedValue(undefined);
// Simulate copyFile success
mockedFsPromises.copyFile.mockResolvedValue(undefined);
mockedGetCacheDistributor.mockReturnValue({restoreCache: mockRestoreCache});
});
it('copies the dependency file and resolves the path with directory structure', async () => {
await cacheDependencies('pip', '3.12');
const sourcePath = path.resolve('/github/action', 'nested/deps.lock');
const targetPath = path.resolve('/github/workspace', 'nested/deps.lock');
expect(mockedFsPromises.access).toHaveBeenCalledWith(
sourcePath,
fs.constants.F_OK
);
expect(mockedFsPromises.mkdir).toHaveBeenCalledWith(
path.dirname(targetPath),
{
recursive: true
}
);
expect(mockedFsPromises.copyFile).toHaveBeenCalledWith(
sourcePath,
targetPath
);
expect(mockedCore.info).toHaveBeenCalledWith(
`Copied ${sourcePath} to ${targetPath}`
);
expect(mockedCore.info).toHaveBeenCalledWith(
`Resolved cache-dependency-path: nested/deps.lock`
);
expect(mockRestoreCache).toHaveBeenCalled();
});
it('warns if the dependency file does not exist', async () => {
// Simulate file does not exist by rejecting access
mockedFsPromises.access.mockRejectedValue(new Error('file not found'));
await cacheDependencies('pip', '3.12');
expect(mockedCore.warning).toHaveBeenCalledWith(
expect.stringContaining('does not exist')
);
expect(mockedFsPromises.copyFile).not.toHaveBeenCalled();
expect(mockRestoreCache).toHaveBeenCalled();
});
it('warns if file copy fails', async () => {
// Simulate copyFile failure
mockedFsPromises.copyFile.mockRejectedValue(new Error('copy failed'));
await cacheDependencies('pip', '3.12');
expect(mockedCore.warning).toHaveBeenCalledWith(
expect.stringContaining('Failed to copy file')
);
expect(mockRestoreCache).toHaveBeenCalled();
});
it('skips path logic if no input is provided', async () => {
mockedCore.getInput.mockReturnValue('');
await cacheDependencies('pip', '3.12');
expect(mockedFsPromises.copyFile).not.toHaveBeenCalled();
expect(mockedCore.warning).not.toHaveBeenCalled();
expect(mockRestoreCache).toHaveBeenCalled();
});
it('does not copy if dependency file is already inside the workspace but still sets resolved path', async () => {
// Simulate cacheDependencyPath inside workspace
mockedCore.getInput.mockReturnValue('deps.lock');
// Override sourcePath and targetPath to be equal
const actionPath = '/github/workspace'; // same path for action and workspace
process.env.GITHUB_ACTION_PATH = actionPath;
process.env.GITHUB_WORKSPACE = actionPath;
// access resolves to simulate file exists
mockedFsPromises.access.mockResolvedValue();
await cacheDependencies('pip', '3.12');
const sourcePath = path.resolve(actionPath, 'deps.lock');
const targetPath = sourcePath; // same path
expect(mockedFsPromises.copyFile).not.toHaveBeenCalled();
expect(mockedCore.info).toHaveBeenCalledWith(
`Dependency file is already inside the workspace: ${sourcePath}`
);
expect(mockedCore.info).toHaveBeenCalledWith(
`Resolved cache-dependency-path: deps.lock`
);
expect(mockRestoreCache).toHaveBeenCalled();
});
});

View File

@ -29,6 +29,8 @@ inputs:
freethreaded:
description: "When 'true', use the freethreaded version of Python."
default: false
pip-version:
description: "Used to specify the version of pip to install with the Python. Supported format: major[.minor][.patch]."
outputs:
python-version:
description: "The installed Python or PyPy version. Useful when given a version range as input."

60
dist/setup/index.js vendored
View File

@ -95990,6 +95990,7 @@ const semver = __importStar(__nccwpck_require__(2088));
const installer = __importStar(__nccwpck_require__(1919));
const core = __importStar(__nccwpck_require__(7484));
const tc = __importStar(__nccwpck_require__(3472));
const exec = __importStar(__nccwpck_require__(5236));
// Python has "scripts" or "bin" directories where command-line tools that come with packages are installed.
// This is where pip is, along with anything that pip installs.
// There is a separate directory for `pip install --user`.
@ -96010,6 +96011,20 @@ function binDir(installDir) {
return path.join(installDir, 'bin');
}
}
function installPip(pythonLocation) {
return __awaiter(this, void 0, void 0, function* () {
const pipVersion = core.getInput('pip-version');
// Validate pip-version format: major[.minor][.patch]
const versionRegex = /^\d+(\.\d+)?(\.\d+)?$/;
if (pipVersion && !versionRegex.test(pipVersion)) {
throw new Error(`Invalid pip-version "${pipVersion}". Please specify a version in the format major[.minor][.patch].`);
}
if (pipVersion) {
core.info(`pip-version input is specified. Installing pip version ${pipVersion}`);
yield exec.exec(`${pythonLocation}/python -m pip install --upgrade pip==${pipVersion} --disable-pip-version-check --no-warn-script-location`);
}
});
}
function useCpythonVersion(version, architecture, updateEnvironment, checkLatest, allowPreReleases, freethreaded) {
return __awaiter(this, void 0, void 0, function* () {
var _a;
@ -96105,6 +96120,8 @@ function useCpythonVersion(version, architecture, updateEnvironment, checkLatest
}
core.setOutput('python-version', pythonVersion);
core.setOutput('python-path', pythonPath);
const binaryPath = utils_1.IS_WINDOWS ? installDir : _binDir;
yield installPip(binaryPath);
return { impl: 'CPython', version: pythonVersion };
});
}
@ -96827,6 +96844,7 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.cacheDependencies = void 0;
const core = __importStar(__nccwpck_require__(7484));
const finder = __importStar(__nccwpck_require__(6843));
const finderPyPy = __importStar(__nccwpck_require__(2625));
@ -96845,10 +96863,50 @@ function isGraalPyVersion(versionSpec) {
function cacheDependencies(cache, pythonVersion) {
return __awaiter(this, void 0, void 0, function* () {
const cacheDependencyPath = core.getInput('cache-dependency-path') || undefined;
const cacheDistributor = (0, cache_factory_1.getCacheDistributor)(cache, pythonVersion, cacheDependencyPath);
let resolvedDependencyPath = undefined;
if (cacheDependencyPath) {
const actionPath = process.env.GITHUB_ACTION_PATH || '';
const workspace = process.env.GITHUB_WORKSPACE || process.cwd();
const sourcePath = path.resolve(actionPath, cacheDependencyPath);
const relativePath = path.relative(actionPath, sourcePath);
const targetPath = path.resolve(workspace, relativePath);
try {
const sourceExists = yield fs_1.default.promises
.access(sourcePath, fs_1.default.constants.F_OK)
.then(() => true)
.catch(() => false);
if (!sourceExists) {
core.warning(`The resolved cache-dependency-path does not exist: ${sourcePath}`);
}
else {
if (sourcePath !== targetPath) {
const targetDir = path.dirname(targetPath);
// Create target directory if it doesn't exist
yield fs_1.default.promises.mkdir(targetDir, { recursive: true });
// Copy file asynchronously
yield fs_1.default.promises.copyFile(sourcePath, targetPath);
core.info(`Copied ${sourcePath} to ${targetPath}`);
}
else {
core.info(`Dependency file is already inside the workspace: ${sourcePath}`);
}
resolvedDependencyPath = path
.relative(workspace, targetPath)
.replace(/\\/g, '/');
core.info(`Resolved cache-dependency-path: ${resolvedDependencyPath}`);
}
}
catch (error) {
core.warning(`Failed to copy file from ${sourcePath} to ${targetPath}: ${error}`);
}
}
// Pass resolvedDependencyPath if available, else fallback to original input
const dependencyPathForCache = resolvedDependencyPath !== null && resolvedDependencyPath !== void 0 ? resolvedDependencyPath : cacheDependencyPath;
const cacheDistributor = (0, cache_factory_1.getCacheDistributor)(cache, pythonVersion, dependencyPathForCache);
yield cacheDistributor.restoreCache();
});
}
exports.cacheDependencies = cacheDependencies;
function resolveVersionInputFromDefaultFile() {
const couples = [
['.python-version', utils_1.getVersionsInputFromPlainFile]

View File

@ -22,6 +22,7 @@
- [macOS](advanced-usage.md#macos)
- [Using `setup-python` on GHES](advanced-usage.md#using-setup-python-on-ghes)
- [Allow pre-releases](advanced-usage.md#allow-pre-releases)
- [Using the pip-version input](advanced-usage.md#using-the-pip-version-input)
## Using the `python-version` input
@ -411,7 +412,7 @@ steps:
- run: pip install -e .
# Or pip install -e '.[test]' to install test dependencies
```
Note: cache-dependency-path supports files located outside the workspace root by copying them into the workspace to enable proper caching.
# Outputs and environment variables
## Outputs
@ -643,3 +644,22 @@ jobs:
- run: pipx run nox --error-on-missing-interpreters -s tests-${{ matrix.python_version }}
```
## Using the pip-version input
The `pip-version` input allows you to specify the desired version of **Pip** to use with the standard Python version.
The version of Pip should be specified in the format `major`, `major.minor`, or `major.minor.patch` (for example: 25, 25.1, or 25.0.1).
```yaml
steps:
- uses: actions/checkout@v4
- name: Set up Python
uses: actions/setup-python@v5
with:
python-version: '3.13'
pip-version: '25.0.1'
- name: Display Pip version
run: pip --version
```
> The `pip-version` input is supported only with standard Python versions. It is not available when using PyPy or GraalPy.
> Using a specific or outdated version of pip may result in compatibility or security issues and can cause job failures. For best practices and guidance, refer to the official [pip documentation](https://pip.pypa.io/en/stable/).

9
package-lock.json generated
View File

@ -34,7 +34,7 @@
"jest-circus": "^29.7.0",
"prettier": "^3.5.3",
"ts-jest": "^29.3.2",
"typescript": "^5.8.3"
"typescript": "^5.4.2"
}
},
"node_modules/@aashutoshrathi/word-wrap": {
@ -5255,11 +5255,10 @@
}
},
"node_modules/typescript": {
"version": "5.8.3",
"resolved": "https://registry.npmjs.org/typescript/-/typescript-5.8.3.tgz",
"integrity": "sha512-p1diW6TqL9L07nNxvRMM7hMMw4c5XOo/1ibL4aAIGmSAt9slTE1Xgw5KWuof2uTOvCg9BY7ZRi+GaF+7sfgPeQ==",
"version": "5.4.2",
"resolved": "https://registry.npmjs.org/typescript/-/typescript-5.4.2.tgz",
"integrity": "sha512-+2/g0Fds1ERlP6JsakQQDXjZdZMM+rqpamFZJEKh4kwTIn3iDkgKtby0CeNd5ATNZ4Ry1ax15TMx0W2V+miizQ==",
"dev": true,
"license": "Apache-2.0",
"bin": {
"tsc": "bin/tsc",
"tsserver": "bin/tsserver"

View File

@ -50,6 +50,6 @@
"jest-circus": "^29.7.0",
"prettier": "^3.5.3",
"ts-jest": "^29.3.2",
"typescript": "^5.8.3"
"typescript": "^5.4.2"
}
}

View File

@ -8,6 +8,7 @@ import * as installer from './install-python';
import * as core from '@actions/core';
import * as tc from '@actions/tool-cache';
import * as exec from '@actions/exec';
// Python has "scripts" or "bin" directories where command-line tools that come with packages are installed.
// This is where pip is, along with anything that pip installs.
@ -30,6 +31,27 @@ function binDir(installDir: string): string {
}
}
async function installPip(pythonLocation: string) {
const pipVersion = core.getInput('pip-version');
// Validate pip-version format: major[.minor][.patch]
const versionRegex = /^\d+(\.\d+)?(\.\d+)?$/;
if (pipVersion && !versionRegex.test(pipVersion)) {
throw new Error(
`Invalid pip-version "${pipVersion}". Please specify a version in the format major[.minor][.patch].`
);
}
if (pipVersion) {
core.info(
`pip-version input is specified. Installing pip version ${pipVersion}`
);
await exec.exec(
`${pythonLocation}/python -m pip install --upgrade pip==${pipVersion} --disable-pip-version-check --no-warn-script-location`
);
}
}
export async function useCpythonVersion(
version: string,
architecture: string,
@ -179,6 +201,9 @@ export async function useCpythonVersion(
core.setOutput('python-version', pythonVersion);
core.setOutput('python-path', pythonPath);
const binaryPath = IS_WINDOWS ? installDir : _binDir;
await installPip(binaryPath);
return {impl: 'CPython', version: pythonVersion};
}

View File

@ -22,13 +22,62 @@ function isGraalPyVersion(versionSpec: string) {
return versionSpec.startsWith('graalpy');
}
async function cacheDependencies(cache: string, pythonVersion: string) {
export async function cacheDependencies(cache: string, pythonVersion: string) {
const cacheDependencyPath =
core.getInput('cache-dependency-path') || undefined;
let resolvedDependencyPath: string | undefined = undefined;
if (cacheDependencyPath) {
const actionPath = process.env.GITHUB_ACTION_PATH || '';
const workspace = process.env.GITHUB_WORKSPACE || process.cwd();
const sourcePath = path.resolve(actionPath, cacheDependencyPath);
const relativePath = path.relative(actionPath, sourcePath);
const targetPath = path.resolve(workspace, relativePath);
try {
const sourceExists = await fs.promises
.access(sourcePath, fs.constants.F_OK)
.then(() => true)
.catch(() => false);
if (!sourceExists) {
core.warning(
`The resolved cache-dependency-path does not exist: ${sourcePath}`
);
} else {
if (sourcePath !== targetPath) {
const targetDir = path.dirname(targetPath);
// Create target directory if it doesn't exist
await fs.promises.mkdir(targetDir, {recursive: true});
// Copy file asynchronously
await fs.promises.copyFile(sourcePath, targetPath);
core.info(`Copied ${sourcePath} to ${targetPath}`);
} else {
core.info(
`Dependency file is already inside the workspace: ${sourcePath}`
);
}
resolvedDependencyPath = path
.relative(workspace, targetPath)
.replace(/\\/g, '/');
core.info(`Resolved cache-dependency-path: ${resolvedDependencyPath}`);
}
} catch (error) {
core.warning(
`Failed to copy file from ${sourcePath} to ${targetPath}: ${error}`
);
}
}
// Pass resolvedDependencyPath if available, else fallback to original input
const dependencyPathForCache = resolvedDependencyPath ?? cacheDependencyPath;
const cacheDistributor = getCacheDistributor(
cache,
pythonVersion,
cacheDependencyPath
dependencyPathForCache
);
await cacheDistributor.restoreCache();
}