Vendored snapshot of setup-dotnet@v5 (no upstream history)
e2e tests / test-setup-multiple-versions (ubuntu-latest) (push) Failing after 15s
e2e tests / test-setup-full-version (ubuntu-latest) (push) Failing after 7s
e2e tests / test-setup-without-patch-version (ubuntu-latest) (push) Failing after 7s
e2e tests / test-setup-prerelease-version (ubuntu-latest) (push) Failing after 7s
e2e tests / test-setup-latest-patch-version (ubuntu-latest) (push) Failing after 7s
e2e tests / test-ABCxx-syntax (ubuntu-latest) (push) Failing after 6s
e2e tests / test-setup-with-wildcard (ubuntu-latest) (push) Failing after 6s
e2e tests / test-setup-global-json-specified-and-version (ubuntu-latest) (push) Failing after 7s
e2e tests / test-setup-global-json-rollforward-latestmajor (ubuntu-latest) (push) Failing after 7s
e2e tests / test-setup-global-json-rollforward-latestfeature (ubuntu-latest) (push) Failing after 7s
e2e tests / test-setup-global-json-rollforward-latestpatch (ubuntu-latest) (push) Failing after 8s
e2e tests / test-global-json-with-comments (ubuntu-latest) (push) Failing after 7s
e2e tests / test-setup-with-dotnet-quality (ubuntu-latest) (push) Failing after 6s
e2e tests / test-setup-with-cache (ubuntu-latest) (push) Failing after 5s
e2e tests / test-setup-with-cache-dependency-path (ubuntu-latest) (push) Failing after 5s
e2e tests / test-dotnet-version-output-during-single-version-installation (ubuntu-latest) (push) Failing after 6s
e2e tests / test-dotnet-version-output-during-multiple-version-installation (ubuntu-latest) (push) Failing after 5s
e2e tests / test-bypass-proxy (push) Failing after 5s
e2e tests / test-sequential-version-installation (10.0.101, 9.0.308, ubuntu-latest) (push) Failing after 5s
e2e tests / test-setup-with-workloads-input (ubuntu-latest) (push) Failing after 5s
e2e tests / test-setup-with-architecture-input (x64, ubuntu-latest) (push) Failing after 5s
e2e tests / test-setup-latest-version (ubuntu-latest) (push) Failing after 5s
Validate dotnet / setup-version (10.0, ubuntu-latest) (push) Failing after 5s
Validate dotnet / setup-version (8.0, ubuntu-latest) (push) Failing after 6s
Validate dotnet / setup-version (9.0, ubuntu-latest) (push) Failing after 5s
e2e tests / test-setup-prerelease-version (ubuntu-22.04) (push) Canceled after 0s
e2e tests / test-setup-prerelease-version (windows-latest) (push) Canceled after 0s
e2e tests / test-setup-latest-patch-version (macos-15-intel) (push) Canceled after 0s
e2e tests / test-setup-latest-patch-version (macos-latest) (push) Canceled after 0s
e2e tests / test-setup-latest-patch-version (ubuntu-22.04) (push) Canceled after 0s
e2e tests / test-setup-latest-patch-version (windows-latest) (push) Canceled after 0s
e2e tests / test-ABCxx-syntax (macos-15-intel) (push) Canceled after 0s
e2e tests / test-ABCxx-syntax (macos-latest) (push) Canceled after 0s
e2e tests / test-ABCxx-syntax (ubuntu-22.04) (push) Canceled after 0s
e2e tests / test-ABCxx-syntax (windows-latest) (push) Canceled after 0s
e2e tests / test-setup-with-wildcard (macos-15-intel) (push) Canceled after 0s
e2e tests / test-setup-with-wildcard (macos-latest) (push) Canceled after 0s
e2e tests / test-setup-with-wildcard (ubuntu-22.04) (push) Canceled after 0s
e2e tests / test-setup-with-wildcard (windows-latest) (push) Canceled after 0s
e2e tests / test-setup-global-json-specified-and-version (macos-15-intel) (push) Canceled after 0s
e2e tests / test-setup-global-json-specified-and-version (macos-latest) (push) Canceled after 0s
e2e tests / test-setup-global-json-specified-and-version (ubuntu-22.04) (push) Canceled after 0s
e2e tests / test-setup-global-json-specified-and-version (windows-latest) (push) Canceled after 0s
e2e tests / test-setup-global-json-rollforward-latestmajor (macos-latest) (push) Canceled after 0s
e2e tests / test-setup-global-json-rollforward-latestmajor (windows-latest) (push) Canceled after 0s
e2e tests / test-setup-global-json-rollforward-latestfeature (macos-latest) (push) Canceled after 0s
e2e tests / test-setup-with-architecture-input (arm64, macos-latest) (push) Canceled after 0s
e2e tests / test-setup-with-architecture-input (x64, macos-latest) (push) Canceled after 0s
e2e tests / test-setup-with-architecture-input (x64, windows-latest) (push) Canceled after 0s
e2e tests / test-setup-global-json-rollforward-latestfeature (windows-latest) (push) Canceled after 0s
e2e tests / test-setup-latest-with-channel-abcxx (macos-latest) (push) Canceled after 0s
Validate dotnet / setup-version (10.0, macos-latest) (push) Canceled after 0s
Validate dotnet / setup-version (10.0, ubuntu-22.04) (push) Canceled after 0s
e2e tests / test-setup-global-json-rollforward-latestpatch (windows-latest) (push) Canceled after 0s
e2e tests / test-global-json-with-comments (macos-15-intel) (push) Canceled after 0s
e2e tests / test-global-json-with-comments (macos-latest) (push) Canceled after 0s
Validate dotnet / setup-version (10.0, windows-latest) (push) Canceled after 0s
e2e tests / test-setup-with-dotnet-quality (macos-latest) (push) Canceled after 0s
e2e tests / test-setup-global-json-rollforward-latestpatch (macos-latest) (push) Canceled after 0s
Validate dotnet / setup-version (10.0, macos-15-intel) (push) Canceled after 0s
Validate dotnet / setup-version (8.0, macos-15-intel) (push) Canceled after 0s
Validate dotnet / setup-version (8.0, macos-latest) (push) Canceled after 0s
Validate dotnet / setup-version (8.0, ubuntu-22.04) (push) Canceled after 0s
Validate dotnet / setup-version (8.0, windows-latest) (push) Canceled after 0s
e2e tests / test-global-json-with-comments (ubuntu-22.04) (push) Canceled after 0s
e2e tests / test-global-json-with-comments (windows-latest) (push) Canceled after 0s
e2e tests / test-setup-with-dotnet-quality (macos-15-intel) (push) Canceled after 0s
e2e tests / test-setup-with-dotnet-quality (ubuntu-22.04) (push) Canceled after 0s
e2e tests / test-setup-with-dotnet-quality (windows-latest) (push) Canceled after 0s
Validate dotnet / setup-version (9.0, macos-15-intel) (push) Canceled after 0s
e2e tests / test-setup-with-cache (macos-15-intel) (push) Canceled after 0s
e2e tests / test-setup-with-cache (macos-latest) (push) Canceled after 0s
Validate dotnet / setup-version (9.0, macos-latest) (push) Canceled after 0s
Validate dotnet / setup-version (9.0, ubuntu-22.04) (push) Canceled after 0s
Validate dotnet / setup-version (9.0, windows-latest) (push) Canceled after 0s
e2e tests / test-setup-full-version (ubuntu-22.04) (push) Canceled after 0s
e2e tests / test-setup-without-patch-version (macos-15-intel) (push) Canceled after 0s
e2e tests / test-setup-without-patch-version (windows-latest) (push) Canceled after 0s
e2e tests / test-setup-with-cache (ubuntu-22.04) (push) Canceled after 0s
e2e tests / test-setup-with-cache (windows-latest) (push) Canceled after 0s
e2e tests / test-setup-with-cache-dependency-path (macos-15-intel) (push) Canceled after 0s
e2e tests / test-setup-multiple-versions (macos-15-intel) (push) Canceled after 0s
e2e tests / test-setup-multiple-versions (macos-latest) (push) Canceled after 0s
e2e tests / test-setup-multiple-versions (ubuntu-22.04) (push) Canceled after 0s
e2e tests / test-setup-multiple-versions (windows-latest) (push) Canceled after 0s
e2e tests / test-setup-full-version (macos-15-intel) (push) Canceled after 0s
e2e tests / test-setup-full-version (macos-latest) (push) Canceled after 0s
e2e tests / test-setup-full-version (windows-latest) (push) Canceled after 0s
e2e tests / test-setup-without-patch-version (macos-latest) (push) Canceled after 0s
e2e tests / test-setup-without-patch-version (ubuntu-22.04) (push) Canceled after 0s
e2e tests / test-setup-with-cache-dependency-path (macos-latest) (push) Canceled after 0s
e2e tests / test-setup-with-cache-dependency-path (ubuntu-22.04) (push) Canceled after 0s
e2e tests / test-setup-with-cache-dependency-path (windows-latest) (push) Canceled after 0s
e2e tests / test-dotnet-version-output-during-single-version-installation (macos-15-intel) (push) Canceled after 0s
e2e tests / test-dotnet-version-output-during-single-version-installation (macos-latest) (push) Canceled after 0s
e2e tests / test-dotnet-version-output-during-single-version-installation (ubuntu-22.04) (push) Canceled after 0s
e2e tests / test-dotnet-version-output-during-single-version-installation (windows-latest) (push) Canceled after 0s
e2e tests / test-dotnet-version-output-during-multiple-version-installation (macos-15-intel) (push) Canceled after 0s
e2e tests / test-dotnet-version-output-during-multiple-version-installation (macos-latest) (push) Canceled after 0s
e2e tests / test-dotnet-version-output-during-multiple-version-installation (ubuntu-22.04) (push) Canceled after 0s
e2e tests / test-dotnet-version-output-during-multiple-version-installation (windows-latest) (push) Canceled after 0s
e2e tests / test-proxy (push) Canceled after 0s
e2e tests / test-setup-prerelease-version (macos-15-intel) (push) Canceled after 0s
e2e tests / test-setup-prerelease-version (macos-latest) (push) Canceled after 0s
e2e tests / test-sequential-version-installation (10.0.101, 9.0.308, macos-15-intel) (push) Canceled after 0s
e2e tests / test-sequential-version-installation (10.0.101, 9.0.308, macos-latest) (push) Canceled after 0s
e2e tests / test-sequential-version-installation (10.0.101, 9.0.308, ubuntu-22.04) (push) Canceled after 0s
e2e tests / test-sequential-version-installation (10.0.101, 9.0.308, windows-latest) (push) Canceled after 0s
e2e tests / test-setup-with-workloads-input (macos-15-intel) (push) Canceled after 0s
e2e tests / test-setup-with-workloads-input (macos-latest) (push) Canceled after 0s
e2e tests / test-setup-with-workloads-input (windows-latest) (push) Canceled after 0s

