mirror of
https://github.com/actions/setup-dotnet.git
synced 2026-11-28 17:15:50 +00:00
Compare commits
3 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
84bc3a3451 | ||
|
|
0f4a354dd5 | ||
|
|
6ec5c6b286 |
26
.github/workflows/e2e-tests.yml
vendored
26
.github/workflows/e2e-tests.yml
vendored
@@ -12,6 +12,32 @@ on:
|
||||
- '**.md'
|
||||
|
||||
jobs:
|
||||
test-runtime-only:
|
||||
runs-on: ${{ matrix.operating-system }}
|
||||
strategy:
|
||||
fail-fast: false
|
||||
matrix:
|
||||
operating-system: [ubuntu-latest, windows-latest, macos-latest]
|
||||
steps:
|
||||
- name: Checkout
|
||||
uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
|
||||
- name: Clear toolcache
|
||||
shell: pwsh
|
||||
run: __tests__/clear-toolcache.ps1 ${{ runner.os }}
|
||||
- name: Setup dotnet runtime 8.0.11
|
||||
uses: ./
|
||||
with:
|
||||
dotnet-runtime: 8.0.11
|
||||
- name: Verify dotnet runtimes
|
||||
shell: pwsh
|
||||
run: |
|
||||
$runtimes = dotnet --list-runtimes
|
||||
foreach ($runtime in 'Microsoft.NETCore.App', 'Microsoft.AspNetCore.App') {
|
||||
if (-not ($runtimes -like "$runtime 8.0.11 *")) {
|
||||
throw "$runtime 8.0.11 was not installed."
|
||||
}
|
||||
}
|
||||
|
||||
test-setup-multiple-versions:
|
||||
runs-on: ${{ matrix.operating-system }}
|
||||
strategy:
|
||||
|
||||
48
README.md
48
README.md
@@ -53,15 +53,41 @@ steps:
|
||||
9.0.x
|
||||
- run: dotnet build <my project>
|
||||
```
|
||||
|
||||
## Installing additional runtimes
|
||||
|
||||
The `dotnet-runtime` input allows you to install .NET runtimes separately from SDKs. This is useful for multi-targeting scenarios where you need one SDK version but multiple runtime versions.
|
||||
|
||||
When `dotnet-runtime` is specified, both the .NET Runtime (Microsoft.NETCore.App) and the ASP.NET Core Runtime (Microsoft.AspNetCore.App) are installed for each specified version. Before .NET Core 2.1, only the base runtime is installed.
|
||||
|
||||
For exact preview/RC versions, release metadata selects the matching ASP.NET Core build. If the mapping is unavailable, the action warns and tries the same exact version; installer failures remain fatal. `dotnet-quality` continues to apply to both SDKs and runtimes.
|
||||
|
||||
`dotnet-runtime` doesn't change how the SDK is selected, so it doesn't suppress the SDK installation from `global.json`. For example, if only `dotnet-runtime` is set and the repository root contains a `global.json` file, the SDK version specified in that file is installed as well, and the `dotnet-version` output contains that SDK version.
|
||||
|
||||
**Example: Install SDK 10 with runtimes 8 and 9**:
|
||||
```yml
|
||||
steps:
|
||||
- uses: actions/checkout@v7
|
||||
- name: Setup dotnet
|
||||
uses: actions/setup-dotnet@v6
|
||||
with:
|
||||
dotnet-version: '10.0.x'
|
||||
dotnet-runtime: |
|
||||
8.0.x
|
||||
9.0.x
|
||||
- run: dotnet build <my project>
|
||||
- run: dotnet test <my project>
|
||||
```
|
||||
|
||||
## Supported version syntax
|
||||
|
||||
The `dotnet-version` input supports following syntax:
|
||||
The `dotnet-version` and `dotnet-runtime` inputs support the following syntax:
|
||||
|
||||
- **A.B.C** (e.g 9.0.308, 10.0.100-preview.1.25120.13) - installs exact version of .NET SDK
|
||||
- **A.B** or **A.B.x** (e.g. 8.0, 8.0.x) - installs the latest patch version of .NET SDK on the channel `8.0`, including prerelease versions (preview, rc)
|
||||
- **A.B.C** (e.g 9.0.308 for an SDK, 9.0.9 for a runtime, 10.0.100-preview.1.25120.13) - installs exact version of .NET SDK or runtime
|
||||
- **A.B** or **A.B.x** (e.g. 8.0, 8.0.x) - installs the latest patch version on the channel `8.0`, including prerelease versions (preview, rc)
|
||||
- **A** or **A.x** (e.g. 8, 8.x) - installs the latest minor version of the specified major tag, including prerelease versions (preview, rc)
|
||||
- **A.B.Cxx** (e.g. 8.0.4xx) - available since `.NET 5.0` release. Installs the latest version of the specific SDK release, including prerelease versions (preview, rc).
|
||||
- **latest** - dynamically resolves to the highest active .NET SDK version. By default, it installs the latest **stable (GA)** version (excluding previews and end-of-life releases). Can be combined with `dotnet-channel` and `dotnet-quality`.
|
||||
- **A.B.Cxx** (e.g. 8.0.4xx) - `dotnet-version` only, available since `.NET 5.0` release. Installs the latest version of the specific SDK feature band, including prerelease versions (preview, rc). Feature bands apply only to SDKs, so `dotnet-runtime` rejects this syntax; use **A.B** or **A.B.x** (e.g. 8.0.x) for the latest runtime patch instead.
|
||||
- **latest** - dynamically resolves to the highest active .NET version. By default, it installs the latest **stable (GA)** version (excluding previews and end-of-life releases). For both `dotnet-version` and `dotnet-runtime`, it can be combined with `dotnet-channel` and `dotnet-quality`.
|
||||
|
||||
## Using with `dotnet-channel` input
|
||||
|
||||
@@ -74,7 +100,7 @@ The optional `dotnet-channel` input specifies the source channel for the install
|
||||
| `A.B` (e.g. `8.0`) | A specific release channel |
|
||||
| `A.B.Cxx` (e.g. `8.0.1xx`) | A specific SDK release (available since 5.0) |
|
||||
|
||||
> **Note**: The `dotnet-channel` input is only applied when `dotnet-version` is set to `latest`. If used with a specific version, a warning will be logged and the channel input will be ignored.
|
||||
> **Note**: The `dotnet-channel` input applies to `latest` entries in `dotnet-version` or `dotnet-runtime`; otherwise it is ignored with a warning. For `dotnet-runtime`, an `A.B.Cxx` channel uses its `A.B` channel (e.g. `8.0.1xx` installs the latest `8.0` runtime), without affecting SDK installation.
|
||||
|
||||
**Install latest LTS version:**
|
||||
```yaml
|
||||
@@ -357,6 +383,8 @@ An installed SDK is reused only when it matches the requested spec (`A.B.C`, `A.
|
||||
|
||||
When the request comes from `global.json`, the SDK is picked the way the .NET resolver picks one: `latestPatch`, `latestFeature`, `latestMinor` and `latestMajor` take the **highest** SDK the policy allows, while `feature`, `minor` and `major` roll forward to the **nearest** higher feature band, minor or major and then take its latest patch. `patch` — the default when `rollForward` is omitted — prefers the declared version, otherwise the latest patch in its band. `disable` and a prerelease `sdk.version` require an exact match, and `allowPrerelease` is not used: `dotnet-quality` is the only prerelease control.
|
||||
|
||||
`check-latest: false` also reuses matching runtime pairs, including those installed by an SDK. Reuse requires each framework's `.deps.json` and a runnable `dotnet` executable; a preview ASP.NET Core runtime pairs with the .NET runtime named in its `runtimeconfig.json`, and before .NET Core 2.1, only the base framework is required. Incomplete pairs, cross-architecture requests, LTS/STS channels and bare wildcards use the online path, so this is not a guarantee of offline operation. The online installer skips versions that are already present, so falling back does not repair a damaged installation.
|
||||
|
||||
### Setting `check-latest` from the environment
|
||||
|
||||
When the input is not set, the action reads the `DOTNET_CHECK_LATEST` environment variable (`true` or `false`, case-insensitive; an unsupported value warns and is ignored), which covers workflows you cannot edit. Setting it on a self-hosted runner alongside SDKs preinstalled under [`DOTNET_INSTALL_DIR`](#environment-variables) lets those workflows run without reaching `aka.ms`, `builds.dotnet.microsoft.com` or `ci.dot.net`. It applies to every job on that runner, so a dedicated runner is recommended; any workflow can still override it with an explicit `check-latest` input.
|
||||
@@ -452,7 +480,13 @@ You can also set `DOTNET_INSTALL_DIR` to a value based on runtime variables, suc
|
||||
- name: Set DOTNET_INSTALL_DIR
|
||||
run: echo "DOTNET_INSTALL_DIR=$HOME/.dotnet" >> $GITHUB_ENV
|
||||
```
|
||||
> **Note**: On some self-hosted or large Linux runners, installing .NET under the default `/usr/share/dotnet` location may fail due to insufficient permissions. To ensure successful installation, set `DOTNET_INSTALL_DIR` to a user-writable path.
|
||||
> **Note**: On some self-hosted, larger or containerized runners the default location is not writable by the current user, and the installation fails with a permission error. The action resolves the install directory in this order:
|
||||
>
|
||||
> 1. `DOTNET_INSTALL_DIR`, when set. It is always honored and never probed.
|
||||
> 2. The default location for the runner OS, when it is writable.
|
||||
> 3. `.dotnet` in the current user's home directory, for example `/home/runner/.dotnet` or `C:\Users\runneradmin\.dotnet`.
|
||||
>
|
||||
> Runners that can write to the default location are unaffected. When the fallback is used, `DOTNET_ROOT` and `PATH` point at the home directory, so .NET preinstalled under the system location is no longer picked up. Set `DOTNET_INSTALL_DIR` explicitly to pin the location. If no writable location is found, the action warns and keeps the default, so the installation is likely to fail.
|
||||
|
||||
## Recommended permissions
|
||||
|
||||
|
||||
@@ -11,6 +11,7 @@ import {
|
||||
import each from 'jest-each';
|
||||
import semver from 'semver';
|
||||
import fspromises from 'fs/promises';
|
||||
import type {Stats} from 'fs';
|
||||
import os from 'os';
|
||||
import path from 'path';
|
||||
|
||||
@@ -35,31 +36,55 @@ jest.unstable_mockModule('@actions/io', () => ({
|
||||
jest.unstable_mockModule('fs', () => {
|
||||
const actual = jest.requireActual('fs') as typeof import('fs');
|
||||
const chmodSync = jest.fn();
|
||||
const lstatSync = jest.fn(actual.lstatSync);
|
||||
const mkdtempSync = jest.fn(actual.mkdtempSync);
|
||||
const rmSync = jest.fn(actual.rmSync);
|
||||
const readdirSync = jest.fn();
|
||||
const readFileSync = jest.fn(actual.readFileSync);
|
||||
const existsSync = jest.fn(() => true);
|
||||
const statSync = jest.fn(() => ({isFile: () => true}));
|
||||
const accessSync = jest.fn();
|
||||
return {
|
||||
...actual,
|
||||
chmodSync,
|
||||
readdirSync,
|
||||
existsSync,
|
||||
statSync,
|
||||
accessSync,
|
||||
default: {
|
||||
const mocked = {
|
||||
...actual,
|
||||
chmodSync,
|
||||
lstatSync,
|
||||
mkdtempSync,
|
||||
rmSync,
|
||||
readdirSync,
|
||||
readFileSync,
|
||||
existsSync,
|
||||
statSync,
|
||||
accessSync
|
||||
}
|
||||
};
|
||||
return {
|
||||
...mocked,
|
||||
default: mocked
|
||||
};
|
||||
});
|
||||
|
||||
jest.unstable_mockModule('os', () => {
|
||||
const actual = jest.requireActual('os') as typeof import('os');
|
||||
// os.homedir() reads the real environment, not jest's process.env.
|
||||
const homedir = jest.fn(actual.homedir);
|
||||
// Resolved per call, so spies placed on the real module still take effect.
|
||||
const arch = () => actual.arch();
|
||||
return {...actual, homedir, arch, default: {...actual, homedir, arch}};
|
||||
});
|
||||
|
||||
// Allows tests to re-import the installer as if running on another OS.
|
||||
let platformOverride: 'windows' | 'linux' | 'mac' | undefined;
|
||||
jest.unstable_mockModule('../src/utils.js', () => {
|
||||
const actual = jest.requireActual(
|
||||
'../src/utils.js'
|
||||
) as typeof import('../src/utils.js');
|
||||
const platform = platformOverride ?? actual.PLATFORM;
|
||||
return {...actual, PLATFORM: platform, IS_WINDOWS: platform === 'windows'};
|
||||
});
|
||||
|
||||
const exec = await import('@actions/exec');
|
||||
const core = await import('@actions/core');
|
||||
const io = await import('@actions/io');
|
||||
const hc = await import('@actions/http-client');
|
||||
const fs = await import('fs');
|
||||
const installer = await import('../src/installer.js');
|
||||
const {IS_WINDOWS} = await import('../src/utils.js');
|
||||
@@ -1349,6 +1374,182 @@ describe('installer tests', () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe('installRuntime() tests', () => {
|
||||
const readdirSyncSpy = fs.readdirSync as unknown as jest.Mock;
|
||||
const statSyncSpy = fs.statSync as unknown as jest.Mock;
|
||||
const accessSyncSpy = fs.accessSync as unknown as jest.Mock;
|
||||
const scriptArgs = () =>
|
||||
getExecOutputSpy.mock.calls.map(call =>
|
||||
(call[1] as string[]).join(' ')
|
||||
);
|
||||
const arg = (name: string, value: string) =>
|
||||
IS_WINDOWS ? `-${name} ${value}` : `--${name.toLowerCase()} ${value}`;
|
||||
|
||||
beforeEach(() => {
|
||||
jest.clearAllMocks();
|
||||
delete process.env['DOTNET_INSTALL_DIR'];
|
||||
whichSpy.mockImplementation(() => Promise.resolve('PathToShell'));
|
||||
chmodSyncSpy.mockImplementation(() => {});
|
||||
readdirSyncSpy.mockReturnValue([]);
|
||||
statSyncSpy.mockReturnValue({isFile: () => true});
|
||||
accessSyncSpy.mockImplementation(() => undefined);
|
||||
getExecOutputSpy.mockImplementation(() =>
|
||||
Promise.resolve({
|
||||
exitCode: 0,
|
||||
stdout: 'Installed version is 8.0.11',
|
||||
stderr: ''
|
||||
})
|
||||
);
|
||||
});
|
||||
|
||||
afterAll(() => {
|
||||
jest.resetAllMocks();
|
||||
});
|
||||
|
||||
it('should install the .NET and ASP.NET Core runtimes and set DOTNET_INSTALL_DIR', async () => {
|
||||
const installedVersion = await new installer.DotnetCoreInstaller(
|
||||
'8.0.11',
|
||||
''
|
||||
).installRuntime();
|
||||
|
||||
expect(installedVersion).toBe('8.0.11');
|
||||
expect(process.env['DOTNET_INSTALL_DIR']).toBe(
|
||||
installer.DotnetInstallDir.dirPath
|
||||
);
|
||||
expect(scriptArgs()).toHaveLength(2);
|
||||
expect(scriptArgs()[0]).toContain(arg('Runtime', 'dotnet'));
|
||||
expect(scriptArgs()[1]).toContain(arg('Runtime', 'aspnetcore'));
|
||||
for (const args of scriptArgs()) {
|
||||
expect(args).toContain(arg('Version', '8.0.11'));
|
||||
}
|
||||
});
|
||||
|
||||
it('should install the ASP.NET Core build paired with a prerelease runtime', async () => {
|
||||
const getJsonSpy = jest
|
||||
.spyOn(hc.HttpClient.prototype, 'getJson')
|
||||
.mockResolvedValue({
|
||||
statusCode: 200,
|
||||
headers: {},
|
||||
result: {
|
||||
releases: [
|
||||
{
|
||||
runtime: {version: '8.0.0-rc.2.23479.6'},
|
||||
'aspnetcore-runtime': {version: '8.0.0-rc.2.23480.2'}
|
||||
}
|
||||
]
|
||||
}
|
||||
});
|
||||
|
||||
try {
|
||||
await new installer.DotnetCoreInstaller(
|
||||
'8.0.0-rc.2.23479.6',
|
||||
''
|
||||
).installRuntime();
|
||||
} finally {
|
||||
getJsonSpy.mockRestore();
|
||||
}
|
||||
|
||||
expect(scriptArgs()[0]).toContain(arg('Version', '8.0.0-rc.2.23479.6'));
|
||||
expect(scriptArgs()[1]).toContain(arg('Version', '8.0.0-rc.2.23480.2'));
|
||||
});
|
||||
|
||||
it('should reuse a complete local runtime pair when check-latest is false', async () => {
|
||||
readdirSyncSpy.mockReturnValue([
|
||||
{name: '8.0.11', isDirectory: () => true, isSymbolicLink: () => false}
|
||||
]);
|
||||
|
||||
const installedVersion = await new installer.DotnetCoreInstaller(
|
||||
'8.0.x',
|
||||
'',
|
||||
undefined,
|
||||
undefined,
|
||||
false
|
||||
).installRuntime();
|
||||
|
||||
expect(installedVersion).toBe('8.0.11');
|
||||
expect(getExecOutputSpy).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
describe('check-latest: false preview runtime pairing', () => {
|
||||
const readFileSyncSpy = fs.readFileSync as unknown as jest.Mock;
|
||||
const runtimeVersion = '8.0.0-rc.2.23479.6';
|
||||
const config = (version: string) => () =>
|
||||
JSON.stringify({
|
||||
runtimeOptions: {
|
||||
framework: {name: 'Microsoft.NETCore.App', version}
|
||||
}
|
||||
});
|
||||
|
||||
afterEach(() => readFileSyncSpy.mockReset());
|
||||
|
||||
it.each([
|
||||
['skip installation for a valid mapping', config(runtimeVersion), 0],
|
||||
[
|
||||
'fall back online for a missing config',
|
||||
() => {
|
||||
throw new Error('ENOENT');
|
||||
},
|
||||
2
|
||||
],
|
||||
['fall back online for a malformed config', () => '{', 2],
|
||||
[
|
||||
'fall back online for an absent declared runtime',
|
||||
config('8.0.0-rc.2.23475.1'),
|
||||
2
|
||||
]
|
||||
])('should %s', async (_, readConfig, installCalls) => {
|
||||
// The ASP.NET Core preview build differs from the .NET runtime build.
|
||||
readdirSyncSpy.mockImplementation((...args: unknown[]) =>
|
||||
[
|
||||
path.basename(args[0] as string) === 'Microsoft.NETCore.App'
|
||||
? runtimeVersion
|
||||
: '8.0.0-rc.2.23480.2'
|
||||
].map(name => ({
|
||||
name,
|
||||
isDirectory: () => true,
|
||||
isSymbolicLink: () => false
|
||||
}))
|
||||
);
|
||||
readFileSyncSpy.mockImplementation(readConfig);
|
||||
const getJsonSpy = jest
|
||||
.spyOn(hc.HttpClient.prototype, 'getJson')
|
||||
.mockRejectedValue(new Error('offline'));
|
||||
|
||||
try {
|
||||
await new installer.DotnetCoreInstaller(
|
||||
runtimeVersion,
|
||||
'',
|
||||
undefined,
|
||||
undefined,
|
||||
false
|
||||
).installRuntime();
|
||||
} finally {
|
||||
getJsonSpy.mockRestore();
|
||||
}
|
||||
|
||||
expect(getExecOutputSpy).toHaveBeenCalledTimes(installCalls);
|
||||
});
|
||||
});
|
||||
|
||||
it.each([
|
||||
[
|
||||
'8.0.1xx',
|
||||
` The A.B.Cxx feature band syntax applies only to .NET SDKs and is supported only by 'dotnet-version'.`
|
||||
],
|
||||
['abc', '']
|
||||
])(
|
||||
"should reject '%s' with an error naming 'dotnet-runtime' before installing",
|
||||
async (version, reason) => {
|
||||
await expect(
|
||||
new installer.DotnetCoreInstaller(version, '').installRuntime()
|
||||
).rejects.toThrow(
|
||||
`The 'dotnet-runtime' was supplied in invalid format: ${version}!${reason} Supported syntax: A.B.C, A.B, A.B.x, A, A.x, latest`
|
||||
);
|
||||
expect(getExecOutputSpy).not.toHaveBeenCalled();
|
||||
}
|
||||
);
|
||||
});
|
||||
|
||||
describe('addToPath() tests', () => {
|
||||
it(`should export DOTNET_ROOT env.var with value from DOTNET_INSTALL_DIR env.var`, async () => {
|
||||
process.env['DOTNET_INSTALL_DIR'] = 'fictitious/dotnet/install/dir';
|
||||
@@ -1364,6 +1565,240 @@ describe('installer tests', () => {
|
||||
expect(path).toContain(process.env['DOTNET_INSTALL_DIR']);
|
||||
});
|
||||
});
|
||||
|
||||
describe('install directory fallback tests', () => {
|
||||
// Mock factories re-run on resetModules, so the installer sees new
|
||||
// instances; configure those, not the ones captured at file load.
|
||||
const importInstallerFor = async (
|
||||
platform: 'windows' | 'linux' | 'mac',
|
||||
isWritable: (dir: string) => boolean
|
||||
) => {
|
||||
platformOverride = platform;
|
||||
jest.resetModules();
|
||||
|
||||
const freshFs = await import('fs');
|
||||
(freshFs.lstatSync as jest.Mock).mockReturnValue({} as Stats);
|
||||
(freshFs.mkdtempSync as jest.Mock).mockImplementation(
|
||||
(...args: unknown[]) => {
|
||||
const prefix = String(args[0]);
|
||||
if (!isWritable(path.dirname(prefix))) {
|
||||
throw Object.assign(new Error('permission denied'), {
|
||||
code: 'EACCES'
|
||||
});
|
||||
}
|
||||
return `${prefix}abc123`;
|
||||
}
|
||||
);
|
||||
(freshFs.rmSync as jest.Mock).mockImplementation(() => {});
|
||||
|
||||
const freshCore = await import('@actions/core');
|
||||
const freshOs = await import('os');
|
||||
const {DotnetInstallDir} = await import('../src/installer.js');
|
||||
|
||||
return {DotnetInstallDir, core: freshCore, fs: freshFs, os: freshOs};
|
||||
};
|
||||
|
||||
const probedDirs = (freshFs: typeof import('fs')) =>
|
||||
(freshFs.mkdtempSync as jest.Mock).mock.calls.map(call =>
|
||||
path.dirname(String(call[0]))
|
||||
);
|
||||
|
||||
beforeEach(() => {
|
||||
delete process.env['DOTNET_INSTALL_DIR'];
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
platformOverride = undefined;
|
||||
});
|
||||
|
||||
it(`should use the default location when it is writable`, async () => {
|
||||
const {DotnetInstallDir} = await importInstallerFor(
|
||||
'linux',
|
||||
() => true
|
||||
);
|
||||
|
||||
expect(DotnetInstallDir.dirPath).toBe('/usr/share/dotnet');
|
||||
});
|
||||
|
||||
it(`should fall back to the home directory when the default location is not writable`, async () => {
|
||||
const fallbackPath = path.join(os.homedir(), '.dotnet');
|
||||
const {DotnetInstallDir, core: freshCore} = await importInstallerFor(
|
||||
'linux',
|
||||
dir => dir === fallbackPath
|
||||
);
|
||||
|
||||
expect(DotnetInstallDir.dirPath).toBe(fallbackPath);
|
||||
expect(freshCore.warning).toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it(`should reject a dangling symlink instead of probing its writable parent`, async () => {
|
||||
// Resolved, because that is the form the probe receives on every platform.
|
||||
const linkPath = path.resolve('/usr/share/dotnet');
|
||||
const {DotnetInstallDir, fs: freshFs} = await importInstallerFor(
|
||||
'linux',
|
||||
() => true
|
||||
);
|
||||
// A dangling link exists for lstat, but nothing can be created under it.
|
||||
(freshFs.mkdtempSync as jest.Mock).mockImplementation(
|
||||
(...args: unknown[]) => {
|
||||
if (path.dirname(String(args[0])) === linkPath) {
|
||||
throw Object.assign(new Error('no such file or directory'), {
|
||||
code: 'ENOENT'
|
||||
});
|
||||
}
|
||||
return `${args[0]}abc123`;
|
||||
}
|
||||
);
|
||||
|
||||
expect(DotnetInstallDir.dirPath).toBe(
|
||||
path.join(os.homedir(), '.dotnet')
|
||||
);
|
||||
const probed = probedDirs(freshFs);
|
||||
expect(probed).toContain(linkPath);
|
||||
expect(probed).not.toContain(path.dirname(linkPath));
|
||||
});
|
||||
|
||||
it(`should probe the nearest existing parent when the directory is missing`, async () => {
|
||||
const systemPath = path.resolve('/usr/share/dotnet');
|
||||
const parentPath = path.dirname(systemPath);
|
||||
const {DotnetInstallDir, fs: freshFs} = await importInstallerFor(
|
||||
'linux',
|
||||
() => true
|
||||
);
|
||||
// Only the parent exists, so the walk has to climb before probing.
|
||||
(freshFs.lstatSync as jest.Mock).mockImplementation(
|
||||
(...args: unknown[]) =>
|
||||
path.resolve(String(args[0])) === parentPath
|
||||
? ({} as Stats)
|
||||
: undefined
|
||||
);
|
||||
|
||||
expect(DotnetInstallDir.dirPath).toBe('/usr/share/dotnet');
|
||||
const probed = probedDirs(freshFs);
|
||||
expect(probed).toContain(parentPath);
|
||||
expect(probed).not.toContain(systemPath);
|
||||
});
|
||||
|
||||
it(`should give up at the filesystem root when no ancestor exists`, async () => {
|
||||
const systemPath = path.resolve('/usr/share/dotnet');
|
||||
const homePath = path.join(os.homedir(), '.dotnet');
|
||||
const {DotnetInstallDir, fs: freshFs} = await importInstallerFor(
|
||||
'linux',
|
||||
() => true
|
||||
);
|
||||
// Nothing on the system path exists, all the way up to the root.
|
||||
(freshFs.lstatSync as jest.Mock).mockImplementation(
|
||||
(...args: unknown[]) =>
|
||||
systemPath.startsWith(path.resolve(String(args[0])))
|
||||
? undefined
|
||||
: ({} as Stats)
|
||||
);
|
||||
|
||||
expect(DotnetInstallDir.dirPath).toBe(homePath);
|
||||
// The walk hit the root and returned without ever probing.
|
||||
expect(probedDirs(freshFs)).toEqual([homePath]);
|
||||
});
|
||||
|
||||
it(`should not probe a relative default location`, async () => {
|
||||
// An unset HOME makes the macOS default relative, e.g. 'undefined/.dotnet'.
|
||||
delete process.env['HOME'];
|
||||
const homePath = path.join(os.homedir(), '.dotnet');
|
||||
const {DotnetInstallDir, fs: freshFs} = await importInstallerFor(
|
||||
'mac',
|
||||
() => true
|
||||
);
|
||||
|
||||
expect(DotnetInstallDir.dirPath).toBe(homePath);
|
||||
expect(probedDirs(freshFs)).not.toContain(process.cwd());
|
||||
});
|
||||
|
||||
it(`should not probe a relative default location on Windows`, async () => {
|
||||
// An unset PROGRAMFILES makes the Windows default relative.
|
||||
delete process.env['PROGRAMFILES'];
|
||||
const homePath = path.join(os.homedir(), '.dotnet');
|
||||
const {DotnetInstallDir, fs: freshFs} = await importInstallerFor(
|
||||
'windows',
|
||||
() => true
|
||||
);
|
||||
|
||||
expect(DotnetInstallDir.dirPath).toBe(homePath);
|
||||
expect(probedDirs(freshFs)).not.toContain(process.cwd());
|
||||
});
|
||||
|
||||
it(`should not treat the filesystem root as a home directory`, async () => {
|
||||
const root = path.parse(process.cwd()).root;
|
||||
const rootDotnet = path.join(root, '.dotnet');
|
||||
// Only the root candidate is writable, so an unguarded run would pick it.
|
||||
const {
|
||||
DotnetInstallDir,
|
||||
os: freshOs,
|
||||
core: freshCore
|
||||
} = await importInstallerFor('linux', dir => dir === rootDotnet);
|
||||
(freshOs.homedir as jest.Mock).mockReturnValue(root);
|
||||
|
||||
expect(DotnetInstallDir.dirPath).toBe('/usr/share/dotnet');
|
||||
expect(freshCore.warning).toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it(`should still report writable when the probe cannot be removed`, async () => {
|
||||
const {DotnetInstallDir, fs: freshFs} = await importInstallerFor(
|
||||
'linux',
|
||||
() => true
|
||||
);
|
||||
(freshFs.rmSync as jest.Mock).mockImplementation(() => {
|
||||
throw Object.assign(new Error('device or resource busy'), {
|
||||
code: 'EBUSY'
|
||||
});
|
||||
});
|
||||
|
||||
expect(DotnetInstallDir.dirPath).toBe('/usr/share/dotnet');
|
||||
});
|
||||
|
||||
it(`should keep the shared macOS location and warn when it is not writable`, async () => {
|
||||
// The mac default derives from HOME, homeInstallPath() from os.homedir();
|
||||
// aligning them is what makes both candidates the same path.
|
||||
process.env['HOME'] = os.homedir();
|
||||
const homePath = path.join(os.homedir(), '.dotnet');
|
||||
const {
|
||||
DotnetInstallDir,
|
||||
fs: freshFs,
|
||||
core: freshCore
|
||||
} = await importInstallerFor('mac', () => false);
|
||||
|
||||
expect(DotnetInstallDir.dirPath).toBe(homePath);
|
||||
// One candidate, so it is probed once rather than twice.
|
||||
expect(probedDirs(freshFs)).toEqual([homePath]);
|
||||
expect(freshCore.warning).toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it(`should prefer DOTNET_INSTALL_DIR env.var without probing`, async () => {
|
||||
process.env['DOTNET_INSTALL_DIR'] = path.join(path.sep, 'custom');
|
||||
const {DotnetInstallDir, fs: freshFs} = await importInstallerFor(
|
||||
'linux',
|
||||
() => false
|
||||
);
|
||||
|
||||
expect(DotnetInstallDir.dirPath).toBe(path.join(path.sep, 'custom'));
|
||||
expect(freshFs.mkdtempSync as jest.Mock).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it(`should resolve once, and not before the directory is needed`, async () => {
|
||||
const {DotnetInstallDir, fs: freshFs} = await importInstallerFor(
|
||||
'linux',
|
||||
() => true
|
||||
);
|
||||
const probe = freshFs.mkdtempSync as jest.Mock;
|
||||
|
||||
expect(probe).not.toHaveBeenCalled();
|
||||
|
||||
void DotnetInstallDir.dirPath;
|
||||
const afterFirstRead = probe.mock.calls.length;
|
||||
void DotnetInstallDir.dirPath;
|
||||
|
||||
expect(afterFirstRead).toBeGreaterThan(0);
|
||||
expect(probe.mock.calls.length).toBe(afterFirstRead);
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe('normalizeArch() tests', () => {
|
||||
|
||||
@@ -9,6 +9,7 @@ import {
|
||||
} from '@jest/globals';
|
||||
import semver from 'semver';
|
||||
import os from 'os';
|
||||
import path from 'path';
|
||||
|
||||
jest.unstable_mockModule('@actions/core', () => ({
|
||||
getInput: jest.fn(),
|
||||
@@ -75,6 +76,11 @@ describe('setup-dotnet tests', () => {
|
||||
'installDotnet'
|
||||
);
|
||||
|
||||
const installRuntimeSpy = jest.spyOn(
|
||||
DotnetCoreInstaller.prototype,
|
||||
'installRuntime'
|
||||
);
|
||||
|
||||
const isCacheFeatureAvailableSpy =
|
||||
cacheUtils.isCacheFeatureAvailable as jest.Mock;
|
||||
const restoreCacheSpy = cacheRestore.restoreCache as jest.Mock;
|
||||
@@ -84,6 +90,7 @@ describe('setup-dotnet tests', () => {
|
||||
describe('run() tests', () => {
|
||||
beforeEach(() => {
|
||||
DotnetInstallDir.addToPath = jest.fn();
|
||||
inputs['dotnet-runtime'] = [];
|
||||
getMultilineInputSpy.mockImplementation(input => inputs[input as string]);
|
||||
getInputSpy.mockImplementation(input => inputs[input as string]);
|
||||
getBooleanInputSpy.mockImplementation(input => {
|
||||
@@ -205,6 +212,97 @@ describe('setup-dotnet tests', () => {
|
||||
expect(DotnetInstallDir.addToPath).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
describe('dotnet-runtime input', () => {
|
||||
beforeEach(() => {
|
||||
inputs['global-json-file'] = '';
|
||||
inputs['dotnet-version'] = [];
|
||||
inputs['dotnet-quality'] = '';
|
||||
inputs['dotnet-channel'] = '';
|
||||
inputs['architecture'] = '';
|
||||
existsSyncSpy.mockReturnValue(false);
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
inputs['dotnet-channel'] = '';
|
||||
inputs['dotnet-quality'] = '';
|
||||
inputs['check-latest'] = '';
|
||||
inputs['architecture'] = '';
|
||||
delete process.env['DOTNET_INSTALL_DIR'];
|
||||
});
|
||||
|
||||
it('should install unique runtime versions, add PATH and not set the dotnet-version output without an SDK', async () => {
|
||||
inputs['dotnet-runtime'] = ['8.0.x', '9.0.x', '8.0.x'];
|
||||
installRuntimeSpy
|
||||
.mockResolvedValueOnce('8.0.11')
|
||||
.mockResolvedValueOnce('9.0.1');
|
||||
|
||||
await setup.run();
|
||||
expect(setFailedSpy).not.toHaveBeenCalled();
|
||||
expect(installDotnetSpy).not.toHaveBeenCalled();
|
||||
expect(installRuntimeSpy).toHaveBeenCalledTimes(2);
|
||||
expect(DotnetInstallDir.addToPath).toHaveBeenCalledTimes(1);
|
||||
expect(setOutputSpy).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('should forward dotnet-channel (feature band as A.B), dotnet-quality and check-latest to runtime latest', async () => {
|
||||
inputs['dotnet-runtime'] = ['latest'];
|
||||
inputs['dotnet-channel'] = '8.0.1xx';
|
||||
inputs['dotnet-quality'] = 'preview';
|
||||
inputs['check-latest'] = 'false';
|
||||
let capturedOptions: object | undefined;
|
||||
installRuntimeSpy.mockImplementation(function (this: {
|
||||
dotnetChannel?: string;
|
||||
quality: string;
|
||||
checkLatest: boolean;
|
||||
}) {
|
||||
capturedOptions = {
|
||||
dotnetChannel: this.dotnetChannel,
|
||||
quality: this.quality,
|
||||
checkLatest: this.checkLatest
|
||||
};
|
||||
return Promise.resolve('8.0.0-preview.1');
|
||||
});
|
||||
|
||||
await setup.run();
|
||||
expect(setFailedSpy).not.toHaveBeenCalled();
|
||||
expect(capturedOptions).toEqual({
|
||||
dotnetChannel: '8.0',
|
||||
quality: 'preview',
|
||||
checkLatest: false
|
||||
});
|
||||
});
|
||||
|
||||
it('should fail the action if unsupported dotnet-channel value is provided with runtime latest', async () => {
|
||||
inputs['dotnet-runtime'] = ['latest'];
|
||||
inputs['dotnet-channel'] = 'invalid';
|
||||
|
||||
await setup.run();
|
||||
expect(setFailedSpy).toHaveBeenCalledWith(
|
||||
`Value 'invalid' is not supported for the 'dotnet-channel' option. Supported values are: LTS, STS, A.B (e.g. 8.0), A.B.Cxx (e.g. 8.0.1xx).`
|
||||
);
|
||||
expect(installRuntimeSpy).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('should keep the cross-architecture DOTNET_INSTALL_DIR after installing an SDK and a runtime', async () => {
|
||||
const architecture = os.arch() === 'arm64' ? 'x64' : 'arm64';
|
||||
inputs['dotnet-version'] = ['8.0.x'];
|
||||
inputs['dotnet-runtime'] = ['9.0.x'];
|
||||
inputs['architecture'] = architecture;
|
||||
installDotnetSpy.mockResolvedValue('8.0.404');
|
||||
installRuntimeSpy.mockImplementation(() => {
|
||||
DotnetInstallDir.setEnvironmentVariable();
|
||||
return Promise.resolve('9.0.1');
|
||||
});
|
||||
|
||||
await setup.run();
|
||||
expect(setFailedSpy).not.toHaveBeenCalled();
|
||||
expect(process.env['DOTNET_INSTALL_DIR']).toBe(
|
||||
path.join(DotnetInstallDir.dirPath, architecture)
|
||||
);
|
||||
expect(DotnetInstallDir.addToPath).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
});
|
||||
|
||||
it(`shouldn't call setOutput() if parsing dotnet-installer logs failed`, async () => {
|
||||
inputs['dotnet-version'] = ['10.0.101'];
|
||||
const warningMessage = `Failed to output the installed version of .NET. The 'dotnet-version' output will not be set.`;
|
||||
@@ -502,7 +600,7 @@ describe('setup-dotnet tests', () => {
|
||||
await setup.run();
|
||||
expect(setFailedSpy).not.toHaveBeenCalled();
|
||||
expect(warningSpy).toHaveBeenCalledWith(
|
||||
`The 'dotnet-channel' input is only supported when 'dotnet-version' is set to 'latest'.`
|
||||
`The 'dotnet-channel' input is only supported when 'dotnet-version' or 'dotnet-runtime' is set to 'latest'.`
|
||||
);
|
||||
});
|
||||
|
||||
|
||||
@@ -8,11 +8,14 @@ inputs:
|
||||
dotnet-version:
|
||||
description: 'Optional SDK version(s) to use. If not provided, will install global.json version when available. Examples: 2.2.104, 3.1, 3.1.x, 3.x, 6.0.2xx, latest'
|
||||
required: false
|
||||
dotnet-runtime:
|
||||
description: 'Optional runtime version(s) to install, including the paired ASP.NET Core runtime for .NET Core 2.1 and later. Supports the same version syntax as dotnet-version, except the SDK-only A.B.Cxx feature band syntax. Examples: 8.0.x, 9.0.x, 8.0.0'
|
||||
required: false
|
||||
dotnet-quality:
|
||||
description: 'Optional quality of the build. The possible values are: daily, preview, ga.'
|
||||
required: false
|
||||
dotnet-channel:
|
||||
description: 'Optional channel for the installation. The possible values are: STS, LTS, A.B (e.g. 8.0), A.B.Cxx (e.g. 8.0.1xx, available since 5.0). To be used with "dotnet-version: latest".'
|
||||
description: 'Optional channel for the installation. The possible values are: STS, LTS, A.B (e.g. 8.0), A.B.Cxx (e.g. 8.0.1xx, available since 5.0; dotnet-runtime uses its A.B channel). To be used with "dotnet-version: latest" or "dotnet-runtime: latest".'
|
||||
required: false
|
||||
skip-lts-prepass:
|
||||
description: 'Optional. When true, skips the LTS runtime pre-pass and installs only the requested dotnet-version. Default: false.'
|
||||
@@ -44,7 +47,7 @@ inputs:
|
||||
description: 'Optional architecture for the .NET install. Supported values: x64, x86, arm64, amd64, arm, s390x, ppc64le, riscv64. If not set, the installer auto-detects the current system architecture.'
|
||||
required: false
|
||||
check-latest:
|
||||
description: 'Optional, defaults to true. When false, a locally installed SDK that satisfies the requested version is reused without any network calls, otherwise the latest matching version is installed online. Cross-architecture requests always install online. Falls back to the DOTNET_CHECK_LATEST environment variable when this input is not set.'
|
||||
description: 'Optional, defaults to true. When false, a locally installed SDK or complete runtime pair that satisfies the request is reused without resolution or download; otherwise installation proceeds online. Cross-architecture requests and LTS/STS channel resolution use the online path. Falls back to DOTNET_CHECK_LATEST when this input is not set.'
|
||||
required: false
|
||||
outputs:
|
||||
cache-hit:
|
||||
|
||||
280
dist/setup/index.js
vendored
280
dist/setup/index.js
vendored
@@ -43957,6 +43957,12 @@ const PLATFORM = (() => {
|
||||
|
||||
const QUALITY_INPUT_MINIMAL_MAJOR_TAG = 6;
|
||||
const LATEST_PATCH_SYNTAX_MINIMAL_MAJOR_TAG = 5;
|
||||
function hasAspNetCoreRuntime(version) {
|
||||
const match = version.match(/^(\d+)\.(\d+)/);
|
||||
return (!match ||
|
||||
Number(match[1]) > 2 ||
|
||||
(Number(match[1]) === 2 && Number(match[2]) >= 1));
|
||||
}
|
||||
function channelForMajor(major) {
|
||||
// Starting with .NET 5, the minor version is always zero.
|
||||
// Hardcode the earlier versions because they will not get new releases.
|
||||
@@ -44195,9 +44201,84 @@ class DotnetInstallDir {
|
||||
mac: external_path_default().join(process.env['HOME'] + '', '.dotnet'),
|
||||
windows: external_path_default().join(process.env['PROGRAMFILES'] + '', 'dotnet')
|
||||
};
|
||||
static dirPath = process.env['DOTNET_INSTALL_DIR']
|
||||
? DotnetInstallDir.convertInstallPathToAbsolute(process.env['DOTNET_INSTALL_DIR'])
|
||||
: DotnetInstallDir.default[PLATFORM];
|
||||
static resolvedDirPath;
|
||||
// Resolved on first use so a job that installs nothing never touches the disk.
|
||||
static get dirPath() {
|
||||
DotnetInstallDir.resolvedDirPath ??= DotnetInstallDir.resolveDirPath();
|
||||
return DotnetInstallDir.resolvedDirPath;
|
||||
}
|
||||
static resolveDirPath() {
|
||||
if (process.env['DOTNET_INSTALL_DIR']) {
|
||||
return DotnetInstallDir.convertInstallPathToAbsolute(process.env['DOTNET_INSTALL_DIR']);
|
||||
}
|
||||
const systemPath = DotnetInstallDir.default[PLATFORM];
|
||||
const homePath = DotnetInstallDir.homeInstallPath();
|
||||
// A relative default (unset HOME/PROGRAMFILES) would probe the cwd.
|
||||
if (external_path_default().isAbsolute(systemPath) &&
|
||||
DotnetInstallDir.isWritableLocation(systemPath)) {
|
||||
return systemPath;
|
||||
}
|
||||
// On macOS both candidates are the same path, already probed above.
|
||||
const hasFallback = !!homePath && homePath !== systemPath;
|
||||
if (hasFallback && DotnetInstallDir.isWritableLocation(homePath)) {
|
||||
warning(`The default .NET install directory '${systemPath}' is not writable by the current user. Falling back to '${homePath}'; .NET preinstalled in the default location will no longer be used. Set the DOTNET_INSTALL_DIR environment variable to override this location.`);
|
||||
return homePath;
|
||||
}
|
||||
// Not setFailed: the install may still succeed, so let it report the error.
|
||||
warning(hasFallback
|
||||
? `Neither the default .NET install directory '${systemPath}' nor '${homePath}' is writable by the current user. Keeping '${systemPath}', but the installation is likely to fail. Set the DOTNET_INSTALL_DIR environment variable to a writable location.`
|
||||
: `The default .NET install directory '${systemPath}' is not writable by the current user. Keeping it, but the installation is likely to fail. Set the DOTNET_INSTALL_DIR environment variable to a writable location.`);
|
||||
return systemPath;
|
||||
}
|
||||
static homeInstallPath() {
|
||||
try {
|
||||
const home = external_os_default().homedir();
|
||||
// An empty HOME resolves against the cwd; a root HOME gives '/.dotnet'.
|
||||
if (!external_path_default().isAbsolute(home) || home === external_path_default().parse(home).root) {
|
||||
return undefined;
|
||||
}
|
||||
return external_path_default().join(home, '.dotnet');
|
||||
}
|
||||
catch {
|
||||
return undefined;
|
||||
}
|
||||
}
|
||||
// Writability is tested by creating a directory. accessSync is not enough: it
|
||||
// ignores Windows ACLs, so it reports success where the install would fail.
|
||||
static isWritableLocation(installDir) {
|
||||
let existingPath = external_path_default().resolve(installDir);
|
||||
try {
|
||||
// lstat also matches a broken symlink. existsSync does not, and the walk
|
||||
// would skip past it to a writable parent and wrongly report success.
|
||||
while (!(0,external_fs_namespaceObject.lstatSync)(existingPath, { throwIfNoEntry: false })) {
|
||||
const parentPath = external_path_default().dirname(existingPath);
|
||||
if (parentPath === existingPath)
|
||||
return false;
|
||||
existingPath = parentPath;
|
||||
}
|
||||
}
|
||||
catch {
|
||||
return false;
|
||||
}
|
||||
let probeDir;
|
||||
try {
|
||||
probeDir = (0,external_fs_namespaceObject.mkdtempSync)(external_path_default().join(existingPath, '.setup-dotnet-probe-'));
|
||||
return true;
|
||||
}
|
||||
catch {
|
||||
return false;
|
||||
}
|
||||
finally {
|
||||
if (probeDir) {
|
||||
try {
|
||||
(0,external_fs_namespaceObject.rmSync)(probeDir, { recursive: true, force: true });
|
||||
}
|
||||
catch {
|
||||
// Throwing here would discard the result already returned above.
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
static convertInstallPathToAbsolute(installDir) {
|
||||
if (external_path_default().isAbsolute(installDir))
|
||||
return external_path_default().normalize(installDir);
|
||||
@@ -44257,9 +44338,6 @@ class DotnetCoreInstaller {
|
||||
rollForward;
|
||||
skipLtsPrepass;
|
||||
static FeatureBandSyntax = /^(\d+)\.(\d+)\.(\d)xx$/;
|
||||
static {
|
||||
DotnetInstallDir.setEnvironmentVariable();
|
||||
}
|
||||
constructor(version, quality, architecture, dotnetChannel, checkLatest = true, minimumVersion, rollForward, skipLtsPrepass = false) {
|
||||
this.version = version;
|
||||
this.quality = quality;
|
||||
@@ -44399,6 +44477,9 @@ class DotnetCoreInstaller {
|
||||
if (this.rollForward && minimumVersion) {
|
||||
return this.findByRollForward(this.filterByQuality(allowed), this.rollForward, minimumVersion);
|
||||
}
|
||||
return this.findMatchingVersion(allowed);
|
||||
}
|
||||
findMatchingVersion(allowed) {
|
||||
if (semver_default().valid(this.version)) {
|
||||
return allowed.find(version => version === this.version) ?? null;
|
||||
}
|
||||
@@ -44446,7 +44527,53 @@ class DotnetCoreInstaller {
|
||||
}
|
||||
return null;
|
||||
}
|
||||
getInstalledRuntimeVersions(framework) {
|
||||
const runtimeDir = external_path_default().join(DotnetInstallDir.dirPath, 'shared', framework);
|
||||
try {
|
||||
return (0,external_fs_namespaceObject.readdirSync)(runtimeDir, { withFileTypes: true })
|
||||
.filter(entry => entry.isDirectory() || entry.isSymbolicLink())
|
||||
.map(entry => entry.name)
|
||||
.filter(version => semver_default().valid(version) !== null)
|
||||
.filter(version => isFile(external_path_default().join(runtimeDir, version, `${framework}.deps.json`)));
|
||||
}
|
||||
catch {
|
||||
core_debug(`Unable to read the runtime directory '${runtimeDir}'.`);
|
||||
return [];
|
||||
}
|
||||
}
|
||||
findLocalRuntimeVersion() {
|
||||
if (!this.hasDotnetMuxer()) {
|
||||
return null;
|
||||
}
|
||||
const dotnetVersions = this.getInstalledRuntimeVersions('Microsoft.NETCore.App');
|
||||
const aspnetVersions = this.getInstalledRuntimeVersions('Microsoft.AspNetCore.App');
|
||||
// Preview pairs can have different build numbers, so a preview ASP.NET Core
|
||||
// runtime is paired with the .NET runtime declared in its runtimeconfig.json.
|
||||
const pairedVersions = new Set([
|
||||
...aspnetVersions,
|
||||
...aspnetVersions
|
||||
.filter(version => semver_default().prerelease(version))
|
||||
.flatMap(version => this.getDeclaredRuntimeVersion(version) ?? [])
|
||||
]);
|
||||
return this.findMatchingVersion(dotnetVersions.filter(version => !hasAspNetCoreRuntime(version) || pairedVersions.has(version)));
|
||||
}
|
||||
getDeclaredRuntimeVersion(aspnetVersion) {
|
||||
const configPath = external_path_default().join(DotnetInstallDir.dirPath, 'shared', 'Microsoft.AspNetCore.App', aspnetVersion, 'Microsoft.AspNetCore.App.runtimeconfig.json');
|
||||
try {
|
||||
const framework = JSON.parse((0,external_fs_namespaceObject.readFileSync)(configPath, 'utf8'))
|
||||
.runtimeOptions?.framework;
|
||||
return framework?.name === 'Microsoft.NETCore.App'
|
||||
? framework.version
|
||||
: undefined;
|
||||
}
|
||||
catch {
|
||||
core_debug(`Unable to read the runtime pairing from '${configPath}'.`);
|
||||
return undefined;
|
||||
}
|
||||
}
|
||||
async installDotnet() {
|
||||
// Before findLocalSdkVersion(), which looks under the resolved directory.
|
||||
DotnetInstallDir.setEnvironmentVariable();
|
||||
const isCrossArch = !!this.architecture &&
|
||||
normalizeArch(this.architecture) !== normalizeArch(external_os_default().arch());
|
||||
if (!this.checkLatest && !isCrossArch) {
|
||||
@@ -44511,6 +44638,107 @@ class DotnetCoreInstaller {
|
||||
}
|
||||
return this.parseInstalledVersion(dotnetInstallOutput.stdout);
|
||||
}
|
||||
async installRuntime() {
|
||||
this.validateRuntimeVersion();
|
||||
DotnetInstallDir.setEnvironmentVariable();
|
||||
const isCrossArch = !!this.architecture &&
|
||||
normalizeArch(this.architecture) !== normalizeArch(external_os_default().arch());
|
||||
if (!this.checkLatest && !isCrossArch) {
|
||||
const localVersion = this.findLocalRuntimeVersion();
|
||||
if (localVersion) {
|
||||
info(`'check-latest' is false and locally installed .NET runtimes (${localVersion}) satisfy the '${this.version}' request. Skipping download.`);
|
||||
return localVersion;
|
||||
}
|
||||
info(`'check-latest' is false but no complete local runtime installation satisfies the '${this.version}' request. Falling back to online installation.`);
|
||||
}
|
||||
const versionResolver = new DotnetVersionResolver(this.version, this.quality, this.dotnetChannel);
|
||||
const dotnetVersion = await versionResolver.createDotnetVersion();
|
||||
if (this.quality && !dotnetVersion.qualityFlag) {
|
||||
warning(`The 'dotnet-quality' input can be used only with .NET runtime channels in A.B, A.B.x, A or A.x formats where the major tag is higher than 5, or 'latest' resolving to such a channel. You specified: ${dotnetVersion.value}. 'dotnet-quality' input is ignored for this runtime.`);
|
||||
}
|
||||
const installAspNetCore = hasAspNetCoreRuntime(dotnetVersion.value);
|
||||
const aspnetVersion = installAspNetCore
|
||||
? await this.resolveAspNetCoreVersion(dotnetVersion)
|
||||
: undefined;
|
||||
if (!installAspNetCore) {
|
||||
warning(`ASP.NET Core shared runtimes are not available before .NET Core 2.1. Installing only the .NET runtime for '${this.version}'.`);
|
||||
}
|
||||
const architectureArguments = isCrossArch
|
||||
? [
|
||||
utils_IS_WINDOWS ? '-InstallDir' : '--install-dir',
|
||||
utils_IS_WINDOWS
|
||||
? `"${external_path_default().join(DotnetInstallDir.dirPath, this.architecture)}"`
|
||||
: external_path_default().join(DotnetInstallDir.dirPath, this.architecture)
|
||||
]
|
||||
: [];
|
||||
// Install the .NET runtime (Microsoft.NETCore.App) first, then the
|
||||
// ASP.NET Core runtime (Microsoft.AspNetCore.App)
|
||||
const dotnetRuntimeStdout = await this.installSharedRuntime('dotnet', dotnetVersion, architectureArguments);
|
||||
if (aspnetVersion) {
|
||||
await this.installSharedRuntime('aspnetcore', aspnetVersion, architectureArguments);
|
||||
}
|
||||
// The output remains the base runtime version, even when build numbers differ.
|
||||
return this.parseInstalledVersion(dotnetRuntimeStdout);
|
||||
}
|
||||
// Runs before the resolver, whose errors name 'dotnet-version'.
|
||||
validateRuntimeVersion() {
|
||||
if (this.version.toLowerCase() === 'latest' ||
|
||||
semver_default().validRange(this.version)) {
|
||||
return;
|
||||
}
|
||||
// Feature bands (A.B.Cxx) exist only for SDKs, so the install script can't resolve them for runtimes.
|
||||
const reason = DotnetCoreInstaller.FeatureBandSyntax.test(this.version)
|
||||
? ` The A.B.Cxx feature band syntax applies only to .NET SDKs and is supported only by 'dotnet-version'.`
|
||||
: '';
|
||||
throw new Error(`The 'dotnet-runtime' was supplied in invalid format: ${this.version}!${reason} Supported syntax: A.B.C, A.B, A.B.x, A, A.x, latest`);
|
||||
}
|
||||
async resolveAspNetCoreVersion(dotnetVersion) {
|
||||
const version = dotnetVersion.value;
|
||||
if (!semver_default().valid(version) || !semver_default().prerelease(version)) {
|
||||
return dotnetVersion;
|
||||
}
|
||||
const channel = `${semver_default().major(version)}.${semver_default().minor(version)}`;
|
||||
const httpClient = new lib_HttpClient('actions/setup-dotnet', [], {
|
||||
allowRetries: true,
|
||||
maxRetries: 3
|
||||
});
|
||||
try {
|
||||
const response = await httpClient.getJson(`https://builds.dotnet.microsoft.com/dotnet/release-metadata/${channel}/releases.json`);
|
||||
const releases = response.result?.releases;
|
||||
const release = Array.isArray(releases)
|
||||
? releases.find(entry => entry?.runtime?.version === version)
|
||||
: undefined;
|
||||
const aspnetVersion = release?.['aspnetcore-runtime']?.version;
|
||||
if (response.statusCode === 200 &&
|
||||
typeof aspnetVersion === 'string' &&
|
||||
semver_default().valid(aspnetVersion)) {
|
||||
return { ...dotnetVersion, value: aspnetVersion };
|
||||
}
|
||||
warning(`No ASP.NET Core release mapping was found for '${version}' (HTTP ${response.statusCode}). Trying the same exact version for this potentially unpublished build; installation failures remain fatal.`);
|
||||
}
|
||||
catch (error) {
|
||||
warning(`Unable to resolve the ASP.NET Core release paired with '${version}': ${error instanceof Error ? error.message : String(error)}. Trying the same exact version; installation failures remain fatal.`);
|
||||
}
|
||||
finally {
|
||||
httpClient.dispose();
|
||||
}
|
||||
return dotnetVersion;
|
||||
}
|
||||
async installSharedRuntime(runtime, dotnetVersion, architectureArguments) {
|
||||
const runtimeInstallOutput = await new DotnetInstallScript()
|
||||
.useArchitecture(this.architecture)
|
||||
// If dotnet CLI is already installed - avoid overwriting it
|
||||
.useArguments(utils_IS_WINDOWS ? '-SkipNonVersionedFiles' : '--skip-non-versioned-files')
|
||||
.useArguments(utils_IS_WINDOWS ? '-Runtime' : '--runtime', runtime)
|
||||
// Use version provided by user
|
||||
.useVersion(dotnetVersion, dotnetVersion.qualityFlag ? this.quality : '')
|
||||
.useArguments(...architectureArguments)
|
||||
.execute();
|
||||
if (runtimeInstallOutput.exitCode) {
|
||||
throw new Error(`Failed to install ${runtime} runtime, exit code: ${runtimeInstallOutput.exitCode}. ${runtimeInstallOutput.stderr}`);
|
||||
}
|
||||
return runtimeInstallOutput.stdout;
|
||||
}
|
||||
parseInstalledVersion(stdout) {
|
||||
const regex = /(?<version>\d+\.\d+\.\d+[a-z0-9._-]*)/gm;
|
||||
const matchedResult = regex.exec(stdout);
|
||||
@@ -105495,6 +105723,7 @@ async function run() {
|
||||
//
|
||||
// dotnet-version is optional, but needs to be provided for most use cases.
|
||||
// If supplied, install / use from the tool cache.
|
||||
// dotnet-runtime is optional and allows installing runtime-only versions.
|
||||
// global-version-file may be specified to point to a specific global.json
|
||||
// and will be used to install an additional version.
|
||||
// If not supplied, look for version in ./global.json.
|
||||
@@ -105512,11 +105741,12 @@ async function run() {
|
||||
globalJsonConstraints.set(version, { minimumVersion, rollForward });
|
||||
}
|
||||
};
|
||||
const runtimeVersions = getMultilineInput('dotnet-runtime');
|
||||
const installedDotnetVersions = [];
|
||||
const architecture = getArchitectureInput();
|
||||
const checkLatest = getCheckLatestInput();
|
||||
let dotnetChannel = getInput('dotnet-channel');
|
||||
const isLatestRequested = versions.some(version => version && version.toLowerCase() === 'latest');
|
||||
const isLatestRequested = [...versions, ...runtimeVersions].some(version => version && version.toLowerCase() === 'latest');
|
||||
if (dotnetChannel && !isValidChannel(dotnetChannel)) {
|
||||
if (isLatestRequested) {
|
||||
throw new Error(`Value '${dotnetChannel}' is not supported for the 'dotnet-channel' option. Supported values are: LTS, STS, A.B (e.g. 8.0), A.B.Cxx (e.g. 8.0.1xx).`);
|
||||
@@ -105527,7 +105757,7 @@ async function run() {
|
||||
}
|
||||
}
|
||||
else if (dotnetChannel && !isLatestRequested) {
|
||||
warning(`The 'dotnet-channel' input is only supported when 'dotnet-version' is set to 'latest'.`);
|
||||
warning(`The 'dotnet-channel' input is only supported when 'dotnet-version' or 'dotnet-runtime' is set to 'latest'.`);
|
||||
dotnetChannel = '';
|
||||
}
|
||||
const globalJsonFileInput = getInput('global-json-file');
|
||||
@@ -105545,15 +105775,17 @@ async function run() {
|
||||
if (external_fs_namespaceObject.existsSync(globalJsonPath)) {
|
||||
addVersionFromGlobalJson(globalJsonPath);
|
||||
}
|
||||
else {
|
||||
else if (!runtimeVersions.length) {
|
||||
info(`The global.json wasn't found in the root directory. No .NET version will be installed.`);
|
||||
}
|
||||
}
|
||||
if (versions.length) {
|
||||
const quality = getInput('dotnet-quality');
|
||||
if (quality && !qualityOptions.includes(quality)) {
|
||||
if ((versions.length || runtimeVersions.length) &&
|
||||
quality &&
|
||||
!qualityOptions.includes(quality)) {
|
||||
throw new Error(`Value '${quality}' is not supported for the 'dotnet-quality' option. Supported values are: daily, preview, ga.`);
|
||||
}
|
||||
if (versions.length) {
|
||||
const skipLtsPrepass = getBooleanInput('skip-lts-prepass');
|
||||
let dotnetInstaller;
|
||||
const uniqueVersions = new Set(versions.map(v => (v.toLowerCase() === 'latest' ? 'latest' : v)));
|
||||
@@ -105563,10 +105795,7 @@ async function run() {
|
||||
const installedVersion = await dotnetInstaller.installDotnet();
|
||||
installedDotnetVersions.push(installedVersion);
|
||||
}
|
||||
if (architecture &&
|
||||
normalizeArch(architecture) !== normalizeArch(external_os_default().arch())) {
|
||||
process.env['DOTNET_INSTALL_DIR'] = external_path_default().join(DotnetInstallDir.dirPath, architecture);
|
||||
}
|
||||
setDotnetInstallDir(architecture);
|
||||
DotnetInstallDir.addToPath();
|
||||
const workloadsInput = getInput('workloads');
|
||||
if (workloadsInput) {
|
||||
@@ -105587,6 +105816,21 @@ async function run() {
|
||||
}
|
||||
}
|
||||
}
|
||||
if (runtimeVersions.length) {
|
||||
const uniqueRuntimeVersions = new Set(runtimeVersions.map(v => (v.toLowerCase() === 'latest' ? 'latest' : v)));
|
||||
// Runtimes have no SDK feature bands, so A.B.Cxx uses its A.B channel.
|
||||
const runtimeChannel = dotnetChannel.replace(/^(\d+\.\d+)\.\dxx$/, '$1');
|
||||
for (const runtimeVersion of uniqueRuntimeVersions) {
|
||||
const dotnetInstaller = new DotnetCoreInstaller(runtimeVersion, quality, architecture, runtimeVersion === 'latest' ? runtimeChannel : undefined, checkLatest);
|
||||
await dotnetInstaller.installRuntime();
|
||||
}
|
||||
// installRuntime() resets DOTNET_INSTALL_DIR to the base directory.
|
||||
setDotnetInstallDir(architecture);
|
||||
// The SDK installation has already added the same directory to PATH.
|
||||
if (!versions.length) {
|
||||
DotnetInstallDir.addToPath();
|
||||
}
|
||||
}
|
||||
const sourceUrl = getInput('source-url');
|
||||
const configFile = getInput('config-file');
|
||||
if (sourceUrl) {
|
||||
@@ -105604,6 +105848,12 @@ async function run() {
|
||||
setFailed(error.message);
|
||||
}
|
||||
}
|
||||
function setDotnetInstallDir(architecture) {
|
||||
if (architecture &&
|
||||
normalizeArch(architecture) !== normalizeArch(external_os_default().arch())) {
|
||||
process.env['DOTNET_INSTALL_DIR'] = external_path_default().join(DotnetInstallDir.dirPath, architecture);
|
||||
}
|
||||
}
|
||||
function getArchitectureInput() {
|
||||
const raw = (getInput('architecture') || '').trim();
|
||||
if (!raw)
|
||||
|
||||
341
src/installer.ts
341
src/installer.ts
@@ -7,7 +7,11 @@ import {
|
||||
accessSync,
|
||||
chmodSync,
|
||||
constants as fsConstants,
|
||||
lstatSync,
|
||||
mkdtempSync,
|
||||
readdirSync,
|
||||
readFileSync,
|
||||
rmSync,
|
||||
statSync
|
||||
} from 'fs';
|
||||
import path from 'path';
|
||||
@@ -33,9 +37,25 @@ interface ReleaseIndexResponse {
|
||||
'releases-index': ReleaseIndexEntry[];
|
||||
}
|
||||
|
||||
interface RuntimeReleasesResponse {
|
||||
releases?: {
|
||||
runtime?: {version?: string} | null;
|
||||
'aspnetcore-runtime'?: {version?: string} | null;
|
||||
}[];
|
||||
}
|
||||
|
||||
const QUALITY_INPUT_MINIMAL_MAJOR_TAG = 6;
|
||||
const LATEST_PATCH_SYNTAX_MINIMAL_MAJOR_TAG = 5;
|
||||
|
||||
function hasAspNetCoreRuntime(version: string): boolean {
|
||||
const match = version.match(/^(\d+)\.(\d+)/);
|
||||
return (
|
||||
!match ||
|
||||
Number(match[1]) > 2 ||
|
||||
(Number(match[1]) === 2 && Number(match[2]) >= 1)
|
||||
);
|
||||
}
|
||||
|
||||
function channelForMajor(major: string): string {
|
||||
// Starting with .NET 5, the minor version is always zero.
|
||||
// Hardcode the earlier versions because they will not get new releases.
|
||||
@@ -347,11 +367,97 @@ export abstract class DotnetInstallDir {
|
||||
windows: path.join(process.env['PROGRAMFILES'] + '', 'dotnet')
|
||||
};
|
||||
|
||||
public static readonly dirPath = process.env['DOTNET_INSTALL_DIR']
|
||||
? DotnetInstallDir.convertInstallPathToAbsolute(
|
||||
private static resolvedDirPath: string | undefined;
|
||||
|
||||
// Resolved on first use so a job that installs nothing never touches the disk.
|
||||
public static get dirPath(): string {
|
||||
DotnetInstallDir.resolvedDirPath ??= DotnetInstallDir.resolveDirPath();
|
||||
return DotnetInstallDir.resolvedDirPath;
|
||||
}
|
||||
|
||||
private static resolveDirPath(): string {
|
||||
if (process.env['DOTNET_INSTALL_DIR']) {
|
||||
return DotnetInstallDir.convertInstallPathToAbsolute(
|
||||
process.env['DOTNET_INSTALL_DIR']
|
||||
)
|
||||
: DotnetInstallDir.default[PLATFORM];
|
||||
);
|
||||
}
|
||||
|
||||
const systemPath = DotnetInstallDir.default[PLATFORM];
|
||||
const homePath = DotnetInstallDir.homeInstallPath();
|
||||
|
||||
// A relative default (unset HOME/PROGRAMFILES) would probe the cwd.
|
||||
if (
|
||||
path.isAbsolute(systemPath) &&
|
||||
DotnetInstallDir.isWritableLocation(systemPath)
|
||||
) {
|
||||
return systemPath;
|
||||
}
|
||||
|
||||
// On macOS both candidates are the same path, already probed above.
|
||||
const hasFallback = !!homePath && homePath !== systemPath;
|
||||
|
||||
if (hasFallback && DotnetInstallDir.isWritableLocation(homePath!)) {
|
||||
core.warning(
|
||||
`The default .NET install directory '${systemPath}' is not writable by the current user. Falling back to '${homePath}'; .NET preinstalled in the default location will no longer be used. Set the DOTNET_INSTALL_DIR environment variable to override this location.`
|
||||
);
|
||||
return homePath!;
|
||||
}
|
||||
|
||||
// Not setFailed: the install may still succeed, so let it report the error.
|
||||
core.warning(
|
||||
hasFallback
|
||||
? `Neither the default .NET install directory '${systemPath}' nor '${homePath}' is writable by the current user. Keeping '${systemPath}', but the installation is likely to fail. Set the DOTNET_INSTALL_DIR environment variable to a writable location.`
|
||||
: `The default .NET install directory '${systemPath}' is not writable by the current user. Keeping it, but the installation is likely to fail. Set the DOTNET_INSTALL_DIR environment variable to a writable location.`
|
||||
);
|
||||
return systemPath;
|
||||
}
|
||||
|
||||
private static homeInstallPath(): string | undefined {
|
||||
try {
|
||||
const home = os.homedir();
|
||||
// An empty HOME resolves against the cwd; a root HOME gives '/.dotnet'.
|
||||
if (!path.isAbsolute(home) || home === path.parse(home).root) {
|
||||
return undefined;
|
||||
}
|
||||
return path.join(home, '.dotnet');
|
||||
} catch {
|
||||
return undefined;
|
||||
}
|
||||
}
|
||||
|
||||
// Writability is tested by creating a directory. accessSync is not enough: it
|
||||
// ignores Windows ACLs, so it reports success where the install would fail.
|
||||
private static isWritableLocation(installDir: string): boolean {
|
||||
let existingPath = path.resolve(installDir);
|
||||
|
||||
try {
|
||||
// lstat also matches a broken symlink. existsSync does not, and the walk
|
||||
// would skip past it to a writable parent and wrongly report success.
|
||||
while (!lstatSync(existingPath, {throwIfNoEntry: false})) {
|
||||
const parentPath = path.dirname(existingPath);
|
||||
if (parentPath === existingPath) return false;
|
||||
existingPath = parentPath;
|
||||
}
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
|
||||
let probeDir: string | undefined;
|
||||
try {
|
||||
probeDir = mkdtempSync(path.join(existingPath, '.setup-dotnet-probe-'));
|
||||
return true;
|
||||
} catch {
|
||||
return false;
|
||||
} finally {
|
||||
if (probeDir) {
|
||||
try {
|
||||
rmSync(probeDir, {recursive: true, force: true});
|
||||
} catch {
|
||||
// Throwing here would discard the result already returned above.
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private static convertInstallPathToAbsolute(installDir: string): string {
|
||||
if (path.isAbsolute(installDir)) return path.normalize(installDir);
|
||||
@@ -410,10 +516,6 @@ function isExecutableFile(filePath: string): boolean {
|
||||
export class DotnetCoreInstaller {
|
||||
private static readonly FeatureBandSyntax = /^(\d+)\.(\d+)\.(\d)xx$/;
|
||||
|
||||
static {
|
||||
DotnetInstallDir.setEnvironmentVariable();
|
||||
}
|
||||
|
||||
constructor(
|
||||
private version: string,
|
||||
private quality: QualityOptions,
|
||||
@@ -615,6 +717,10 @@ export class DotnetCoreInstaller {
|
||||
);
|
||||
}
|
||||
|
||||
return this.findMatchingVersion(allowed);
|
||||
}
|
||||
|
||||
private findMatchingVersion(allowed: string[]): string | null {
|
||||
if (semver.valid(this.version)) {
|
||||
return allowed.find(version => version === this.version) ?? null;
|
||||
}
|
||||
@@ -686,7 +792,71 @@ export class DotnetCoreInstaller {
|
||||
return null;
|
||||
}
|
||||
|
||||
private getInstalledRuntimeVersions(framework: string): string[] {
|
||||
const runtimeDir = path.join(DotnetInstallDir.dirPath, 'shared', framework);
|
||||
try {
|
||||
return readdirSync(runtimeDir, {withFileTypes: true})
|
||||
.filter(entry => entry.isDirectory() || entry.isSymbolicLink())
|
||||
.map(entry => entry.name)
|
||||
.filter(version => semver.valid(version) !== null)
|
||||
.filter(version =>
|
||||
isFile(path.join(runtimeDir, version, `${framework}.deps.json`))
|
||||
);
|
||||
} catch {
|
||||
core.debug(`Unable to read the runtime directory '${runtimeDir}'.`);
|
||||
return [];
|
||||
}
|
||||
}
|
||||
|
||||
private findLocalRuntimeVersion(): string | null {
|
||||
if (!this.hasDotnetMuxer()) {
|
||||
return null;
|
||||
}
|
||||
const dotnetVersions = this.getInstalledRuntimeVersions(
|
||||
'Microsoft.NETCore.App'
|
||||
);
|
||||
const aspnetVersions = this.getInstalledRuntimeVersions(
|
||||
'Microsoft.AspNetCore.App'
|
||||
);
|
||||
// Preview pairs can have different build numbers, so a preview ASP.NET Core
|
||||
// runtime is paired with the .NET runtime declared in its runtimeconfig.json.
|
||||
const pairedVersions = new Set([
|
||||
...aspnetVersions,
|
||||
...aspnetVersions
|
||||
.filter(version => semver.prerelease(version))
|
||||
.flatMap(version => this.getDeclaredRuntimeVersion(version) ?? [])
|
||||
]);
|
||||
return this.findMatchingVersion(
|
||||
dotnetVersions.filter(
|
||||
version => !hasAspNetCoreRuntime(version) || pairedVersions.has(version)
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
private getDeclaredRuntimeVersion(aspnetVersion: string): string | undefined {
|
||||
const configPath = path.join(
|
||||
DotnetInstallDir.dirPath,
|
||||
'shared',
|
||||
'Microsoft.AspNetCore.App',
|
||||
aspnetVersion,
|
||||
'Microsoft.AspNetCore.App.runtimeconfig.json'
|
||||
);
|
||||
try {
|
||||
const framework = JSON.parse(readFileSync(configPath, 'utf8'))
|
||||
.runtimeOptions?.framework;
|
||||
return framework?.name === 'Microsoft.NETCore.App'
|
||||
? framework.version
|
||||
: undefined;
|
||||
} catch {
|
||||
core.debug(`Unable to read the runtime pairing from '${configPath}'.`);
|
||||
return undefined;
|
||||
}
|
||||
}
|
||||
|
||||
public async installDotnet(): Promise<string | null> {
|
||||
// Before findLocalSdkVersion(), which looks under the resolved directory.
|
||||
DotnetInstallDir.setEnvironmentVariable();
|
||||
|
||||
const isCrossArch =
|
||||
!!this.architecture &&
|
||||
normalizeArch(this.architecture) !== normalizeArch(os.arch());
|
||||
@@ -775,6 +945,161 @@ export class DotnetCoreInstaller {
|
||||
return this.parseInstalledVersion(dotnetInstallOutput.stdout);
|
||||
}
|
||||
|
||||
public async installRuntime(): Promise<string | null> {
|
||||
this.validateRuntimeVersion();
|
||||
DotnetInstallDir.setEnvironmentVariable();
|
||||
const isCrossArch =
|
||||
!!this.architecture &&
|
||||
normalizeArch(this.architecture) !== normalizeArch(os.arch());
|
||||
|
||||
if (!this.checkLatest && !isCrossArch) {
|
||||
const localVersion = this.findLocalRuntimeVersion();
|
||||
if (localVersion) {
|
||||
core.info(
|
||||
`'check-latest' is false and locally installed .NET runtimes (${localVersion}) satisfy the '${this.version}' request. Skipping download.`
|
||||
);
|
||||
return localVersion;
|
||||
}
|
||||
core.info(
|
||||
`'check-latest' is false but no complete local runtime installation satisfies the '${this.version}' request. Falling back to online installation.`
|
||||
);
|
||||
}
|
||||
|
||||
const versionResolver = new DotnetVersionResolver(
|
||||
this.version,
|
||||
this.quality,
|
||||
this.dotnetChannel
|
||||
);
|
||||
const dotnetVersion = await versionResolver.createDotnetVersion();
|
||||
if (this.quality && !dotnetVersion.qualityFlag) {
|
||||
core.warning(
|
||||
`The 'dotnet-quality' input can be used only with .NET runtime channels in A.B, A.B.x, A or A.x formats where the major tag is higher than 5, or 'latest' resolving to such a channel. You specified: ${dotnetVersion.value}. 'dotnet-quality' input is ignored for this runtime.`
|
||||
);
|
||||
}
|
||||
|
||||
const installAspNetCore = hasAspNetCoreRuntime(dotnetVersion.value);
|
||||
const aspnetVersion = installAspNetCore
|
||||
? await this.resolveAspNetCoreVersion(dotnetVersion)
|
||||
: undefined;
|
||||
if (!installAspNetCore) {
|
||||
core.warning(
|
||||
`ASP.NET Core shared runtimes are not available before .NET Core 2.1. Installing only the .NET runtime for '${this.version}'.`
|
||||
);
|
||||
}
|
||||
|
||||
const architectureArguments = isCrossArch
|
||||
? [
|
||||
IS_WINDOWS ? '-InstallDir' : '--install-dir',
|
||||
IS_WINDOWS
|
||||
? `"${path.join(DotnetInstallDir.dirPath, this.architecture!)}"`
|
||||
: path.join(DotnetInstallDir.dirPath, this.architecture!)
|
||||
]
|
||||
: [];
|
||||
|
||||
// Install the .NET runtime (Microsoft.NETCore.App) first, then the
|
||||
// ASP.NET Core runtime (Microsoft.AspNetCore.App)
|
||||
const dotnetRuntimeStdout = await this.installSharedRuntime(
|
||||
'dotnet',
|
||||
dotnetVersion,
|
||||
architectureArguments
|
||||
);
|
||||
if (aspnetVersion) {
|
||||
await this.installSharedRuntime(
|
||||
'aspnetcore',
|
||||
aspnetVersion,
|
||||
architectureArguments
|
||||
);
|
||||
}
|
||||
|
||||
// The output remains the base runtime version, even when build numbers differ.
|
||||
return this.parseInstalledVersion(dotnetRuntimeStdout);
|
||||
}
|
||||
|
||||
// Runs before the resolver, whose errors name 'dotnet-version'.
|
||||
private validateRuntimeVersion(): void {
|
||||
if (
|
||||
this.version.toLowerCase() === 'latest' ||
|
||||
semver.validRange(this.version)
|
||||
) {
|
||||
return;
|
||||
}
|
||||
// Feature bands (A.B.Cxx) exist only for SDKs, so the install script can't resolve them for runtimes.
|
||||
const reason = DotnetCoreInstaller.FeatureBandSyntax.test(this.version)
|
||||
? ` The A.B.Cxx feature band syntax applies only to .NET SDKs and is supported only by 'dotnet-version'.`
|
||||
: '';
|
||||
throw new Error(
|
||||
`The 'dotnet-runtime' was supplied in invalid format: ${this.version}!${reason} Supported syntax: A.B.C, A.B, A.B.x, A, A.x, latest`
|
||||
);
|
||||
}
|
||||
|
||||
private async resolveAspNetCoreVersion(
|
||||
dotnetVersion: DotnetVersion
|
||||
): Promise<DotnetVersion> {
|
||||
const version = dotnetVersion.value;
|
||||
if (!semver.valid(version) || !semver.prerelease(version)) {
|
||||
return dotnetVersion;
|
||||
}
|
||||
|
||||
const channel = `${semver.major(version)}.${semver.minor(version)}`;
|
||||
const httpClient = new hc.HttpClient('actions/setup-dotnet', [], {
|
||||
allowRetries: true,
|
||||
maxRetries: 3
|
||||
});
|
||||
try {
|
||||
const response = await httpClient.getJson<RuntimeReleasesResponse>(
|
||||
`https://builds.dotnet.microsoft.com/dotnet/release-metadata/${channel}/releases.json`
|
||||
);
|
||||
const releases = response.result?.releases;
|
||||
const release = Array.isArray(releases)
|
||||
? releases.find(entry => entry?.runtime?.version === version)
|
||||
: undefined;
|
||||
const aspnetVersion = release?.['aspnetcore-runtime']?.version;
|
||||
if (
|
||||
response.statusCode === 200 &&
|
||||
typeof aspnetVersion === 'string' &&
|
||||
semver.valid(aspnetVersion)
|
||||
) {
|
||||
return {...dotnetVersion, value: aspnetVersion};
|
||||
}
|
||||
core.warning(
|
||||
`No ASP.NET Core release mapping was found for '${version}' (HTTP ${response.statusCode}). Trying the same exact version for this potentially unpublished build; installation failures remain fatal.`
|
||||
);
|
||||
} catch (error) {
|
||||
core.warning(
|
||||
`Unable to resolve the ASP.NET Core release paired with '${version}': ${error instanceof Error ? error.message : String(error)}. Trying the same exact version; installation failures remain fatal.`
|
||||
);
|
||||
} finally {
|
||||
httpClient.dispose();
|
||||
}
|
||||
return dotnetVersion;
|
||||
}
|
||||
|
||||
private async installSharedRuntime(
|
||||
runtime: 'dotnet' | 'aspnetcore',
|
||||
dotnetVersion: DotnetVersion,
|
||||
architectureArguments: string[]
|
||||
): Promise<string> {
|
||||
const runtimeInstallOutput = await new DotnetInstallScript()
|
||||
.useArchitecture(this.architecture)
|
||||
// If dotnet CLI is already installed - avoid overwriting it
|
||||
.useArguments(
|
||||
IS_WINDOWS ? '-SkipNonVersionedFiles' : '--skip-non-versioned-files'
|
||||
)
|
||||
.useArguments(IS_WINDOWS ? '-Runtime' : '--runtime', runtime)
|
||||
// Use version provided by user
|
||||
.useVersion(dotnetVersion, dotnetVersion.qualityFlag ? this.quality : '')
|
||||
.useArguments(...architectureArguments)
|
||||
.execute();
|
||||
|
||||
if (runtimeInstallOutput.exitCode) {
|
||||
throw new Error(
|
||||
`Failed to install ${runtime} runtime, exit code: ${runtimeInstallOutput.exitCode}. ${runtimeInstallOutput.stderr}`
|
||||
);
|
||||
}
|
||||
|
||||
return runtimeInstallOutput.stdout;
|
||||
}
|
||||
|
||||
private parseInstalledVersion(stdout: string): string | null {
|
||||
const regex = /(?<version>\d+\.\d+\.\d+[a-z0-9._-]*)/gm;
|
||||
const matchedResult = regex.exec(stdout);
|
||||
|
||||
@@ -49,6 +49,7 @@ export async function run() {
|
||||
//
|
||||
// dotnet-version is optional, but needs to be provided for most use cases.
|
||||
// If supplied, install / use from the tool cache.
|
||||
// dotnet-runtime is optional and allows installing runtime-only versions.
|
||||
// global-version-file may be specified to point to a specific global.json
|
||||
// and will be used to install an additional version.
|
||||
// If not supplied, look for version in ./global.json.
|
||||
@@ -71,12 +72,13 @@ export async function run() {
|
||||
globalJsonConstraints.set(version, {minimumVersion, rollForward});
|
||||
}
|
||||
};
|
||||
const runtimeVersions = core.getMultilineInput('dotnet-runtime');
|
||||
const installedDotnetVersions: (string | null)[] = [];
|
||||
const architecture = getArchitectureInput();
|
||||
const checkLatest = getCheckLatestInput();
|
||||
let dotnetChannel = core.getInput('dotnet-channel');
|
||||
|
||||
const isLatestRequested = versions.some(
|
||||
const isLatestRequested = [...versions, ...runtimeVersions].some(
|
||||
version => version && version.toLowerCase() === 'latest'
|
||||
);
|
||||
if (dotnetChannel && !isValidChannel(dotnetChannel)) {
|
||||
@@ -92,7 +94,7 @@ export async function run() {
|
||||
}
|
||||
} else if (dotnetChannel && !isLatestRequested) {
|
||||
core.warning(
|
||||
`The 'dotnet-channel' input is only supported when 'dotnet-version' is set to 'latest'.`
|
||||
`The 'dotnet-channel' input is only supported when 'dotnet-version' or 'dotnet-runtime' is set to 'latest'.`
|
||||
);
|
||||
dotnetChannel = '';
|
||||
}
|
||||
@@ -114,22 +116,26 @@ export async function run() {
|
||||
const globalJsonPath = path.join(process.cwd(), 'global.json');
|
||||
if (fs.existsSync(globalJsonPath)) {
|
||||
addVersionFromGlobalJson(globalJsonPath);
|
||||
} else {
|
||||
} else if (!runtimeVersions.length) {
|
||||
core.info(
|
||||
`The global.json wasn't found in the root directory. No .NET version will be installed.`
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
if (versions.length) {
|
||||
const quality = core.getInput('dotnet-quality') as QualityOptions;
|
||||
|
||||
if (quality && !qualityOptions.includes(quality)) {
|
||||
if (
|
||||
(versions.length || runtimeVersions.length) &&
|
||||
quality &&
|
||||
!qualityOptions.includes(quality)
|
||||
) {
|
||||
throw new Error(
|
||||
`Value '${quality}' is not supported for the 'dotnet-quality' option. Supported values are: daily, preview, ga.`
|
||||
);
|
||||
}
|
||||
|
||||
if (versions.length) {
|
||||
const skipLtsPrepass = core.getBooleanInput('skip-lts-prepass');
|
||||
|
||||
let dotnetInstaller: DotnetCoreInstaller;
|
||||
@@ -151,15 +157,7 @@ export async function run() {
|
||||
const installedVersion = await dotnetInstaller.installDotnet();
|
||||
installedDotnetVersions.push(installedVersion);
|
||||
}
|
||||
if (
|
||||
architecture &&
|
||||
normalizeArch(architecture) !== normalizeArch(os.arch())
|
||||
) {
|
||||
process.env['DOTNET_INSTALL_DIR'] = path.join(
|
||||
DotnetInstallDir.dirPath,
|
||||
architecture
|
||||
);
|
||||
}
|
||||
setDotnetInstallDir(architecture);
|
||||
DotnetInstallDir.addToPath();
|
||||
|
||||
const workloadsInput = core.getInput('workloads');
|
||||
@@ -186,6 +184,30 @@ export async function run() {
|
||||
}
|
||||
}
|
||||
|
||||
if (runtimeVersions.length) {
|
||||
const uniqueRuntimeVersions = new Set<string>(
|
||||
runtimeVersions.map(v => (v.toLowerCase() === 'latest' ? 'latest' : v))
|
||||
);
|
||||
// Runtimes have no SDK feature bands, so A.B.Cxx uses its A.B channel.
|
||||
const runtimeChannel = dotnetChannel.replace(/^(\d+\.\d+)\.\dxx$/, '$1');
|
||||
for (const runtimeVersion of uniqueRuntimeVersions) {
|
||||
const dotnetInstaller = new DotnetCoreInstaller(
|
||||
runtimeVersion,
|
||||
quality,
|
||||
architecture,
|
||||
runtimeVersion === 'latest' ? runtimeChannel : undefined,
|
||||
checkLatest
|
||||
);
|
||||
await dotnetInstaller.installRuntime();
|
||||
}
|
||||
// installRuntime() resets DOTNET_INSTALL_DIR to the base directory.
|
||||
setDotnetInstallDir(architecture);
|
||||
// The SDK installation has already added the same directory to PATH.
|
||||
if (!versions.length) {
|
||||
DotnetInstallDir.addToPath();
|
||||
}
|
||||
}
|
||||
|
||||
const sourceUrl: string = core.getInput('source-url');
|
||||
const configFile: string = core.getInput('config-file');
|
||||
if (sourceUrl) {
|
||||
@@ -211,6 +233,18 @@ export async function run() {
|
||||
}
|
||||
}
|
||||
|
||||
function setDotnetInstallDir(architecture: SupportedArchitecture | ''): void {
|
||||
if (
|
||||
architecture &&
|
||||
normalizeArch(architecture) !== normalizeArch(os.arch())
|
||||
) {
|
||||
process.env['DOTNET_INSTALL_DIR'] = path.join(
|
||||
DotnetInstallDir.dirPath,
|
||||
architecture
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
function getArchitectureInput(): SupportedArchitecture | '' {
|
||||
const raw = (core.getInput('architecture') || '').trim();
|
||||
if (!raw) return '';
|
||||
|
||||
Reference in New Issue
Block a user