Resolve MSBuild with a single discovery and probing pass

Read installation path and version from one vswhere JSON query. Probe architecture candidates in priority order, retain the first matching path, and stop without repeating filesystem checks.

Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
This commit is contained in:
Chet HuskandCopilot App committed 2026-11-13 13:50:22 -06:00
1 parent 50a58bfea2
commit 0e355a7858
4 files changed
+228 -208

No files matched your search

+78 -18
View File
@@ -14,16 +14,24 @@ const x86Path = path.join(
installationPath,
'MSBuild\\Current\\Bin\\MSBuild.exe'
)
const legacyPath = path.join(
installationPath,
'MSBuild\\15.0\\Bin\\MSBuild.exe'
)
async function runAction(
files: string[],
explicitArch = '',
version = '17.4.0.0',
nativeArchOverride = ''
nativeArchOverride = '',
installations = JSON.stringify([
{installationPath, installationVersion: version}
])
): Promise<{
addedPath: jest.Mock
failed: jest.Mock
exec: jest.Mock
existsSync: jest.Mock
}> {
const platform = Object.getOwnPropertyDescriptor(process, 'platform')
const runnerArch = process.env['RUNNER_ARCH']
@@ -34,18 +42,18 @@ async function runAction(
})
const addedPath = jest.fn(() => finish())
const failed = jest.fn(() => finish())
const existsSync = jest.fn(
(file: string) => file === 'vswhere.exe' || files.includes(file)
)
const exec = jest.fn(
async (command: string, _args: string[], options: ExecOptions) => {
const stdout = options.listeners && options.listeners.stdout
if (!stdout) {
throw new Error('Missing stdout listener')
}
if (command.includes('installationVersion')) {
stdout(Buffer.from(version.slice(0, 3)))
stdout(Buffer.from(`${version.slice(3)}\n`))
} else if (command.includes('installationPath')) {
stdout(Buffer.from('visual-'))
stdout(Buffer.from('studio\n'))
if (command.includes('vswhere.exe')) {
stdout(Buffer.from(installations.slice(0, 12)))
stdout(Buffer.from(installations.slice(12)))
} else {
stdout(Buffer.from('17.4.0\n'))
}
@@ -76,14 +84,19 @@ async function runAction(
which: jest.fn().mockResolvedValue('vswhere.exe')
}))
jest.doMock('os', () => ({arch: () => 'x64'}))
jest.doMock('fs', () => ({
existsSync: (file: string) =>
file === 'vswhere.exe' || files.includes(file)
}))
jest.doMock('fs', () => ({existsSync}))
require('../src/main')
await finished
return {addedPath, failed, exec}
expect(existsSync.mock.calls).toEqual(
Array.from(
new Set(existsSync.mock.calls.map(call => call[0]))
).map(file => [file])
)
expect(
exec.mock.calls.filter(call => call[0].includes('vswhere.exe'))
).toHaveLength(1)
return {addedPath, failed, exec, existsSync}
} finally {
if (platform) {
Object.defineProperty(process, 'platform', platform)
@@ -113,6 +126,7 @@ describe('ARM64 action selection', () => {
[],
expect.anything()
)
expect(result.existsSync.mock.calls).toEqual([['vswhere.exe'], [arm64Path]])
})
it('uses the native Windows architecture when a 32-bit runner is emulated', async () => {
@@ -142,6 +156,11 @@ describe('ARM64 action selection', () => {
[],
expect.anything()
)
expect(result.existsSync.mock.calls).toEqual([
['vswhere.exe'],
[arm64Path],
[x64Path]
])
})
it('falls back to x86 when neither 64-bit executable is installed', async () => {
@@ -154,6 +173,12 @@ describe('ARM64 action selection', () => {
[],
expect.anything()
)
expect(result.existsSync.mock.calls).toEqual([
['vswhere.exe'],
[arm64Path],
[x64Path],
[x86Path]
])
})
it('uses x86 for Visual Studio versions older than 17', async () => {
@@ -168,7 +193,7 @@ describe('ARM64 action selection', () => {
)
})
it('respects explicit x86 without querying the version', async () => {
it('respects explicit x86 without probing other architectures', async () => {
const result = await runAction([arm64Path, x86Path], 'x86')
expect(result.failed).not.toHaveBeenCalled()
@@ -178,11 +203,7 @@ describe('ARM64 action selection', () => {
[],
expect.anything()
)
expect(
result.exec.mock.calls.some(call =>
call[0].includes('installationVersion')
)
).toBe(false)
expect(result.existsSync.mock.calls).toEqual([['vswhere.exe'], [x86Path]])
})
it('does not fall back when an explicit ARM64 executable is missing', async () => {
@@ -190,5 +211,44 @@ describe('ARM64 action selection', () => {
expect(result.addedPath).not.toHaveBeenCalled()
expect(result.failed).toHaveBeenCalledWith('Unable to find MSBuild.')
expect(result.existsSync.mock.calls).toEqual([['vswhere.exe'], [arm64Path]])
})
it('probes each legacy x86 path once', async () => {
const result = await runAction([legacyPath], 'x86')
expect(result.failed).not.toHaveBeenCalled()
expect(result.exec).toHaveBeenCalledWith(
`"${legacyPath}" -version -nologo`,
[],
expect.anything()
)
expect(result.existsSync.mock.calls).toEqual([
['vswhere.exe'],
[x86Path],
[legacyPath]
])
})
it('does not probe executables when no installation matches', async () => {
const result = await runAction([], '', '', '', '[]')
expect(result.failed).toHaveBeenCalledWith('Unable to find MSBuild.')
expect(result.existsSync.mock.calls).toEqual([['vswhere.exe']])
})
it('reports invalid installation output without probing executables', async () => {
const result = await runAction(
[],
'',
'',
'',
'{"installationPath":"wrong"}'
)
expect(result.failed).toHaveBeenCalledWith(
'Invalid Visual Studio installation data from vswhere.'
)
expect(result.existsSync.mock.calls).toEqual([['vswhere.exe']])
})
})
+16 -31
View File
@@ -1,4 +1,4 @@
import {parseMajorVersion, resolveMSBuildArchitecture} from '../src/main'
import {parseMajorVersion, getMSBuildArchitectures} from '../src/main'
jest.mock('@actions/core', () => ({
getInput: jest.fn().mockReturnValue(''),
@@ -28,48 +28,33 @@ describe('parseMajorVersion', () => {
})
})
describe('resolveMSBuildArchitecture', () => {
describe('getMSBuildArchitectures', () => {
it('always respects an explicit architecture, regardless of OS/version', () => {
expect(resolveMSBuildArchitecture('x86', 'arm64', 17, true, true)).toBe(
'x86'
)
expect(resolveMSBuildArchitecture('x64', 'ia32', 15, false, false)).toBe(
'x64'
)
expect(resolveMSBuildArchitecture('arm64', 'x64', 16, false, false)).toBe(
'arm64'
)
expect(getMSBuildArchitectures('x86', 'arm64', 17)).toEqual(['x86'])
expect(getMSBuildArchitectures('x64', 'ia32', 15)).toEqual(['x64'])
expect(getMSBuildArchitectures('arm64', 'x64', 16)).toEqual(['arm64'])
})
it('defaults to x64 on an x64 host with VS 17 or later', () => {
expect(resolveMSBuildArchitecture('', 'x64', 17, false, false)).toBe('x64')
expect(resolveMSBuildArchitecture('', 'amd64', 18, false, false)).toBe(
'x64'
)
expect(getMSBuildArchitectures('', 'x64', 17)).toEqual(['x64'])
expect(getMSBuildArchitectures('', 'amd64', 18)).toEqual(['x64'])
})
it('prefers native ARM64 when it is available', () => {
expect(resolveMSBuildArchitecture('', 'arm64', 17, true, true)).toBe(
'arm64'
)
})
it('falls back to x64 and then x86 when ARM64 MSBuild is unavailable', () => {
expect(resolveMSBuildArchitecture('', 'arm64', 17, false, true)).toBe('x64')
expect(resolveMSBuildArchitecture('', 'arm64', 17, false, false)).toBe(
it('orders ARM64 candidates from native to emulated architectures', () => {
expect(getMSBuildArchitectures('', 'arm64', 17)).toEqual([
'arm64',
'x64',
'x86'
)
])
})
it('defaults to x86 for older versions and 32-bit hosts', () => {
expect(resolveMSBuildArchitecture('', 'arm64', 16, true, true)).toBe('x86')
expect(resolveMSBuildArchitecture('', 'x64', 16, false, false)).toBe('x86')
expect(resolveMSBuildArchitecture('', 'ia32', 17, false, false)).toBe('x86')
expect(getMSBuildArchitectures('', 'arm64', 16)).toEqual(['x86'])
expect(getMSBuildArchitectures('', 'x64', 16)).toEqual(['x86'])
expect(getMSBuildArchitectures('', 'ia32', 17)).toEqual(['x86'])
})
it('defaults to x86 when the VS/MSBuild version could not be determined', () => {
expect(resolveMSBuildArchitecture('', 'arm64', undefined, true, true)).toBe(
'x86'
)
expect(getMSBuildArchitectures('', 'arm64', undefined)).toEqual(['x86'])
})
})
+58 -61
View File
@@ -34,28 +34,24 @@ const VS_VERSION = core.getInput('vs-version') || 'latest';
const VSWHERE_PATH = core.getInput('vswhere-path');
const ALLOW_PRERELEASE = core.getInput('vs-prerelease') || 'false';
const MSBUILD_ARCH_INPUT = core.getInput('msbuild-architecture');
let MSBUILD_ARCH = MSBUILD_ARCH_INPUT;
// The minimum Visual Studio version for the v4 automatic 64-bit default.
exports.MIN_VS_VERSION_FOR_X64 = 17;
function resolveMSBuildArchitecture(explicitArch, hostArch, vsMajorVersion, arm64Available, x64Available) {
const MIN_VS_VERSION_FOR_X64 = 17;
function getMSBuildArchitectures(explicitArch, hostArch, vsMajorVersion) {
if (explicitArch) {
return explicitArch;
return [explicitArch];
}
if (vsMajorVersion === undefined || vsMajorVersion < exports.MIN_VS_VERSION_FOR_X64) {
return 'x86';
if (vsMajorVersion === undefined || vsMajorVersion < MIN_VS_VERSION_FOR_X64) {
return ['x86'];
}
if (hostArch === 'arm64') {
if (arm64Available) {
return 'arm64';
}
return x64Available ? 'x64' : 'x86';
return ['arm64', 'x64', 'x86'];
}
if (hostArch === 'x64' || hostArch === 'amd64') {
return 'x64';
return ['x64'];
}
return 'x86';
return ['x86'];
}
exports.resolveMSBuildArchitecture = resolveMSBuildArchitecture;
exports.getMSBuildArchitectures = getMSBuildArchitectures;
// Parses the major version number out of a vswhere `installationVersion` string
// such as "17.9.34728.123". Returns undefined if it cannot be parsed.
function parseMajorVersion(installationVersion) {
@@ -68,7 +64,7 @@ function parseMajorVersion(installationVersion) {
}
exports.parseMajorVersion = parseMajorVersion;
// if a specific version of VS is requested
let VSWHERE_EXEC = '-products * -requires Microsoft.Component.MSBuild -property installationPath -latest ';
let VSWHERE_EXEC = '-products * -requires Microsoft.Component.MSBuild -format json -utf8 -latest ';
if (ALLOW_PRERELEASE === 'true') {
VSWHERE_EXEC += ' -prerelease ';
}
@@ -109,79 +105,80 @@ function run() {
return;
}
core.debug(`Full tool exe: ${vswhereToolExe}`);
let vsMajorVersion;
if (!MSBUILD_ARCH_INPUT) {
let installationVersion = '';
const versionOptions = {};
versionOptions.listeners = {
stdout: (data) => {
installationVersion += data.toString();
}
};
const versionExec = VSWHERE_EXEC.replace('-property installationPath', '-property installationVersion');
yield exec.exec(`"${vswhereToolExe}" ${versionExec}`, [], versionOptions);
core.debug(`Found installation version: ${installationVersion.trim()}`);
vsMajorVersion = parseMajorVersion(installationVersion);
}
let installationPath = '';
const output = [];
const options = {};
options.listeners = {
stdout: (data) => {
installationPath += data.toString();
output.push(data);
}
};
yield exec.exec(`"${vswhereToolExe}" ${VSWHERE_EXEC}`, [], options);
installationPath = installationPath.trim();
core.debug(`Found installation path: ${installationPath}`);
if (!installationPath) {
const installations = JSON.parse(Buffer.concat(output).toString('utf8'));
if (!Array.isArray(installations)) {
throw new Error('Invalid Visual Studio installation data from vswhere.');
}
if (installations.length === 0) {
core.setFailed('Unable to find MSBuild.');
return;
}
if (!MSBUILD_ARCH_INPUT) {
const installation = installations[0];
if (typeof installation !== 'object' ||
installation === null ||
!('installationPath' in installation)) {
throw new Error('Invalid Visual Studio installation data from vswhere.');
}
const { installationPath, installationVersion } = installation;
if (typeof installationPath !== 'string' || !installationPath) {
throw new Error('Invalid Visual Studio installation path from vswhere.');
}
core.debug(`Found installation path: ${installationPath}`);
const vsMajorVersion = typeof installationVersion === 'string'
? parseMajorVersion(installationVersion)
: undefined;
core.debug(`Found installation version: ${installationVersion}`);
// os.arch() describes Node, which can run under emulation on Windows.
const hostArch = (process.env['PROCESSOR_ARCHITEW6432'] ||
process.env['RUNNER_ARCH'] ||
os.arch()).toLowerCase();
const arm64Available = hostArch === 'arm64' &&
fs.existsSync(path.join(installationPath, 'MSBuild\\Current\\Bin\\arm64\\MSBuild.exe'));
const x64Available = hostArch === 'arm64' &&
!arm64Available &&
fs.existsSync(path.join(installationPath, 'MSBuild\\Current\\Bin\\amd64\\MSBuild.exe'));
MSBUILD_ARCH = resolveMSBuildArchitecture(MSBUILD_ARCH_INPUT, hostArch, vsMajorVersion, arm64Available, x64Available);
if (hostArch === 'arm64' &&
vsMajorVersion !== undefined &&
vsMajorVersion >= exports.MIN_VS_VERSION_FOR_X64 &&
!arm64Available) {
core.info(`ARM64 MSBuild not found; using ${MSBUILD_ARCH} instead`);
}
core.info(`Auto-detected msbuild-architecture: ${MSBUILD_ARCH} (host architecture=${hostArch}, vsMajorVersion=${vsMajorVersion})`);
}
const architectures = getMSBuildArchitectures(MSBUILD_ARCH_INPUT, hostArch, vsMajorVersion);
let msbuildArch = '';
let foundToolPath = '';
if (MSBUILD_ARCH === 'x64' || MSBUILD_ARCH === 'arm64') {
const directory = MSBUILD_ARCH === 'x64' ? 'amd64' : 'arm64';
const toolPath = path.join(installationPath, `MSBuild\\Current\\Bin\\${directory}\\MSBuild.exe`);
for (const architecture of architectures) {
const relativePaths = architecture === 'x64' || architecture === 'arm64'
? [
`MSBuild\\Current\\Bin\\${architecture === 'x64' ? 'amd64' : 'arm64'}\\MSBuild.exe`
]
: [
'MSBuild\\Current\\Bin\\MSBuild.exe',
'MSBuild\\15.0\\Bin\\MSBuild.exe'
];
for (const relativePath of relativePaths) {
const toolPath = path.join(installationPath, relativePath);
core.debug(`Checking for path: ${toolPath}`);
if (fs.existsSync(toolPath)) {
foundToolPath = toolPath;
msbuildArch = architecture;
break;
}
}
else {
let toolPath = path.join(installationPath, 'MSBuild\\Current\\Bin\\MSBuild.exe');
core.debug(`Checking for path: ${toolPath}`);
if (!fs.existsSync(toolPath)) {
toolPath = path.join(installationPath, 'MSBuild\\15.0\\Bin\\MSBuild.exe');
core.debug(`Checking for path: ${toolPath}`);
}
if (fs.existsSync(toolPath)) {
foundToolPath = toolPath;
if (foundToolPath) {
break;
}
}
if (!foundToolPath) {
core.setFailed('Unable to find MSBuild.');
return;
}
if (!MSBUILD_ARCH_INPUT) {
if (hostArch === 'arm64' &&
architectures[0] === 'arm64' &&
msbuildArch !== 'arm64') {
core.info(`ARM64 MSBuild not found; using ${msbuildArch} instead`);
}
core.info(`Auto-detected msbuild-architecture: ${msbuildArch} (host architecture=${hostArch}, vsMajorVersion=${vsMajorVersion})`);
}
core.info(`Found MSBuild tool path: ${foundToolPath}`);
core.info(`Using MSBuild architecture: ${MSBUILD_ARCH}`);
core.info(`Using MSBuild architecture: ${msbuildArch}`);
// try to get the MSBuild version for diagnostic purposes; a failure here shouldn't fail the action
try {
let msbuildVersion = '';
+76 -98
View File
@@ -11,38 +11,32 @@ const VS_VERSION = core.getInput('vs-version') || 'latest'
const VSWHERE_PATH = core.getInput('vswhere-path')
const ALLOW_PRERELEASE = core.getInput('vs-prerelease') || 'false'
const MSBUILD_ARCH_INPUT = core.getInput('msbuild-architecture')
let MSBUILD_ARCH = MSBUILD_ARCH_INPUT
// The minimum Visual Studio version for the v4 automatic 64-bit default.
export const MIN_VS_VERSION_FOR_X64 = 17
const MIN_VS_VERSION_FOR_X64 = 17
export function resolveMSBuildArchitecture(
export function getMSBuildArchitectures(
explicitArch: string,
hostArch: string,
vsMajorVersion: number | undefined,
arm64Available: boolean,
x64Available: boolean
): string {
vsMajorVersion: number | undefined
): string[] {
if (explicitArch) {
return explicitArch
return [explicitArch]
}
if (vsMajorVersion === undefined || vsMajorVersion < MIN_VS_VERSION_FOR_X64) {
return 'x86'
return ['x86']
}
if (hostArch === 'arm64') {
if (arm64Available) {
return 'arm64'
}
return x64Available ? 'x64' : 'x86'
return ['arm64', 'x64', 'x86']
}
if (hostArch === 'x64' || hostArch === 'amd64') {
return 'x64'
return ['x64']
}
return 'x86'
return ['x86']
}
// Parses the major version number out of a vswhere `installationVersion` string
@@ -60,7 +54,7 @@ export function parseMajorVersion(
// if a specific version of VS is requested
let VSWHERE_EXEC =
'-products * -requires Microsoft.Component.MSBuild -property installationPath -latest '
'-products * -requires Microsoft.Component.MSBuild -format json -utf8 -latest '
if (ALLOW_PRERELEASE === 'true') {
VSWHERE_EXEC += ' -prerelease '
}
@@ -112,111 +106,82 @@ async function run(): Promise<void> {
core.debug(`Full tool exe: ${vswhereToolExe}`)
let vsMajorVersion: number | undefined
if (!MSBUILD_ARCH_INPUT) {
let installationVersion = ''
const versionOptions: ExecOptions = {}
versionOptions.listeners = {
stdout: (data: Buffer) => {
installationVersion += data.toString()
}
}
const versionExec = VSWHERE_EXEC.replace(
'-property installationPath',
'-property installationVersion'
)
await exec.exec(`"${vswhereToolExe}" ${versionExec}`, [], versionOptions)
core.debug(`Found installation version: ${installationVersion.trim()}`)
vsMajorVersion = parseMajorVersion(installationVersion)
}
let installationPath = ''
const output: Buffer[] = []
const options: ExecOptions = {}
options.listeners = {
stdout: (data: Buffer) => {
installationPath += data.toString()
output.push(data)
}
}
await exec.exec(`"${vswhereToolExe}" ${VSWHERE_EXEC}`, [], options)
installationPath = installationPath.trim()
core.debug(`Found installation path: ${installationPath}`)
if (!installationPath) {
const installations: unknown = JSON.parse(
Buffer.concat(output).toString('utf8')
)
if (!Array.isArray(installations)) {
throw new Error('Invalid Visual Studio installation data from vswhere.')
}
if (installations.length === 0) {
core.setFailed('Unable to find MSBuild.')
return
}
if (!MSBUILD_ARCH_INPUT) {
const installation: unknown = installations[0]
if (
typeof installation !== 'object' ||
installation === null ||
!('installationPath' in installation)
) {
throw new Error('Invalid Visual Studio installation data from vswhere.')
}
const {installationPath, installationVersion} = installation as {
installationPath: unknown
installationVersion?: unknown
}
if (typeof installationPath !== 'string' || !installationPath) {
throw new Error('Invalid Visual Studio installation path from vswhere.')
}
core.debug(`Found installation path: ${installationPath}`)
const vsMajorVersion =
typeof installationVersion === 'string'
? parseMajorVersion(installationVersion)
: undefined
core.debug(`Found installation version: ${installationVersion}`)
// os.arch() describes Node, which can run under emulation on Windows.
const hostArch = (
process.env['PROCESSOR_ARCHITEW6432'] ||
process.env['RUNNER_ARCH'] ||
os.arch()
).toLowerCase()
const arm64Available =
hostArch === 'arm64' &&
fs.existsSync(
path.join(
installationPath,
'MSBuild\\Current\\Bin\\arm64\\MSBuild.exe'
)
)
const x64Available =
hostArch === 'arm64' &&
!arm64Available &&
fs.existsSync(
path.join(
installationPath,
'MSBuild\\Current\\Bin\\amd64\\MSBuild.exe'
)
)
MSBUILD_ARCH = resolveMSBuildArchitecture(
const architectures = getMSBuildArchitectures(
MSBUILD_ARCH_INPUT,
hostArch,
vsMajorVersion,
arm64Available,
x64Available
vsMajorVersion
)
if (
hostArch === 'arm64' &&
vsMajorVersion !== undefined &&
vsMajorVersion >= MIN_VS_VERSION_FOR_X64 &&
!arm64Available
) {
core.info(`ARM64 MSBuild not found; using ${MSBUILD_ARCH} instead`)
}
core.info(
`Auto-detected msbuild-architecture: ${MSBUILD_ARCH} (host architecture=${hostArch}, vsMajorVersion=${vsMajorVersion})`
)
}
let msbuildArch = ''
let foundToolPath = ''
if (MSBUILD_ARCH === 'x64' || MSBUILD_ARCH === 'arm64') {
const directory = MSBUILD_ARCH === 'x64' ? 'amd64' : 'arm64'
const toolPath = path.join(
installationPath,
`MSBuild\\Current\\Bin\\${directory}\\MSBuild.exe`
)
core.debug(`Checking for path: ${toolPath}`)
if (fs.existsSync(toolPath)) {
foundToolPath = toolPath
}
} else {
let toolPath = path.join(
installationPath,
'MSBuild\\Current\\Bin\\MSBuild.exe'
)
core.debug(`Checking for path: ${toolPath}`)
if (!fs.existsSync(toolPath)) {
toolPath = path.join(
installationPath,
for (const architecture of architectures) {
const relativePaths =
architecture === 'x64' || architecture === 'arm64'
? [
`MSBuild\\Current\\Bin\\${
architecture === 'x64' ? 'amd64' : 'arm64'
}\\MSBuild.exe`
]
: [
'MSBuild\\Current\\Bin\\MSBuild.exe',
'MSBuild\\15.0\\Bin\\MSBuild.exe'
)
]
for (const relativePath of relativePaths) {
const toolPath = path.join(installationPath, relativePath)
core.debug(`Checking for path: ${toolPath}`)
}
if (fs.existsSync(toolPath)) {
foundToolPath = toolPath
msbuildArch = architecture
break
}
}
if (foundToolPath) {
break
}
}
@@ -225,8 +190,21 @@ async function run(): Promise<void> {
return
}
if (!MSBUILD_ARCH_INPUT) {
if (
hostArch === 'arm64' &&
architectures[0] === 'arm64' &&
msbuildArch !== 'arm64'
) {
core.info(`ARM64 MSBuild not found; using ${msbuildArch} instead`)
}
core.info(
`Auto-detected msbuild-architecture: ${msbuildArch} (host architecture=${hostArch}, vsMajorVersion=${vsMajorVersion})`
)
}
core.info(`Found MSBuild tool path: ${foundToolPath}`)
core.info(`Using MSBuild architecture: ${MSBUILD_ARCH}`)
core.info(`Using MSBuild architecture: ${msbuildArch}`)
// try to get the MSBuild version for diagnostic purposes; a failure here shouldn't fail the action
try {