This commit is contained in:
signalhub-ci-mirror
2026-09-18 18:02:10 +00:00
commit 27776e00c6
131 changed files with 205069 additions and 0 deletions
+196
View File
@@ -0,0 +1,196 @@
import * as fs from 'fs';
import * as path from 'path';
import * as core from '@actions/core';
import * as github from '@actions/github';
import {XMLParser, XMLBuilder} from 'fast-xml-parser';
export function configAuthentication(
feedUrl: string,
existingFileLocation = '',
processRoot: string = process.cwd()
) {
const existingNuGetConfig: string = path.resolve(
processRoot,
existingFileLocation === ''
? getExistingNugetConfig(processRoot)
: existingFileLocation
);
const tempNuGetConfig: string = path.resolve(
processRoot,
'../',
'nuget.config'
);
writeFeedToFile(feedUrl, existingNuGetConfig, tempNuGetConfig);
}
function isValidKey(key: string): boolean {
return /^[\w\-.]+$/i.test(key);
}
function getExistingNugetConfig(processRoot: string) {
const defaultConfigName = 'nuget.config';
const configFileNames = fs
.readdirSync(processRoot)
.filter(filename => filename.toLowerCase() === defaultConfigName);
if (configFileNames.length) {
return configFileNames[0];
}
return defaultConfigName;
}
function writeFeedToFile(
feedUrl: string,
existingFileLocation: string,
tempFileLocation: string
) {
core.info(
`dotnet-auth: Finding any source references in ${existingFileLocation}, writing a new temporary configuration file with credentials to ${tempFileLocation}`
);
const sourceKeys: string[] = [];
let owner: string = core.getInput('owner');
const sourceUrl: string = feedUrl;
if (!owner) {
owner = github.context.repo.owner;
}
if (!process.env.NUGET_AUTH_TOKEN) {
throw new Error(
'The NUGET_AUTH_TOKEN environment variable was not provided. In this step, add the following: \r\nenv:\r\n NUGET_AUTH_TOKEN: ${{secrets.GITHUB_TOKEN}}'
);
}
if (fs.existsSync(existingFileLocation)) {
// get key from existing NuGet.config so NuGet/dotnet can match credentials
const curContents: string = fs.readFileSync(existingFileLocation, 'utf8');
const parserOptions = {
ignoreAttributes: false
};
const parser = new XMLParser(parserOptions);
const json = parser.parse(curContents);
if (typeof json.configuration === 'undefined') {
throw new Error(`The provided NuGet.config seems invalid.`);
}
if (json.configuration?.packageSources?.add) {
const packageSources = json.configuration.packageSources.add;
if (Array.isArray(packageSources)) {
packageSources.forEach(source => {
const value = source['@_value'];
core.debug(`source '${value}'`);
if (value.toLowerCase().includes(feedUrl.toLowerCase())) {
const key = source['@_key'];
sourceKeys.push(key);
core.debug(`Found a URL with key ${key}`);
}
});
} else {
if (
packageSources['@_value']
.toLowerCase()
.includes(feedUrl.toLowerCase())
) {
const key = packageSources['@_key'];
sourceKeys.push(key);
core.debug(`Found a URL with key ${key}`);
}
}
}
}
const xmlSource: any[] = [
{
'?xml': [
{
'#text': ''
}
],
':@': {
'@_version': '1.0'
}
},
{
configuration: [
{
config: [
{
add: [],
':@': {
'@_key': 'defaultPushSource',
'@_value': sourceUrl
}
}
]
}
]
}
];
if (!sourceKeys.length) {
const keystring = 'Source';
xmlSource[1].configuration.push({
packageSources: [
{
add: [],
':@': {
'@_key': keystring,
'@_value': sourceUrl
}
}
]
});
sourceKeys.push(keystring);
}
const packageSourceCredentials: any[] = [];
sourceKeys.forEach(key => {
if (!isValidKey(key)) {
throw new Error(
"Source name can contain letters, numbers, and '-', '_', '.' symbols only. Please, fix source name in NuGet.config and try again."
);
}
packageSourceCredentials.push({
[key]: [
{
add: [],
':@': {
'@_key': 'Username',
'@_value': owner
}
},
{
add: [],
':@': {
'@_key': 'ClearTextPassword',
'@_value': process.env.NUGET_AUTH_TOKEN
}
}
]
});
});
xmlSource[1].configuration.push({
packageSourceCredentials
});
const xmlBuilderOptions = {
format: true,
ignoreAttributes: false,
preserveOrder: true,
allowBooleanAttributes: true,
suppressBooleanAttributes: true,
suppressEmptyNode: true
};
const builder = new XMLBuilder(xmlBuilderOptions);
const output = builder.build(xmlSource).trim();
fs.writeFileSync(tempFileLocation, output);
}
+50
View File
@@ -0,0 +1,50 @@
import {readdir} from 'node:fs/promises';
import {join} from 'node:path';
import * as cache from '@actions/cache';
import * as core from '@actions/core';
import * as glob from '@actions/glob';
import {getNuGetFolderPath} from './cache-utils';
import {lockFilePatterns, State, Outputs} from './constants';
export const restoreCache = async (cacheDependencyPath?: string) => {
const lockFilePath = cacheDependencyPath || (await findLockFile());
const fileHash = await glob.hashFiles(lockFilePath);
if (!fileHash) {
throw new Error(
'Some specified paths were not resolved, unable to cache dependencies.'
);
}
const platform = process.env.RUNNER_OS;
const primaryKey = `dotnet-cache-${platform}-${fileHash}`;
core.debug(`primary key is ${primaryKey}`);
core.saveState(State.CachePrimaryKey, primaryKey);
const {'global-packages': cachePath} = await getNuGetFolderPath();
const cacheKey = await cache.restoreCache([cachePath], primaryKey);
core.setOutput(Outputs.CacheHit, Boolean(cacheKey));
if (!cacheKey) {
core.info('Dotnet cache is not found');
return;
}
core.saveState(State.CacheMatchedKey, cacheKey);
core.info(`Cache restored from key: ${cacheKey}`);
};
const findLockFile = async () => {
const workspace = process.env.GITHUB_WORKSPACE!;
const rootContent = await readdir(workspace);
const lockFile = lockFilePatterns.find(item => rootContent.includes(item));
if (!lockFile) {
throw new Error(
`Dependencies lock file is not found in ${workspace}. Supported file patterns: ${lockFilePatterns.toString()}`
);
}
return join(workspace, lockFile);
};
+61
View File
@@ -0,0 +1,61 @@
import * as core from '@actions/core';
import * as cache from '@actions/cache';
import fs from 'node:fs';
import {getNuGetFolderPath} from './cache-utils';
import {State} from './constants';
// Catch and log any unhandled exceptions. These exceptions can leak out of the uploadChunk method in
// @actions/toolkit when a failed upload closes the file descriptor causing any in-process reads to
// throw an uncaught exception. Instead of failing this action, just warn.
process.on('uncaughtException', e => {
const warningPrefix = '[warning]';
core.info(`${warningPrefix}${e.message}`);
});
export async function run() {
try {
if (core.getBooleanInput('cache')) {
await cachePackages();
}
} catch (error) {
core.setFailed(error.message);
}
}
const cachePackages = async () => {
const state = core.getState(State.CacheMatchedKey);
const primaryKey = core.getState(State.CachePrimaryKey);
if (!primaryKey) {
core.info('Primary key was not generated, not saving cache.');
return;
}
const {'global-packages': cachePath} = await getNuGetFolderPath();
if (!fs.existsSync(cachePath)) {
throw new Error(
`Cache folder path is retrieved for .NET CLI but doesn't exist on disk: ${cachePath}`
);
}
if (primaryKey === state) {
core.info(
`Cache hit occurred on the primary key ${primaryKey}, not saving cache.`
);
return;
}
const cacheId = await cache.saveCache([cachePath], primaryKey);
if (cacheId === -1) {
// saveCache returns -1 without throwing when the cache was not saved, e.g.
// a reserve collision or a read-only token (fork PR). @actions/cache has
// already logged the reason at the appropriate severity, so just trace it.
core.debug(`Cache was not saved for the key: ${primaryKey}`);
return;
}
core.info(`Cache saved with the key: ${primaryKey}`);
};
run();
+105
View File
@@ -0,0 +1,105 @@
import * as cache from '@actions/cache';
import * as core from '@actions/core';
import * as exec from '@actions/exec';
import {cliCommand} from './constants';
type NuGetFolderName =
| 'http-cache'
| 'global-packages'
| 'temp'
| 'plugins-cache';
/**
* Get NuGet global packages, cache, and temp folders from .NET CLI.
* @returns (Folder Name)-(Path) mappings
* @see https://docs.microsoft.com/nuget/consume-packages/managing-the-global-packages-and-cache-folders
* @example
* Windows
* ```json
* {
* "http-cache": "C:\\Users\\user1\\AppData\\Local\\NuGet\\v3-cache",
* "global-packages": "C:\\Users\\user1\\.nuget\\packages\\",
* "temp": "C:\\Users\\user1\\AppData\\Local\\Temp\\NuGetScratch",
* "plugins-cache": "C:\\Users\\user1\\AppData\\Local\\NuGet\\plugins-cache"
* }
* ```
*
* Mac/Linux
* ```json
* {
* "http-cache": "/home/user1/.local/share/NuGet/v3-cache",
* "global-packages": "/home/user1/.nuget/packages/",
* "temp": "/tmp/NuGetScratch",
* "plugins-cache": "/home/user1/.local/share/NuGet/plugins-cache"
* }
* ```
*/
export const getNuGetFolderPath = async () => {
const {stdout, stderr, exitCode} = await exec.getExecOutput(
cliCommand,
undefined,
{ignoreReturnCode: true, silent: true}
);
if (exitCode) {
throw new Error(
!stderr.trim()
? `The '${cliCommand}' command failed with exit code: ${exitCode}`
: stderr
);
}
const result: Record<NuGetFolderName, string> = {
'http-cache': '',
'global-packages': '',
temp: '',
'plugins-cache': ''
};
const regex = /(?:^|\s)(?<key>[a-z-]+): (?<path>.+[/\\].+)$/gm;
let match: RegExpExecArray | null;
while ((match = regex.exec(stdout)) !== null) {
const key = match.groups!.key;
if ((key as NuGetFolderName) in result) {
result[key] = match.groups!.path;
}
}
return result;
};
export function isCacheFeatureAvailable(): boolean {
if (cache.isFeatureAvailable()) {
return true;
}
if (isGhes()) {
core.warning(
'Cache action is only supported on GHES version >= 3.5. If you are on version >=3.5 Please check with GHES admin if Actions cache service is enabled or not.'
);
return false;
}
core.warning(
'The runner was not able to contact the cache service. Caching will be skipped'
);
return false;
}
/**
* Returns this action runs on GitHub Enterprise Server or not.
*/
function isGhes(): boolean {
const ghUrl = new URL(
process.env['GITHUB_SERVER_URL'] || 'https://github.com'
);
const hostname = ghUrl.hostname.trimEnd().toUpperCase();
const isGitHubHost = hostname === 'GITHUB.COM';
const isGitHubEnterpriseCloudHost = hostname.endsWith('.GHE.COM');
const isLocalHost = hostname.endsWith('.LOCALHOST');
return !isGitHubHost && !isGitHubEnterpriseCloudHost && !isLocalHost;
}
+19
View File
@@ -0,0 +1,19 @@
/** NuGet lock file patterns */
export const lockFilePatterns = ['packages.lock.json'];
/**
* .NET CLI command to list local NuGet resources.
* @see https://docs.microsoft.com/dotnet/core/tools/dotnet-nuget-locals
*/
export const cliCommand =
'dotnet nuget locals all --list --force-english-output';
export enum State {
CachePrimaryKey = 'CACHE_KEY',
CacheMatchedKey = 'CACHE_RESULT'
}
export enum Outputs {
CacheHit = 'cache-hit',
DotnetVersion = 'dotnet-version'
}
+464
View File
@@ -0,0 +1,464 @@
// Load tempDirectory before it gets wiped by tool-cache
import * as core from '@actions/core';
import * as exec from '@actions/exec';
import * as io from '@actions/io';
import * as hc from '@actions/http-client';
import {chmodSync} from 'fs';
import path from 'path';
import os from 'os';
import semver from 'semver';
import {IS_WINDOWS, PLATFORM} from './utils';
import {QualityOptions} from './setup-dotnet';
export interface DotnetVersion {
type: string;
value: string;
qualityFlag: boolean;
}
interface ReleaseIndexEntry {
'channel-version': string;
'support-phase': string;
'release-type': string;
}
interface ReleaseIndexResponse {
'releases-index': ReleaseIndexEntry[];
}
const QUALITY_INPUT_MINIMAL_MAJOR_TAG = 6;
const LATEST_PATCH_SYNTAX_MINIMAL_MAJOR_TAG = 5;
export class DotnetVersionResolver {
private inputVersion: string;
private resolvedArgument: DotnetVersion;
constructor(
version: string,
private quality: QualityOptions = '',
private dotnetChannel?: string
) {
this.inputVersion = version.trim();
this.resolvedArgument = {type: '', value: '', qualityFlag: false};
}
private isVersionChannel(channel: string): boolean {
// A.B format (e.g., 3.1, 8.0)
if (/^\d+\.\d+$/.test(channel)) return true;
// A.B.Cxx format (e.g., 8.0.1xx) is supported only for .NET 5.0+
const latestPatchMatch = channel.match(/^(\d+)\.\d+\.\d{1}xx$/);
if (latestPatchMatch) {
const major = Number(latestPatchMatch[1]);
return (
!Number.isNaN(major) && major >= LATEST_PATCH_SYNTAX_MINIMAL_MAJOR_TAG
);
}
return false;
}
private async resolveVersionInput(): Promise<void> {
if (this.inputVersion.toLowerCase() === 'latest') {
const channel = this.dotnetChannel || '';
if (this.isVersionChannel(channel)) {
// A.B or A.B.Cxx channels are passed directly to the install script
this.resolvedArgument.value = channel;
} else {
// LTS, STS, or empty — resolve via releases index API
this.resolvedArgument.value = await this.getLatestVersion(channel);
}
this.resolvedArgument.type = 'channel';
const latestChannelMajorTag = Number(
this.resolvedArgument.value.split('.')[0]
);
this.resolvedArgument.qualityFlag =
!Number.isNaN(latestChannelMajorTag) &&
latestChannelMajorTag >= QUALITY_INPUT_MINIMAL_MAJOR_TAG;
return;
}
if (this.dotnetChannel) {
core.warning(
`The 'dotnet-channel' input is only supported when 'dotnet-version' is set to 'latest'.`
);
}
if (!semver.validRange(this.inputVersion) && !this.isLatestPatchSyntax()) {
throw new Error(
`The 'dotnet-version' was supplied in invalid format: ${this.inputVersion}! Supported syntax: A.B.C, A.B, A.B.x, A, A.x, A.B.Cxx, latest`
);
}
if (semver.valid(this.inputVersion)) {
this.createVersionArgument();
} else {
await this.createChannelArgument();
}
}
private isNumericTag(versionTag): boolean {
return /^\d+$/.test(versionTag);
}
private isLatestPatchSyntax() {
const majorTag = this.inputVersion.match(
/^(?<majorTag>\d+)\.\d+\.\d{1}x{2}$/
)?.groups?.majorTag;
if (
majorTag &&
parseInt(majorTag) < LATEST_PATCH_SYNTAX_MINIMAL_MAJOR_TAG
) {
throw new Error(
`The 'dotnet-version' was supplied in invalid format: ${this.inputVersion}! The A.B.Cxx syntax is available since the .NET 5.0 release.`
);
}
return majorTag ? true : false;
}
private createVersionArgument() {
this.resolvedArgument.type = 'version';
this.resolvedArgument.value = this.inputVersion;
}
private async createChannelArgument() {
this.resolvedArgument.type = 'channel';
const [major, minor] = this.inputVersion.split('.');
if (this.isLatestPatchSyntax()) {
this.resolvedArgument.value = this.inputVersion;
} else if (this.isNumericTag(major) && this.isNumericTag(minor)) {
this.resolvedArgument.value = `${major}.${minor}`;
} else if (this.isNumericTag(major)) {
// Starting with .NET 5, the minor version is always zero.
// Hardcode the earlier versions because they will not get new releases.
switch (major) {
case '1':
this.resolvedArgument.value = '1.1';
break;
case '2':
this.resolvedArgument.value = '2.2';
break;
case '3':
this.resolvedArgument.value = '3.1';
break;
default:
this.resolvedArgument.value = `${major}.0`;
break;
}
} else {
// If "dotnet-version" is specified as *, x or X resolve latest version of .NET explicitly from LTS channel. The version argument will default to "latest" by install-dotnet script.
this.resolvedArgument.value = 'LTS';
}
this.resolvedArgument.qualityFlag =
parseInt(major) >= QUALITY_INPUT_MINIMAL_MAJOR_TAG ? true : false;
}
public async createDotnetVersion(): Promise<DotnetVersion> {
await this.resolveVersionInput();
if (!this.resolvedArgument.type) {
return this.resolvedArgument;
}
if (IS_WINDOWS) {
this.resolvedArgument.type =
this.resolvedArgument.type === 'channel' ? '-Channel' : '-Version';
} else {
this.resolvedArgument.type =
this.resolvedArgument.type === 'channel' ? '--channel' : '--version';
}
return this.resolvedArgument;
}
private async getLatestVersion(channelFilter: string): Promise<string> {
const httpClient = new hc.HttpClient('actions/setup-dotnet', [], {
allowRetries: true,
maxRetries: 3
});
const response = await httpClient.getJson<ReleaseIndexResponse>(
DotnetVersionResolver.DotnetCoreIndexUrl
);
const result = response.result;
const rawReleasesInfo = result?.['releases-index'];
if (!Array.isArray(rawReleasesInfo)) {
throw new Error('Unexpected response format from .NET releases index.');
}
let releasesInfo = rawReleasesInfo;
// Filter out EOL versions
releasesInfo = releasesInfo.filter(info => info['support-phase'] !== 'eol');
// Filter out preview versions if quality is not 'preview' or 'daily'
// If quality is not specified, we assume strict stability (GA only)
const normalizedQuality = (this.quality || '').toLowerCase();
if (!['preview', 'daily'].includes(normalizedQuality)) {
releasesInfo = releasesInfo.filter(
info => info['support-phase'] !== 'preview'
);
}
// Apply channel filter (LTS/STS)
if (channelFilter) {
const type = channelFilter.toLowerCase();
releasesInfo = releasesInfo.filter(info => info['release-type'] === type);
}
releasesInfo.sort((a, b) => {
const partsA = a['channel-version'].split('.').map(Number);
const partsB = b['channel-version'].split('.').map(Number);
for (let i = 0; i < Math.max(partsA.length, partsB.length); i++) {
const diff = (partsB[i] || 0) - (partsA[i] || 0);
if (diff !== 0) return diff;
}
return 0;
});
if (releasesInfo.length === 0) {
throw new Error(
`Could not find any active releases matching channel '${
channelFilter || 'any'
}'`
);
}
return releasesInfo[0]['channel-version'];
}
static DotnetCoreIndexUrl =
'https://builds.dotnet.microsoft.com/dotnet/release-metadata/releases-index.json';
}
export class DotnetInstallScript {
private scriptName = IS_WINDOWS ? 'install-dotnet.ps1' : 'install-dotnet.sh';
private escapedScript: string;
private scriptArguments: string[] = [];
constructor() {
this.escapedScript = path
.join(__dirname, '..', '..', 'externals', this.scriptName)
.replace(/'/g, "''");
if (IS_WINDOWS) {
this.setupScriptPowershell();
return;
}
this.setupScriptBash();
}
private setupScriptPowershell() {
this.scriptArguments = [
'-NoLogo',
'-Sta',
'-NoProfile',
'-NonInteractive',
'-ExecutionPolicy',
'Unrestricted',
'-Command'
];
this.scriptArguments.push('&', `'${this.escapedScript}'`);
if (process.env['https_proxy'] != null) {
this.scriptArguments.push(`-ProxyAddress ${process.env['https_proxy']}`);
}
// This is not currently an option
if (process.env['no_proxy'] != null) {
this.scriptArguments.push(`-ProxyBypassList ${process.env['no_proxy']}`);
}
}
private setupScriptBash() {
chmodSync(this.escapedScript, '777');
}
private async getScriptPath() {
if (IS_WINDOWS) {
return (await io.which('pwsh', false)) || io.which('powershell', true);
}
return io.which(this.escapedScript, true);
}
public useArguments(...args: string[]) {
this.scriptArguments.push(...args);
return this;
}
// When architecture is empty/undefined, the installer auto-detects the current runner architecture.
public useArchitecture(architecture?: string) {
if (!architecture) return this;
this.useArguments(
IS_WINDOWS ? '-Architecture' : '--architecture',
architecture
);
return this;
}
public useVersion(dotnetVersion: DotnetVersion, quality?: QualityOptions) {
if (dotnetVersion.type) {
this.useArguments(dotnetVersion.type, dotnetVersion.value);
}
if (quality && !dotnetVersion.qualityFlag) {
core.warning(
`The 'dotnet-quality' input can be used only with .NET SDK version in A.B, A.B.x, A, A.x and A.B.Cxx formats where the major tag is higher than 5. You specified: ${dotnetVersion.value}. 'dotnet-quality' input is ignored.`
);
return this;
}
if (quality) {
this.useArguments(IS_WINDOWS ? '-Quality' : '--quality', quality);
}
return this;
}
public async execute() {
const getExecOutputOptions = {
ignoreReturnCode: true,
env: process.env as {string: string}
};
return exec.getExecOutput(
`"${await this.getScriptPath()}"`,
this.scriptArguments,
getExecOutputOptions
);
}
}
export abstract class DotnetInstallDir {
private static readonly default = {
linux: '/usr/share/dotnet',
mac: path.join(process.env['HOME'] + '', '.dotnet'),
windows: path.join(process.env['PROGRAMFILES'] + '', 'dotnet')
};
public static readonly dirPath = process.env['DOTNET_INSTALL_DIR']
? DotnetInstallDir.convertInstallPathToAbsolute(
process.env['DOTNET_INSTALL_DIR']
)
: DotnetInstallDir.default[PLATFORM];
private static convertInstallPathToAbsolute(installDir: string): string {
if (path.isAbsolute(installDir)) return path.normalize(installDir);
const transformedPath = installDir.startsWith('~')
? path.join(os.homedir(), installDir.slice(1))
: path.join(process.cwd(), installDir);
return path.normalize(transformedPath);
}
public static addToPath() {
core.addPath(process.env['DOTNET_INSTALL_DIR']!);
core.exportVariable('DOTNET_ROOT', process.env['DOTNET_INSTALL_DIR']);
}
public static setEnvironmentVariable() {
process.env['DOTNET_INSTALL_DIR'] = DotnetInstallDir.dirPath;
}
}
export function normalizeArch(arch: string): string {
switch (arch.toLowerCase()) {
case 'amd64':
return 'x64';
case 'ia32':
return 'x86';
default:
return arch.toLowerCase();
}
}
export class DotnetCoreInstaller {
static {
DotnetInstallDir.setEnvironmentVariable();
}
constructor(
private version: string,
private quality: QualityOptions,
private architecture?: string,
private dotnetChannel?: string
) {}
public async installDotnet(): Promise<string | null> {
const versionResolver = new DotnetVersionResolver(
this.version,
this.quality,
this.dotnetChannel
);
const dotnetVersion = await versionResolver.createDotnetVersion();
const architectureArguments =
this.architecture &&
normalizeArch(this.architecture) !== normalizeArch(os.arch())
? [
IS_WINDOWS ? '-InstallDir' : '--install-dir',
IS_WINDOWS
? `"${path.join(DotnetInstallDir.dirPath, this.architecture)}"`
: path.join(DotnetInstallDir.dirPath, this.architecture)
]
: [];
/**
* Install dotnet runtime first in order to get
* the latest stable version of dotnet CLI
*/
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'
)
// Install only runtime + CLI
.useArguments(IS_WINDOWS ? '-Runtime' : '--runtime', 'dotnet')
// Use latest stable version
.useArguments(IS_WINDOWS ? '-Channel' : '--channel', 'LTS')
.useArguments(...architectureArguments)
.execute();
if (runtimeInstallOutput.exitCode) {
/**
* dotnetInstallScript will install CLI and runtime even if previous script haven't succeded,
* so at this point it's too early to throw an error
*/
core.warning(
`Failed to install dotnet runtime + cli, exit code: ${runtimeInstallOutput.exitCode}. ${runtimeInstallOutput.stderr}`
);
}
/**
* Install dotnet over the latest version of
* dotnet CLI
*/
const dotnetInstallOutput = await new DotnetInstallScript()
.useArchitecture(this.architecture)
// Don't overwrite CLI because it should be already installed
.useArguments(
IS_WINDOWS ? '-SkipNonVersionedFiles' : '--skip-non-versioned-files'
)
// Use version provided by user
.useVersion(dotnetVersion, this.quality)
.useArguments(...architectureArguments)
.execute();
if (dotnetInstallOutput.exitCode) {
throw new Error(
`Failed to install dotnet, exit code: ${dotnetInstallOutput.exitCode}. ${dotnetInstallOutput.stderr}`
);
}
return this.parseInstalledVersion(dotnetInstallOutput.stdout);
}
private parseInstalledVersion(stdout: string): string | null {
const regex = /(?<version>\d+\.\d+\.\d+[a-z0-9._-]*)/gm;
const matchedResult = regex.exec(stdout);
if (!matchedResult) {
core.warning(`Failed to parse installed by the script version of .NET`);
return null;
}
return matchedResult.groups!.version;
}
}
+278
View File
@@ -0,0 +1,278 @@
import * as core from '@actions/core';
import * as exec from '@actions/exec';
import {
DotnetCoreInstaller,
DotnetInstallDir,
normalizeArch
} from './installer';
import * as fs from 'fs';
import path from 'path';
import semver from 'semver';
import os from 'os';
import * as auth from './authutil';
import {isCacheFeatureAvailable} from './cache-utils';
import {restoreCache} from './cache-restore';
import {Outputs} from './constants';
import JSON5 from 'json5';
const qualityOptions = ['daily', 'preview', 'ga'] as const;
const supportedArchitectures = [
'x64',
'x86',
'arm64',
'amd64',
'arm',
's390x',
'ppc64le',
'riscv64'
] as const;
type SupportedArchitecture = (typeof supportedArchitectures)[number];
export type QualityOptions = (typeof qualityOptions)[number] | '';
function isValidChannel(channel: string): boolean {
const upper = channel.toUpperCase();
if (upper === 'LTS' || upper === 'STS') return true;
// A.B format (e.g., 3.1, 8.0)
if (/^\d+\.\d+$/.test(channel)) return true;
// A.B.Cxx format (e.g., 8.0.1xx) - available since 5.0
const match = channel.match(/^(?<major>\d+)\.\d+\.\d{1}xx$/);
if (match && parseInt(match.groups!.major) >= 5) return true;
return false;
}
export async function run() {
try {
//
// dotnet-version is optional, but needs to be provided for most use cases.
// If supplied, install / use from the tool cache.
// 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.
// If a valid version still can't be identified, nothing will be installed.
// Proxy, auth, (etc) are still set up, even if no version is identified
//
const versions = core.getMultilineInput('dotnet-version');
const installedDotnetVersions: (string | null)[] = [];
const architecture = getArchitectureInput();
let dotnetChannel = core.getInput('dotnet-channel');
const isLatestRequested = versions.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).`
);
} else {
core.warning(
`Value '${dotnetChannel}' is not supported for the 'dotnet-channel' option and will be ignored because 'dotnet-version' is not set to 'latest'. Supported values are: LTS, STS, A.B (e.g. 8.0), A.B.Cxx (e.g. 8.0.1xx).`
);
dotnetChannel = '';
}
} else if (dotnetChannel && !isLatestRequested) {
core.warning(
`The 'dotnet-channel' input is only supported when 'dotnet-version' is set to 'latest'.`
);
dotnetChannel = '';
}
const globalJsonFileInput = core.getInput('global-json-file');
if (globalJsonFileInput) {
const globalJsonPath = path.resolve(process.cwd(), globalJsonFileInput);
if (!fs.existsSync(globalJsonPath)) {
throw new Error(
`The specified global.json file '${globalJsonFileInput}' does not exist`
);
}
versions.push(getVersionFromGlobalJson(globalJsonPath));
}
if (!versions.length) {
// Try to fall back to global.json
core.debug('No version found, trying to find version from global.json');
const globalJsonPath = path.join(process.cwd(), 'global.json');
if (fs.existsSync(globalJsonPath)) {
versions.push(getVersionFromGlobalJson(globalJsonPath));
} else {
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)) {
throw new Error(
`Value '${quality}' is not supported for the 'dotnet-quality' option. Supported values are: daily, preview, ga.`
);
}
let dotnetInstaller: DotnetCoreInstaller;
const uniqueVersions = new Set<string>(
versions.map(v => (v.toLowerCase() === 'latest' ? 'latest' : v))
);
for (const version of uniqueVersions) {
dotnetInstaller = new DotnetCoreInstaller(
version,
quality,
architecture,
version.toLowerCase() === 'latest' ? dotnetChannel : undefined
);
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
);
}
DotnetInstallDir.addToPath();
const workloadsInput = core.getInput('workloads');
if (workloadsInput) {
const workloads = workloadsInput
.split(',')
.map(w => w.trim())
.filter(Boolean);
if (workloads.length) {
try {
core.info(`Refreshing workload manifests...`);
await exec.exec('dotnet', ['workload', 'update']);
core.info(`Installing workloads: ${workloads.join(', ')}`);
await exec.exec('dotnet', ['workload', 'install', ...workloads]);
} catch (err) {
throw new Error(
`Failed to install workloads [${workloads.join(', ')}]: ${err}`
);
}
}
}
}
const sourceUrl: string = core.getInput('source-url');
const configFile: string = core.getInput('config-file');
if (sourceUrl) {
auth.configAuthentication(sourceUrl, configFile);
}
outputInstalledVersion(installedDotnetVersions, globalJsonFileInput);
if (core.getBooleanInput('cache') && isCacheFeatureAvailable()) {
const cacheDependencyPath = core.getInput('cache-dependency-path');
await restoreCache(cacheDependencyPath);
}
const matchersPath = path.join(__dirname, '..', '..', '.github');
core.info(`##[add-matcher]${path.join(matchersPath, 'csc.json')}`);
} catch (error) {
core.setFailed(error.message);
}
}
function getArchitectureInput(): SupportedArchitecture | '' {
const raw = (core.getInput('architecture') || '').trim();
if (!raw) return '';
const normalized = raw.toLowerCase();
if ((supportedArchitectures as readonly string[]).includes(normalized)) {
return normalizeArch(normalized) as SupportedArchitecture;
}
throw new Error(
`Value '${raw}' is not supported for the 'architecture' option. Supported values are: ${supportedArchitectures.join(
', '
)}.`
);
}
function getVersionFromGlobalJson(globalJsonPath: string): string {
let version = '';
const globalJson = JSON5.parse(
// .trim() is necessary to strip BOM https://github.com/nodejs/node/issues/20649
fs.readFileSync(globalJsonPath, {encoding: 'utf8'}).trim(),
// is necessary as JSON5 supports wider variety of options for numbers: https://www.npmjs.com/package/json5#numbers
(key, value) => {
if (key === 'version' || key === 'rollForward') return String(value);
return value;
}
);
if (globalJson.sdk && globalJson.sdk.version) {
version = globalJson.sdk.version;
const rollForward = globalJson.sdk.rollForward;
if (rollForward && !semver.prerelease(version)) {
const versionPattern = /^\d+\.\d+\.[1-9]\d{2,}$/;
if (!versionPattern.test(version)) {
throw new Error(
`Version '${version}' is not valid for the 'sdk.version' value in global.json. ` +
`When 'rollForward' is specified, a full SDK version is required. ` +
`See: https://learn.microsoft.com/en-us/dotnet/core/tools/global-json`
);
}
const [major, minor, featurePatch] = version.split('.');
const feature = featurePatch.substring(0, 1);
switch (rollForward) {
case 'latestMajor':
version = '';
break;
case 'latestMinor':
version = `${major}`;
break;
case 'latestFeature':
version = `${major}.${minor}`;
break;
case 'latestPatch':
version = `${major}.${minor}.${feature}xx`;
break;
}
}
}
return version;
}
function outputInstalledVersion(
installedVersions: (string | null)[],
globalJsonFileInput: string
): void {
if (!installedVersions.length) {
core.info(`The '${Outputs.DotnetVersion}' output will not be set.`);
return;
}
if (installedVersions.includes(null)) {
core.warning(
`Failed to output the installed version of .NET. The '${Outputs.DotnetVersion}' output will not be set.`
);
return;
}
if (globalJsonFileInput) {
const versionToOutput = installedVersions.at(-1); // .NET SDK version parsed from the global.json file is installed last
core.setOutput(Outputs.DotnetVersion, versionToOutput);
return;
}
const versionToOutput = semver.maxSatisfying(
installedVersions as string[],
'*',
{
includePrerelease: true
}
);
core.setOutput(Outputs.DotnetVersion, versionToOutput);
}
run();
+6
View File
@@ -0,0 +1,6 @@
export const IS_WINDOWS = process.platform === 'win32';
export const PLATFORM = ((): 'windows' | 'linux' | 'mac' => {
if (process.platform === 'win32') return 'windows';
if (process.platform === 'linux') return 'linux';
return 'mac';
})();