[Windows] Apply code style rules to Windows scripts (#8957)

* Apply code style rules to Windows scripts

* Fix typo

* Fix configure-toolset script

* Fix parameters in Msys2 installation script

* Improve log readability

* Remove broken exit code validation
This commit is contained in:
Vasilii Polikarpov
2023-12-11 22:23:36 +01:00
committed by GitHub
parent 76d6f0f574
commit 7fe65a2204
54 changed files with 544 additions and 418 deletions

View File

@@ -4,10 +4,10 @@
################################################################################ ################################################################################
function Disable-InternetExplorerESC { function Disable-InternetExplorerESC {
$AdminKey = "HKLM:\SOFTWARE\Microsoft\Active Setup\Installed Components\{A509B1A7-37EF-4b3f-8CFC-4F3A74704073}" $adminKey = "HKLM:\SOFTWARE\Microsoft\Active Setup\Installed Components\{A509B1A7-37EF-4b3f-8CFC-4F3A74704073}"
$UserKey = "HKLM:\SOFTWARE\Microsoft\Active Setup\Installed Components\{A509B1A8-37EF-4b3f-8CFC-4F3A74704073}" $userKey = "HKLM:\SOFTWARE\Microsoft\Active Setup\Installed Components\{A509B1A8-37EF-4b3f-8CFC-4F3A74704073}"
Set-ItemProperty -Path $AdminKey -Name "IsInstalled" -Value 0 -Force Set-ItemProperty -Path $adminKey -Name "IsInstalled" -Value 0 -Force
Set-ItemProperty -Path $UserKey -Name "IsInstalled" -Value 0 -Force Set-ItemProperty -Path $userKey -Name "IsInstalled" -Value 0 -Force
$ieProcess = Get-Process -Name Explorer -ErrorAction SilentlyContinue $ieProcess = Get-Process -Name Explorer -ErrorAction SilentlyContinue
@@ -19,9 +19,9 @@ function Disable-InternetExplorerESC {
} }
function Disable-InternetExplorerWelcomeScreen { function Disable-InternetExplorerWelcomeScreen {
$AdminKey = "HKLM:\Software\Policies\Microsoft\Internet Explorer\Main" $adminKey = "HKLM:\Software\Policies\Microsoft\Internet Explorer\Main"
New-Item -Path $AdminKey -Value 1 -Force New-Item -Path $adminKey -Value 1 -Force
Set-ItemProperty -Path $AdminKey -Name "DisableFirstRunCustomize" -Value 1 -Force Set-ItemProperty -Path $adminKey -Name "DisableFirstRunCustomize" -Value 1 -Force
Write-Host "Disabled IE Welcome screen" Write-Host "Disabled IE Welcome screen"
} }
@@ -31,9 +31,9 @@ function Disable-UserAccessControl {
} }
function Disable-WindowsUpdate { function Disable-WindowsUpdate {
$AutoUpdatePath = "HKLM:SOFTWARE\Policies\Microsoft\Windows\WindowsUpdate\AU" $autoUpdatePath = "HKLM:SOFTWARE\Policies\Microsoft\Windows\WindowsUpdate\AU"
If (Test-Path -Path $AutoUpdatePath) { if (Test-Path -Path $autoUpdatePath) {
Set-ItemProperty -Path $AutoUpdatePath -Name NoAutoUpdate -Value 1 Set-ItemProperty -Path $autoUpdatePath -Name NoAutoUpdate -Value 1
Write-Host "Disabled Windows Update" Write-Host "Disabled Windows Update"
} else { } else {
Write-Host "Windows Update key does not exist" Write-Host "Windows Update key does not exist"

View File

@@ -4,10 +4,10 @@
################################################################################ ################################################################################
# Create AppModelUnlock if it doesn't exist, required for enabling Developer Mode # Create AppModelUnlock if it doesn't exist, required for enabling Developer Mode
$RegistryKeyPath = "HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\AppModelUnlock" $registryKeyPath = "HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\AppModelUnlock"
if (-not(Test-Path -Path $RegistryKeyPath)) { if (-not(Test-Path -Path $registryKeyPath)) {
New-Item -Path $RegistryKeyPath -ItemType Directory -Force New-Item -Path $registryKeyPath -ItemType Directory -Force
} }
# Add registry value to enable Developer Mode # Add registry value to enable Developer Mode
New-ItemProperty -Path $RegistryKeyPath -Name AllowDevelopmentWithoutDevLicense -PropertyType DWORD -Value 1 New-ItemProperty -Path $registryKeyPath -Name AllowDevelopmentWithoutDevLicense -PropertyType DWORD -Value 1

View File

@@ -1,3 +1,9 @@
################################################################################
## File: Configure-DynamicPort.ps1
## Desc: Configure dynamic port range for TCP and UDP to start at port 49152
## and to end at the 65536 (16384 ports)
################################################################################
# https://support.microsoft.com/en-us/help/929851/the-default-dynamic-port-range-for-tcp-ip-has-changed-in-windows-vista # https://support.microsoft.com/en-us/help/929851/the-default-dynamic-port-range-for-tcp-ip-has-changed-in-windows-vista
# The new default start port is 49152, and the new default end port is 65535. # The new default start port is 49152, and the new default end port is 65535.
# Default port configuration was changed during image generation by Visual Studio Enterprise Installer to: # Default port configuration was changed during image generation by Visual Studio Enterprise Installer to:
@@ -5,10 +11,17 @@
# --------------------------------- # ---------------------------------
# Start Port : 1024 # Start Port : 1024
# Number of Ports : 64511 # Number of Ports : 64511
Write-Host "Set the dynamic port range to start at port 49152 and to end at the 65536 (16384 ports)"
$null = netsh int ipv4 set dynamicport tcp start=49152 num=16384
$null = netsh int ipv4 set dynamicport udp start=49152 num=16384
$null = netsh int ipv6 set dynamicport tcp start=49152 num=16384
$null = netsh int ipv6 set dynamicport udp start=49152 num=16384
Invoke-PesterTests -TestFile "WindowsFeatures" -TestName "DynamicPorts" Write-Host "Set the dynamic port range to start at port 49152 and to end at the 65536 (16384 ports)"
foreach ($ipVersion in @("ipv4", "ipv6")) {
foreach ($protocol in @("tcp", "udp")) {
$command = "netsh int $ipVersion set dynamicport $protocol start=49152 num=16384"
Invoke-Expression $command | Out-Null
if ($LASTEXITCODE -ne 0) {
Write-Host "Failed to set dynamic port range for $ipVersion $protocol"
exit $LASTEXITCODE
}
}
}
Invoke-PesterTests -TestFile "WindowsFeatures" -TestName "DynamicPorts"

View File

@@ -1,3 +1,8 @@
################################################################################
## File: Configure-GDIProcessHandleQuota.ps1
## Desc: Set the GDIProcessHandleQuota value to 20000
################################################################################
# https://docs.microsoft.com/en-us/windows/win32/sysinfo/gdi-objects # https://docs.microsoft.com/en-us/windows/win32/sysinfo/gdi-objects
# This value can be set to a number between 256 and 65,536 # This value can be set to a number between 256 and 65,536

View File

@@ -16,15 +16,15 @@ $imageDataFile = $env:IMAGEDATA_FILE
$githubUrl = "https://github.com/actions/runner-images/blob" $githubUrl = "https://github.com/actions/runner-images/blob"
if (Test-IsWin22) { if (Test-IsWin22) {
$imageLabel = "windows-2022" $imageLabel = "windows-2022"
$softwareUrl = "${githubUrl}/win22/$imageMajorVersion.$imageMinorVersion/images/windows/Windows2022-Readme.md" $softwareUrl = "${githubUrl}/win22/$imageMajorVersion.$imageMinorVersion/images/windows/Windows2022-Readme.md"
$releaseUrl = "https://github.com/actions/runner-images/releases/tag/win22%2F$imageMajorVersion.$imageMinorVersion" $releaseUrl = "https://github.com/actions/runner-images/releases/tag/win22%2F$imageMajorVersion.$imageMinorVersion"
} elseif (Test-IsWin19) { } elseif (Test-IsWin19) {
$imageLabel = "windows-2019" $imageLabel = "windows-2019"
$softwareUrl = "${githubUrl}/win19/$imageMajorVersion.$imageMinorVersion/images/windows/Windows2019-Readme.md" $softwareUrl = "${githubUrl}/win19/$imageMajorVersion.$imageMinorVersion/images/windows/Windows2019-Readme.md"
$releaseUrl = "https://github.com/actions/runner-images/releases/tag/win19%2F$imageMajorVersion.$imageMinorVersion" $releaseUrl = "https://github.com/actions/runner-images/releases/tag/win19%2F$imageMajorVersion.$imageMinorVersion"
} else { } else {
throw "Invalid platform version is found. Either Windows Server 2019 or 2022 are required" throw "Invalid platform version is found. Either Windows Server 2019 or 2022 are required"
} }
$json = @" $json = @"

View File

@@ -17,7 +17,7 @@ $PSModuleAnalysisCachePath = 'C:\PSModuleAnalysisCachePath\ModuleAnalysisCache'
# make variable to be available in the current session # make variable to be available in the current session
${env:PSModuleAnalysisCachePath} = $PSModuleAnalysisCachePath ${env:PSModuleAnalysisCachePath} = $PSModuleAnalysisCachePath
$null = New-Item -Path $PSModuleAnalysisCachePath -ItemType 'File' -Force New-Item -Path $PSModuleAnalysisCachePath -ItemType 'File' -Force | Out-Null
#endregion #endregion
#region User (current user, image generation only) #region User (current user, image generation only)

View File

@@ -4,7 +4,10 @@
################################################################################ ################################################################################
Write-Host "Cleanup WinSxS" Write-Host "Cleanup WinSxS"
Dism.exe /online /Cleanup-Image /StartComponentCleanup /ResetBase dism.exe /online /Cleanup-Image /StartComponentCleanup /ResetBase
if ($LASTEXITCODE -ne 0) {
throw "Failed to cleanup WinSxS"
}
# Set default version to 1 for WSL (aka LXSS - Linux Subsystem) # Set default version to 1 for WSL (aka LXSS - Linux Subsystem)
# The value should be set in the default user registry hive # The value should be set in the default user registry hive
@@ -47,7 +50,13 @@ Write-Host "Clean up various directories"
if (Test-Path $_) { if (Test-Path $_) {
Write-Host "Removing $_" Write-Host "Removing $_"
cmd /c "takeown /d Y /R /f $_ 2>&1" | Out-Null cmd /c "takeown /d Y /R /f $_ 2>&1" | Out-Null
if ($LASTEXITCODE -ne 0) {
throw "Failed to take ownership of $_"
}
cmd /c "icacls $_ /grant:r administrators:f /t /c /q 2>&1" | Out-Null cmd /c "icacls $_ /grant:r administrators:f /t /c /q 2>&1" | Out-Null
if ($LASTEXITCODE -ne 0) {
throw "Failed to grant administrators full control of $_"
}
Remove-Item $_ -Recurse -Force -ErrorAction SilentlyContinue | Out-Null Remove-Item $_ -Recurse -Force -ErrorAction SilentlyContinue | Out-Null
} }
} }
@@ -60,11 +69,21 @@ Remove-Item $profile.AllUsersAllHosts -Force -ErrorAction SilentlyContinue | Out
# Clean yarn and npm cache # Clean yarn and npm cache
cmd /c "yarn cache clean 2>&1" | Out-Null cmd /c "yarn cache clean 2>&1" | Out-Null
if ($LASTEXITCODE -ne 0) {
throw "Failed to clean yarn cache"
}
cmd /c "npm cache clean --force 2>&1" | Out-Null cmd /c "npm cache clean --force 2>&1" | Out-Null
if ($LASTEXITCODE -ne 0) {
throw "Failed to clean npm cache"
}
# allow msi to write to temp folder # allow msi to write to temp folder
# see https://github.com/actions/runner-images/issues/1704 # see https://github.com/actions/runner-images/issues/1704
cmd /c "icacls $env:SystemRoot\Temp /grant Users:f /t /c /q 2>&1" | Out-Null cmd /c "icacls $env:SystemRoot\Temp /grant Users:f /t /c /q 2>&1" | Out-Null
if ($LASTEXITCODE -ne 0) {
throw "Failed to grant Users full control of $env:SystemRoot\Temp"
}
# Registry settings # Registry settings
$registrySettings = @( $registrySettings = @(

View File

@@ -4,12 +4,11 @@
################################################################################ ################################################################################
$variables = @{ $variables = @{
"ImageVersion" = $env:IMAGE_VERSION "ImageVersion" = $env:IMAGE_VERSION
"ImageOS" = $env:IMAGE_OS "ImageOS" = $env:IMAGE_OS
"AGENT_TOOLSDIRECTORY" = $env:AGENT_TOOLSDIRECTORY "AGENT_TOOLSDIRECTORY" = $env:AGENT_TOOLSDIRECTORY
"ACTIONS_RUNNER_ACTION_ARCHIVE_CACHE" = $env:ACTIONS_RUNNER_ACTION_ARCHIVE_CACHE
} }
$variables.GetEnumerator() | ForEach-Object { $variables.GetEnumerator() | ForEach-Object {
[Environment]::SetEnvironmentVariable($_.Key, $_.Value, "Machine") [Environment]::SetEnvironmentVariable($_.Key, $_.Value, "Machine")
} }

View File

@@ -4,60 +4,37 @@
## Desc: Configure Toolset ## Desc: Configure Toolset
################################################################################ ################################################################################
Function Set-DefaultVariables $toolEnvConfigs = @{
{
param
(
[Parameter(Mandatory=$true)]
[object] $EnvVars,
[Parameter(Mandatory=$true)]
[string] $ToolVersionPath
)
$templates = $EnvVars.pathTemplates
foreach ($template in $templates)
{
$toolSystemPath = $template -f $ToolVersionPath
Add-MachinePathItem -PathItem $toolSystemPath | Out-Null
}
if (-not ([string]::IsNullOrEmpty($EnvVars.defaultVariable)))
{
[Environment]::SetEnvironmentVariable($toolEnvVars.defaultVariable, $ToolVersionPath, "Machine")
}
}
# Define executables for cached tools
$toolsEnvironmentVariables = @{
Python = @{ Python = @{
pathTemplates = @( pathTemplates = @(
"{0}", "{0}"
"{0}\Scripts" "{0}\Scripts"
) )
} }
go = @{ go = @{
pathTemplates = @( pathTemplates = @(
"{0}\bin" "{0}\bin"
) )
variableTemplate = "GOROOT_{0}_{1}_X64" envVarTemplate = "GOROOT_{0}_{1}_X64"
} }
} }
$toolsToConfigure = @("Python", "Go") $tools = Get-ToolsetContent `
$tools = Get-ToolsetContent | Select-Object -ExpandProperty toolcache ` | Select-Object -ExpandProperty toolcache `
| Where-Object { $toolsToConfigure -contains $_.name } | Where-Object { $toolEnvConfigs.Keys -contains $_.name }
Write-Host "Configure toolset tools environment..." Write-Host "Configure toolset tools environment..."
foreach ($tool in $tools) { foreach ($tool in $tools) {
$toolEnvVars = $toolsEnvironmentVariables[$tool.name] $toolEnvConfig = $toolEnvConfigs[$tool.name]
if (-not ([string]::IsNullOrEmpty($toolEnvVars.variableTemplate))) { if (-not ([string]::IsNullOrEmpty($toolEnvConfig.envVarTemplate))) {
foreach ($version in $tool.versions) { foreach ($version in $tool.versions) {
Write-Host "Set $($tool.name) $version environment variable..." Write-Host "Set $($tool.name) $version environment variable..."
$foundVersionArchPath = Get-TCToolVersionPath -Name $tool.name -Version $version -Arch $tool.arch $foundVersionArchPath = Get-TCToolVersionPath -Name $tool.name -Version $version -Arch $tool.arch
$envName = $toolEnvVars.variableTemplate -f $version.Split(".") $envName = $toolEnvConfig.envVarTemplate -f $version.Split(".")
Write-Host "Set $envName to $foundVersionArchPath"
[Environment]::SetEnvironmentVariable($envName, $foundVersionArchPath, "Machine") [Environment]::SetEnvironmentVariable($envName, $foundVersionArchPath, "Machine")
} }
} }
@@ -67,7 +44,16 @@ foreach ($tool in $tools) {
$toolVersionPath = Get-TCToolVersionPath -Name $tool.name -Version $tool.default -Arch $tool.arch $toolVersionPath = Get-TCToolVersionPath -Name $tool.name -Version $tool.default -Arch $tool.arch
Set-DefaultVariables -ToolVersionPath $toolVersionPath -EnvVars $toolEnvVars foreach ($template in $toolEnvConfig.pathTemplates) {
$toolSystemPath = $template -f $toolVersionPath
Write-Host "Add $toolSystemPath to system PATH..."
Add-MachinePathItem -PathItem $toolSystemPath | Out-Null
}
if (-not ([string]::IsNullOrEmpty($tool.defaultVariable))) {
Write-Host "Set $($tool.name) $($tool.default) $($tool.defaultVariable) environment variable..."
[Environment]::SetEnvironmentVariable($tool.defaultVariable, $toolVersionPath, "Machine")
}
} }
} }

View File

@@ -9,17 +9,23 @@
# #
Write-Host "Warmup 'devenv.exe /updateconfiguration'" Write-Host "Warmup 'devenv.exe /updateconfiguration'"
$vsInstallRoot = (Get-VisualStudioInstance).InstallationPath $vsInstallRoot = (Get-VisualStudioInstance).InstallationPath
$devEnvPath = "$vsInstallRoot\Common7\IDE\devenv.exe" cmd.exe /c "`"$vsInstallRoot\Common7\IDE\devenv.exe`" /updateconfiguration"
if ($LASTEXITCODE -ne 0) {
cmd.exe /c "`"$devEnvPath`" /updateconfiguration" throw "Failed to warmup 'devenv.exe /updateconfiguration'"
}
# we are fine if some file is locked and cannot be copied # we are fine if some file is locked and cannot be copied
Copy-Item ${env:USERPROFILE}\AppData\Local\Microsoft\VisualStudio -Destination c:\users\default\AppData\Local\Microsoft\VisualStudio -Recurse -ErrorAction SilentlyContinue Copy-Item ${env:USERPROFILE}\AppData\Local\Microsoft\VisualStudio -Destination c:\users\default\AppData\Local\Microsoft\VisualStudio -Recurse -ErrorAction SilentlyContinue
reg.exe load HKLM\DEFAULT c:\users\default\ntuser.dat Mount-RegistryHive `
-FileName "C:\Users\Default\NTUSER.DAT" `
-SubKey "HKLM\DEFAULT"
reg.exe copy HKCU\Software\Microsoft\VisualStudio HKLM\DEFAULT\Software\Microsoft\VisualStudio /s reg.exe copy HKCU\Software\Microsoft\VisualStudio HKLM\DEFAULT\Software\Microsoft\VisualStudio /s
if ($LASTEXITCODE -ne 0) {
throw "Failed to copy HKCU\Software\Microsoft\VisualStudio to HKLM\DEFAULT\Software\Microsoft\VisualStudio"
}
# disable TSVNCache.exe # disable TSVNCache.exe
$registryKeyPath = 'HKCU:\Software\TortoiseSVN' $registryKeyPath = 'HKCU:\Software\TortoiseSVN'
@@ -27,8 +33,12 @@ if (-not(Test-Path -Path $registryKeyPath)) {
New-Item -Path $registryKeyPath -ItemType Directory -Force New-Item -Path $registryKeyPath -ItemType Directory -Force
} }
New-ItemProperty -Path $RegistryKeyPath -Name CacheType -PropertyType DWORD -Value 0 New-ItemProperty -Path $registryKeyPath -Name CacheType -PropertyType DWORD -Value 0
reg.exe copy HKCU\Software\TortoiseSVN HKLM\DEFAULT\Software\TortoiseSVN /s reg.exe copy HKCU\Software\TortoiseSVN HKLM\DEFAULT\Software\TortoiseSVN /s
if ($LASTEXITCODE -ne 0) {
throw "Failed to copy HKCU\Software\TortoiseSVN to HKLM\DEFAULT\Software\TortoiseSVN"
}
Dismount-RegistryHive "HKLM\DEFAULT"
reg.exe unload HKLM\DEFAULT
Write-Host "Configure-User.ps1 - completed" Write-Host "Configure-User.ps1 - completed"

View File

@@ -4,9 +4,11 @@
## Maintainer: #actions-runtime and @TingluoHuang ## Maintainer: #actions-runtime and @TingluoHuang
################################################################################ ################################################################################
if (-not (Test-Path $env:ACTIONS_RUNNER_ACTION_ARCHIVE_CACHE)) { $actionArchiveCache = "C:\actionarchivecache\"
if (-not (Test-Path $actionArchiveCache)) {
Write-Host "Creating action archive cache folder" Write-Host "Creating action archive cache folder"
New-Item -ItemType Directory -Path $env:ACTIONS_RUNNER_ACTION_ARCHIVE_CACHE | Out-Null New-Item -ItemType Directory -Path $actionArchiveCache | Out-Null
} }
$downloadUrl = Resolve-GithubReleaseAssetUrl ` $downloadUrl = Resolve-GithubReleaseAssetUrl `
@@ -18,6 +20,8 @@ Write-Host "Download Latest action-versions archive from $downloadUrl"
$actionVersionsArchivePath = Invoke-DownloadWithRetry $downloadUrl $actionVersionsArchivePath = Invoke-DownloadWithRetry $downloadUrl
Write-Host "Expand action-versions archive" Write-Host "Expand action-versions archive"
Expand-7ZipArchive -Path $actionVersionsArchivePath -DestinationPath $env:ACTIONS_RUNNER_ACTION_ARCHIVE_CACHE Expand-7ZipArchive -Path $actionVersionsArchivePath -DestinationPath $actionArchiveCache
[Environment]::SetEnvironmentVariable("ACTIONS_RUNNER_ACTION_ARCHIVE_CACHE", $actionArchiveCache, "Machine")
Invoke-PesterTests -TestFile "ActionArchiveCache" Invoke-PesterTests -TestFile "ActionArchiveCache"

View File

@@ -9,13 +9,13 @@ $azureCliConfigPath = 'C:\azureCli'
# Store azure-cli cache outside of the provisioning user's profile # Store azure-cli cache outside of the provisioning user's profile
[Environment]::SetEnvironmentVariable('AZURE_CONFIG_DIR', $azureCliConfigPath, "Machine") [Environment]::SetEnvironmentVariable('AZURE_CONFIG_DIR', $azureCliConfigPath, "Machine")
$azureCliExtensionPath = Join-Path $Env:CommonProgramFiles 'AzureCliExtensionDirectory' $azureCliExtensionPath = Join-Path $env:CommonProgramFiles 'AzureCliExtensionDirectory'
New-Item -ItemType 'Directory' -Path $azureCliExtensionPath | Out-Null New-Item -ItemType 'Directory' -Path $azureCliExtensionPath | Out-Null
[Environment]::SetEnvironmentVariable('AZURE_EXTENSION_DIR', $azureCliExtensionPath, "Machine") [Environment]::SetEnvironmentVariable('AZURE_EXTENSION_DIR', $azureCliExtensionPath, "Machine")
Install-Binary -Type MSI ` Install-Binary -Type MSI `
-Url 'https://aka.ms/installazurecliwindowsx64' ` -Url 'https://aka.ms/installazurecliwindowsx64' `
-ExpectedSignature '72105B6D5F370B62FD5C82F1512F7AD7DEE5F2C0' -ExpectedSignature '72105B6D5F370B62FD5C82F1512F7AD7DEE5F2C0'
Update-Environment Update-Environment
@@ -23,7 +23,7 @@ Update-Environment
Write-Host "Warmup 'az'" Write-Host "Warmup 'az'"
az --help | Out-Null az --help | Out-Null
if ($LASTEXITCODE -ne 0) { if ($LASTEXITCODE -ne 0) {
throw "Command 'az --help' failed" throw "Command 'az --help' failed"
} }
Invoke-PesterTests -TestFile 'CLI.Tools' -TestName 'Azure CLI' Invoke-PesterTests -TestFile 'CLI.Tools' -TestName 'Azure CLI'

View File

@@ -4,7 +4,7 @@
#################################################################################### ####################################################################################
Install-Binary -Type MSI ` Install-Binary -Type MSI `
-Url "https://aka.ms/cosmosdb-emulator" ` -Url "https://aka.ms/cosmosdb-emulator" `
-ExpectedSignature "F372C27F6E052A6BE8BAB3112B465C692196CD6F" -ExpectedSignature "F372C27F6E052A6BE8BAB3112B465C692196CD6F"
Invoke-PesterTests -TestFile "Tools" -TestName "Azure Cosmos DB Emulator" Invoke-PesterTests -TestFile "Tools" -TestName "Azure Cosmos DB Emulator"

View File

@@ -15,16 +15,16 @@ Update-Environment
az extension add -n azure-devops az extension add -n azure-devops
if ($LASTEXITCODE -ne 0) { if ($LASTEXITCODE -ne 0) {
throw "Command 'az extension add -n azure-devops' failed" throw "Command 'az extension add -n azure-devops' failed"
} }
# Warm-up Azure DevOps CLI # Warm-up Azure DevOps CLI
Write-Host "Warmup 'az-devops'" Write-Host "Warmup 'az-devops'"
@('devops', 'pipelines', 'boards', 'repos', 'artifacts') | ForEach-Object { @('devops', 'pipelines', 'boards', 'repos', 'artifacts') | ForEach-Object {
az $_ --help az $_ --help
if ($LASTEXITCODE -ne 0) { if ($LASTEXITCODE -ne 0) {
throw "Command 'az $_ --help' failed" throw "Command 'az $_ --help' failed"
} }
} }
# calling az devops login to force it to install `keyring`. Login will actually fail, redirecting error to null # calling az devops login to force it to install `keyring`. Login will actually fail, redirecting error to null

View File

@@ -7,7 +7,7 @@ Install-ChocoPackage bazel
npm install -g @bazel/bazelisk npm install -g @bazel/bazelisk
if ($LASTEXITCODE -ne 0) { if ($LASTEXITCODE -ne 0) {
throw "Command 'npm install -g @bazel/bazelisk' failed" throw "Command 'npm install -g @bazel/bazelisk' failed"
} }
Invoke-PesterTests -TestFile "Tools" -TestName "Bazel" Invoke-PesterTests -TestFile "Tools" -TestName "Bazel"

View File

@@ -3,15 +3,15 @@
## Desc: Install BizTalk Project Build Component ## Desc: Install BizTalk Project Build Component
################################################################################ ################################################################################
$BuildComponentUri = "https://aka.ms/BuildComponentSetup.EN" $downloadUrl = "https://aka.ms/BuildComponentSetup.EN"
$BuildComponentSignatureThumbprint = "8740DF4ACB749640AD318E4BE842F72EC651AD80" $signatureThumbprint = "8740DF4ACB749640AD318E4BE842F72EC651AD80"
Write-Host "Downloading BizTalk Project Build Component archive..." Write-Host "Downloading BizTalk Project Build Component archive..."
$zipFile = Invoke-DownloadWithRetry $BuildComponentUri $zipFile = Invoke-DownloadWithRetry $downloadUrl
$setupPath = Join-Path $env:TEMP "BizTalkBuildComponent" $setupPath = Join-Path $env:TEMP "BizTalkBuildComponent"
if (-not (Test-Path -Path $setupPath)) { if (-not (Test-Path -Path $setupPath)) {
$null = New-Item -Path $setupPath -ItemType Directory -Force New-Item -Path $setupPath -ItemType Directory -Force | Out-Null
} }
Expand-7ZipArchive -Path $zipFile -DestinationPath $setupPath Expand-7ZipArchive -Path $zipFile -DestinationPath $setupPath
@@ -19,10 +19,10 @@ Write-Host "Installing BizTalk Project Build Component..."
Install-Binary ` Install-Binary `
-LocalPath "$setupPath\Bootstrap.msi" ` -LocalPath "$setupPath\Bootstrap.msi" `
-ExtraInstallArgs ("/l*v", "$setupPath\bootstrap.log") ` -ExtraInstallArgs ("/l*v", "$setupPath\bootstrap.log") `
-ExpectedSignature $BuildComponentSignatureThumbprint -ExpectedSignature $signatureThumbprint
Install-Binary ` Install-Binary `
-LocalPath "$setupPath\BuildComponentSetup.msi" ` -LocalPath "$setupPath\BuildComponentSetup.msi" `
-ExtraInstallArgs ("/l*v", "$setupPath\buildComponentSetup.log") ` -ExtraInstallArgs ("/l*v", "$setupPath\buildComponentSetup.log") `
-ExpectedSignature $BuildComponentSignatureThumbprint -ExpectedSignature $signatureThumbprint
Invoke-PesterTests -TestFile "BizTalk" -TestName "BizTalk Build Component Setup" Invoke-PesterTests -TestFile "BizTalk" -TestName "BizTalk Build Component Setup"

View File

@@ -14,9 +14,9 @@ Update-Environment
# Verify and run choco installer # Verify and run choco installer
$signatureThumbprint = "83AC7D88C66CB8680BCE802E0F0F5C179722764B" $signatureThumbprint = "83AC7D88C66CB8680BCE802E0F0F5C179722764B"
$InstallScriptPath = Invoke-DownloadWithRetry 'https://chocolatey.org/install.ps1' $installScriptPath = Invoke-DownloadWithRetry 'https://chocolatey.org/install.ps1'
Test-FileSignature -Path $InstallScriptPath -ExpectedThumbprint $signatureThumbprint Test-FileSignature -Path $installScriptPath -ExpectedThumbprint $signatureThumbprint
Invoke-Expression $InstallScriptPath Invoke-Expression $installScriptPath
# Turn off confirmation # Turn off confirmation
choco feature enable -n allowGlobalConfirmation choco feature enable -n allowGlobalConfirmation

View File

@@ -32,52 +32,51 @@ $regGoogleParameters = @(
) )
$regGoogleParameters | ForEach-Object { $regGoogleParameters | ForEach-Object {
$Arguments = $_ $arguments = $_
if (-not ($Arguments.Path)) { if (-not ($arguments.Path)) {
$Arguments.Add("Path", $regGoogleUpdatePath) $arguments.Add("Path", $regGoogleUpdatePath)
} }
$Arguments.Add("Force", $true) $arguments.Add("Force", $true)
New-ItemProperty @Arguments New-ItemProperty @arguments
} }
# Install Chrome WebDriver # Install Chrome WebDriver
Write-Host "Install Chrome WebDriver..." Write-Host "Install Chrome WebDriver..."
$ChromeDriverPath = "$($env:SystemDrive)\SeleniumWebDrivers\ChromeDriver" $chromeDriverPath = "$($env:SystemDrive)\SeleniumWebDrivers\ChromeDriver"
if (-not (Test-Path -Path $ChromeDriverPath)) { if (-not (Test-Path -Path $chromeDriverPath)) {
New-Item -Path $ChromeDriverPath -ItemType Directory -Force New-Item -Path $chromeDriverPath -ItemType Directory -Force
} }
Write-Host "Get the Chrome WebDriver download URL..." Write-Host "Get the Chrome WebDriver download URL..."
$RegistryPath = "HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\App Paths" $registryPath = "HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\App Paths"
$ChromePath = (Get-ItemProperty "$RegistryPath\chrome.exe").'(default)' $chromePath = (Get-ItemProperty "$registryPath\chrome.exe").'(default)'
[version] $ChromeVersion = [System.Diagnostics.FileVersionInfo]::GetVersionInfo($ChromePath).ProductVersion [version] $chromeVersion = [System.Diagnostics.FileVersionInfo]::GetVersionInfo($chromePath).ProductVersion
$ChromeBuild = "$($ChromeVersion.Major).$($ChromeVersion.Minor).$($ChromeVersion.Build)" $chromeBuild = "$($chromeVersion.Major).$($chromeVersion.Minor).$($chromeVersion.Build)"
$ChromeDriverVersionsUrl = "https://googlechromelabs.github.io/chrome-for-testing/latest-patch-versions-per-build-with-downloads.json" $chromeDriverVersionsUrl = "https://googlechromelabs.github.io/chrome-for-testing/latest-patch-versions-per-build-with-downloads.json"
Write-Host "Chrome version is $ChromeVersion" Write-Host "Chrome version is $chromeVersion"
$ChromeDriverVersions = Invoke-RestMethod -Uri $ChromeDriverVersionsUrl $chromeDriverVersions = Invoke-RestMethod -Uri $chromeDriverVersionsUrl
$ChromeDriverVersion = $ChromeDriverVersions.builds.$ChromeBuild $chromeDriverVersion = $chromeDriverVersions.builds.$chromeBuild
if (-not ($ChromeDriverVersion)) { if (-not ($chromeDriverVersion)) {
$availableVersions = $ChromeDriverVersions.builds | Get-Member | Select-Object -ExpandProperty Name $availableVersions = $chromeDriverVersions.builds | Get-Member | Select-Object -ExpandProperty Name
Write-Host "Available chromedriver builds are $availableVersions" Write-Host "Available chromedriver builds are $availableVersions"
throw "Can't determine chromedriver version that matches chrome build $ChromeBuild" throw "Can't determine chromedriver version that matches chrome build $chromeBuild"
} }
$ChromeDriverVersion.version | Out-File -FilePath "$ChromeDriverPath\versioninfo.txt" -Force; $chromeDriverVersion.version | Out-File -FilePath "$chromeDriverPath\versioninfo.txt" -Force;
Write-Host "Chrome WebDriver version to install is $($ChromeDriverVersion.version)" Write-Host "Chrome WebDriver version to install is $($chromeDriverVersion.version)"
$ChromeDriverZipDownloadUrl = ($ChromeDriverVersion.downloads.chromedriver | Where-Object platform -eq "win64").url $chromeDriverZipDownloadUrl = ($chromeDriverVersion.downloads.chromedriver | Where-Object platform -eq "win64").url
Write-Host "Download Chrome WebDriver from $ChromeDriverZipDownloadUrl..." Write-Host "Download Chrome WebDriver from $chromeDriverZipDownloadUrl..."
$ChromeDriverArchPath = Invoke-DownloadWithRetry $ChromeDriverZipDownloadUrl $chromeDriverArchPath = Invoke-DownloadWithRetry $chromeDriverZipDownloadUrl
Write-Host "Expand Chrome WebDriver archive (without using directory names)..." Write-Host "Expand Chrome WebDriver archive (without using directory names)..."
Expand-7ZipArchive -Path $ChromeDriverArchPath -DestinationPath $ChromeDriverPath -ExtractMethod "e" Expand-7ZipArchive -Path $chromeDriverArchPath -DestinationPath $chromeDriverPath -ExtractMethod "e"
Write-Host "Setting the environment variables..." Write-Host "Setting the environment variables..."
[Environment]::SetEnvironmentVariable("ChromeWebDriver", $ChromeDriverPath, "Machine") [Environment]::SetEnvironmentVariable("ChromeWebDriver", $chromeDriverPath, "Machine")
Add-MachinePathItem $ChromeDriverPath Add-MachinePathItem $chromeDriverPath
Update-Environment Update-Environment
Invoke-PesterTests -TestFile "Browsers" -TestName "Chrome" Invoke-PesterTests -TestFile "Browsers" -TestName "Chrome"

View File

@@ -4,23 +4,23 @@
################################################################################ ################################################################################
# Download the latest cf cli exe # Download the latest cf cli exe
$CloudFoundryCliUrl = "https://packages.cloudfoundry.org/stable?release=windows64-exe&source=github" $cloudFoundryCliUrl = "https://packages.cloudfoundry.org/stable?release=windows64-exe&source=github"
$CloudFoundryArchPath = Invoke-DownloadWithRetry $CloudFoundryCliUrl $cloudFoundryArchPath = Invoke-DownloadWithRetry $cloudFoundryCliUrl
# Create directory for cf cli # Create directory for cf cli
$CloudFoundryCliPath = "C:\cf-cli" $cloudFoundryCliPath = "C:\cf-cli"
New-Item -Path $CloudFoundryCliPath -ItemType Directory -Force New-Item -Path $cloudFoundryCliPath -ItemType Directory -Force
# Extract the zip archive # Extract the zip archive
Write-Host "Extracting cf cli..." Write-Host "Extracting cf cli..."
Expand-7ZipArchive -Path $CloudFoundryArchPath -DestinationPath $CloudFoundryCliPath Expand-7ZipArchive -Path $cloudFoundryArchPath -DestinationPath $cloudFoundryCliPath
# Add cf to path # Add cf to path
Add-MachinePathItem $CloudFoundryCliPath Add-MachinePathItem $cloudFoundryCliPath
# Validate cf signature # Validate cf signature
$CloudFoundrySignatureThumbprint = "4C69EDD13930ED01B83DD1D17B09C434DC1F2177" $cloudFoundrySignatureThumbprint = "4C69EDD13930ED01B83DD1D17B09C434DC1F2177"
Test-FileSignature -Path "$CloudFoundryCliPath\cf.exe" -ExpectedThumbprint $CloudFoundrySignatureThumbprint Test-FileSignature -Path "$cloudFoundryCliPath\cf.exe" -ExpectedThumbprint $cloudFoundrySignatureThumbprint
Invoke-PesterTests -TestFile "CLI.Tools" -TestName "CloudFoundry CLI" Invoke-PesterTests -TestFile "CLI.Tools" -TestName "CloudFoundry CLI"

View File

@@ -4,33 +4,33 @@
################################################################################ ################################################################################
# Retrieve the CLI version of the latest CodeQL bundle. # Retrieve the CLI version of the latest CodeQL bundle.
$Defaults = (Invoke-RestMethod "https://raw.githubusercontent.com/github/codeql-action/v2/src/defaults.json") $defaults = (Invoke-RestMethod "https://raw.githubusercontent.com/github/codeql-action/v2/src/defaults.json")
$CliVersion = $Defaults.cliVersion $cliVersion = $defaults.cliVersion
$TagName = "codeql-bundle-v" + $CliVersion $tagName = "codeql-bundle-v" + $cliVersion
Write-Host "Downloading CodeQL bundle $($CliVersion)..." Write-Host "Downloading CodeQL bundle $($cliVersion)..."
# Note that this is the all-platforms CodeQL bundle, to support scenarios where customers run # Note that this is the all-platforms CodeQL bundle, to support scenarios where customers run
# different operating systems within containers. # different operating systems within containers.
$CodeQLBundlePath = Invoke-DownloadWithRetry "https://github.com/github/codeql-action/releases/download/$($TagName)/codeql-bundle.tar.gz" $codeQLBundlePath = Invoke-DownloadWithRetry "https://github.com/github/codeql-action/releases/download/$($tagName)/codeql-bundle.tar.gz"
$DownloadDirectoryPath = (Get-Item $CodeQLBundlePath).Directory.FullName $downloadDirectoryPath = (Get-Item $codeQLBundlePath).Directory.FullName
$CodeQLToolcachePath = Join-Path $Env:AGENT_TOOLSDIRECTORY -ChildPath "CodeQL" | Join-Path -ChildPath $CliVersion | Join-Path -ChildPath "x64" $codeQLToolcachePath = Join-Path $env:AGENT_TOOLSDIRECTORY -ChildPath "CodeQL" | Join-Path -ChildPath $cliVersion | Join-Path -ChildPath "x64"
New-Item -Path $CodeQLToolcachePath -ItemType Directory -Force | Out-Null New-Item -Path $codeQLToolcachePath -ItemType Directory -Force | Out-Null
Write-Host "Unpacking the downloaded CodeQL bundle archive..." Write-Host "Unpacking the downloaded CodeQL bundle archive..."
Expand-7ZipArchive -Path $CodeQLBundlePath -DestinationPath $DownloadDirectoryPath Expand-7ZipArchive -Path $codeQLBundlePath -DestinationPath $downloadDirectoryPath
$UnGzipedCodeQLBundlePath = Join-Path $DownloadDirectoryPath "codeql-bundle.tar" $unGzipedCodeQLBundlePath = Join-Path $downloadDirectoryPath "codeql-bundle.tar"
Expand-7ZipArchive -Path $UnGzipedCodeQLBundlePath -DestinationPath $CodeQLToolcachePath Expand-7ZipArchive -Path $unGzipedCodeQLBundlePath -DestinationPath $codeQLToolcachePath
Write-Host "CodeQL bundle at $($CodeQLToolcachePath) contains the following directories:" Write-Host "CodeQL bundle at $($codeQLToolcachePath) contains the following directories:"
Get-ChildItem -Path $CodeQLToolcachePath -Depth 2 Get-ChildItem -Path $codeQLToolcachePath -Depth 2
# Touch a file to indicate to the CodeQL Action that this bundle shipped with the toolcache. This is # Touch a file to indicate to the CodeQL Action that this bundle shipped with the toolcache. This is
# to support overriding the CodeQL version specified in defaults.json on GitHub Enterprise. # to support overriding the CodeQL version specified in defaults.json on GitHub Enterprise.
New-Item -ItemType file (Join-Path $CodeQLToolcachePath -ChildPath "pinned-version") New-Item -ItemType file (Join-Path $codeQLToolcachePath -ChildPath "pinned-version")
# Touch a file to indicate to the toolcache that setting up CodeQL is complete. # Touch a file to indicate to the toolcache that setting up CodeQL is complete.
New-Item -ItemType file "$CodeQLToolcachePath.complete" New-Item -ItemType file "$codeQLToolcachePath.complete"
# Test that the tools have been extracted successfully. # Test that the tools have been extracted successfully.
Invoke-PesterTests -TestFile "Tools" -TestName "CodeQL Bundle" Invoke-PesterTests -TestFile "Tools" -TestName "CodeQL Bundle"

View File

@@ -4,7 +4,7 @@
#################################################################################### ####################################################################################
Install-Binary -Type MSI ` Install-Binary -Type MSI `
-Url 'https://aka.ms/dacfx-msi' ` -Url 'https://aka.ms/dacfx-msi' `
-ExpectedSignature '72105B6D5F370B62FD5C82F1512F7AD7DEE5F2C0' -ExpectedSignature '72105B6D5F370B62FD5C82F1512F7AD7DEE5F2C0'
Invoke-PesterTests -TestFile "Tools" -TestName "DACFx" Invoke-PesterTests -TestFile "Tools" -TestName "DACFx"

View File

@@ -42,13 +42,18 @@ function Invoke-DotnetWarmup {
) )
# warm up dotnet for first time experience # warm up dotnet for first time experience
$projectTypes = @('console', 'mstest', 'web', 'mvc', 'webapi') $projectTypes = @('console', 'mstest', 'web', 'mvc', 'webapi')
$projectTypes | ForEach-Object { foreach ($template in $projectTypes) {
$template = $_ $projectPath = Join-Path -Path "C:\temp" -ChildPath $template
$projectPath = Join-Path -Path C:\temp -ChildPath $template
New-Item -Path $projectPath -Force -ItemType Directory New-Item -Path $projectPath -Force -ItemType Directory
Push-Location -Path $projectPath Push-Location -Path $projectPath
& $env:ProgramFiles\dotnet\dotnet.exe new globaljson --sdk-version "$SDKVersion" & "$env:ProgramFiles\dotnet\dotnet.exe" new globaljson --sdk-version "$SDKVersion"
& $env:ProgramFiles\dotnet\dotnet.exe new $template if ($LastExitCode -ne 0) {
throw "Dotnet new globaljson failed with exit code $LastExitCode"
}
& "$env:ProgramFiles\dotnet\dotnet.exe" new $template
if ($LastExitCode -ne 0) {
throw "Dotnet new $template failed with exit code $LastExitCode"
}
Pop-Location Pop-Location
Remove-Item $projectPath -Force -Recurse Remove-Item $projectPath -Force -Recurse
} }
@@ -73,6 +78,8 @@ function Install-DotnetSDK {
Write-Host "Installing dotnet $SDKVersion" Write-Host "Installing dotnet $SDKVersion"
$zipPath = Join-Path ([IO.Path]::GetTempPath()) ([IO.Path]::GetRandomFileName()) $zipPath = Join-Path ([IO.Path]::GetTempPath()) ([IO.Path]::GetRandomFileName())
& $InstallScriptPath -Version $SDKVersion -InstallDir $(Join-Path -Path $env:ProgramFiles -ChildPath 'dotnet') -ZipPath $zipPath -KeepZip & $InstallScriptPath -Version $SDKVersion -InstallDir $(Join-Path -Path $env:ProgramFiles -ChildPath 'dotnet') -ZipPath $zipPath -KeepZip
# Installer is PowerShell script that doesn't set exit code on failure
# If installation failed, tests will fail anyway
#region Supply chain security #region Supply chain security
$releasesJsonUri = "https://dotnetcli.blob.core.windows.net/dotnet/release-metadata/${DotnetVersion}/releases.json" $releasesJsonUri = "https://dotnetcli.blob.core.windows.net/dotnet/release-metadata/${DotnetVersion}/releases.json"
@@ -110,13 +117,19 @@ if (Test-Path $nugetPath) {
# Generate and copy new NuGet.Config config # Generate and copy new NuGet.Config config
dotnet nuget list source | Out-Null dotnet nuget list source | Out-Null
Copy-Item -Path $nugetPath -Destination C:\Users\Default\AppData\Roaming -Force -Recurse if ($LastExitCode -ne 0) {
throw "Dotnet nuget list source failed with exit code $LastExitCode"
}
Copy-Item -Path $nugetPath -Destination "C:\Users\Default\AppData\Roaming" -Force -Recurse
# Install dotnet tools # Install dotnet tools
Write-Host "Installing dotnet tools" Write-Host "Installing dotnet tools"
Add-DefaultPathItem "%USERPROFILE%\.dotnet\tools" Add-DefaultPathItem "%USERPROFILE%\.dotnet\tools"
foreach ($dotnetTool in $dotnetToolset.tools) { foreach ($dotnetTool in $dotnetToolset.tools) {
dotnet tool install $($dotnetTool.name) --tool-path "C:\Users\Default\.dotnet\tools" --add-source https://api.nuget.org/v3/index.json | Out-Null dotnet tool install $($dotnetTool.name) --tool-path "C:\Users\Default\.dotnet\tools" --add-source "https://api.nuget.org/v3/index.json" | Out-Null
if ($LastExitCode -ne 0) {
throw "Dotnet tool install failed with exit code $LastExitCode"
}
} }
Invoke-PesterTests -TestFile "DotnetSDK" Invoke-PesterTests -TestFile "DotnetSDK"

View File

@@ -6,11 +6,11 @@
# Install and configure Firefox browser # Install and configure Firefox browser
Write-Host "Get the latest Firefox version..." Write-Host "Get the latest Firefox version..."
$VersionsManifest = Invoke-RestMethod "https://product-details.mozilla.org/1.0/firefox_versions.json" $versionsManifest = Invoke-RestMethod "https://product-details.mozilla.org/1.0/firefox_versions.json"
Write-Host "Install Firefox browser..." Write-Host "Install Firefox browser..."
$installerUrl = "https://download.mozilla.org/?product=firefox-$($VersionsManifest.LATEST_FIREFOX_VERSION)&os=win64&lang=en-US" $installerUrl = "https://download.mozilla.org/?product=firefox-$($versionsManifest.LATEST_FIREFOX_VERSION)&os=win64&lang=en-US"
$hashUrl = "https://archive.mozilla.org/pub/firefox/releases/$($VersionsManifest.LATEST_FIREFOX_VERSION)/SHA256SUMS" $hashUrl = "https://archive.mozilla.org/pub/firefox/releases/$($versionsManifest.LATEST_FIREFOX_VERSION)/SHA256SUMS"
$externalHash = Get-ChecksumFromUrl -Type "SHA256" ` $externalHash = Get-ChecksumFromUrl -Type "SHA256" `
-Url $hashUrl ` -Url $hashUrl `
@@ -22,42 +22,42 @@ Install-Binary -Type EXE `
-ExpectedSHA256Sum $externalHash -ExpectedSHA256Sum $externalHash
Write-Host "Disable autoupdate..." Write-Host "Disable autoupdate..."
$FirefoxDirectoryPath = Join-Path $env:ProgramFiles "Mozilla Firefox" $firefoxDirectoryPath = Join-Path $env:ProgramFiles "Mozilla Firefox"
New-Item -path $FirefoxDirectoryPath -Name 'mozilla.cfg' -Value '// New-Item -path $firefoxDirectoryPath -Name 'mozilla.cfg' -Value '//
pref("browser.shell.checkDefaultBrowser", false); pref("browser.shell.checkDefaultBrowser", false);
pref("app.update.enabled", false);' -ItemType file -force pref("app.update.enabled", false);' -ItemType file -force
$FirefoxPreferencesFolder = Join-Path $FirefoxDirectoryPath "defaults\pref" $firefoxPreferencesFolder = Join-Path $firefoxDirectoryPath "defaults\pref"
New-Item -path $FirefoxPreferencesFolder -Name 'local-settings.js' -Value 'pref("general.config.obscure_value", 0); New-Item -path $firefoxPreferencesFolder -Name 'local-settings.js' -Value 'pref("general.config.obscure_value", 0);
pref("general.config.filename", "mozilla.cfg");' -ItemType file -force pref("general.config.filename", "mozilla.cfg");' -ItemType file -force
# Download and install Gecko WebDriver # Download and install Gecko WebDriver
Write-Host "Install Gecko WebDriver..." Write-Host "Install Gecko WebDriver..."
$GeckoDriverPath = "$($env:SystemDrive)\SeleniumWebDrivers\GeckoDriver" $geckoDriverPath = "$($env:SystemDrive)\SeleniumWebDrivers\GeckoDriver"
if (-not (Test-Path -Path $GeckoDriverPath)) { if (-not (Test-Path -Path $geckoDriverPath)) {
New-Item -Path $GeckoDriverPath -ItemType Directory -Force New-Item -Path $geckoDriverPath -ItemType Directory -Force
} }
Write-Host "Get the Gecko WebDriver version..." Write-Host "Get the Gecko WebDriver version..."
$GeckoDriverVersion = (Get-GithubReleasesByVersion -Repo "mozilla/geckodriver" -Version "latest").version $geckoDriverVersion = (Get-GithubReleasesByVersion -Repo "mozilla/geckodriver" -Version "latest").version
$GeckoDriverVersion | Out-File -FilePath "$GeckoDriverPath\versioninfo.txt" -Force $geckoDriverVersion | Out-File -FilePath "$geckoDriverPath\versioninfo.txt" -Force
Write-Host "Download Gecko WebDriver WebDriver..." Write-Host "Download Gecko WebDriver WebDriver..."
$GeckoDriverDownloadUrl = Resolve-GithubReleaseAssetUrl ` $geckoDriverDownloadUrl = Resolve-GithubReleaseAssetUrl `
-Repo "mozilla/geckodriver" ` -Repo "mozilla/geckodriver" `
-Version $GeckoDriverVersion ` -Version $geckoDriverVersion `
-UrlMatchPattern "geckodriver-*-win64.zip" -UrlMatchPattern "geckodriver-*-win64.zip"
$GeckoDriverArchPath = Invoke-DownloadWithRetry $GeckoDriverDownloadUrl $geckoDriverArchPath = Invoke-DownloadWithRetry $geckoDriverDownloadUrl
Write-Host "Expand Gecko WebDriver archive..." Write-Host "Expand Gecko WebDriver archive..."
Expand-7ZipArchive -Path $GeckoDriverArchPath -DestinationPath $GeckoDriverPath Expand-7ZipArchive -Path $geckoDriverArchPath -DestinationPath $geckoDriverPath
# Validate Gecko WebDriver signature # Validate Gecko WebDriver signature
$GeckoDriverSignatureThumbprint = "1326B39C3D5D2CA012F66FB439026F7B59CB1974" $geckoDriverSignatureThumbprint = "1326B39C3D5D2CA012F66FB439026F7B59CB1974"
Test-FileSignature -Path "$GeckoDriverPath/geckodriver.exe" -ExpectedThumbprint $GeckoDriverSignatureThumbprint Test-FileSignature -Path "$geckoDriverPath/geckodriver.exe" -ExpectedThumbprint $geckoDriverSignatureThumbprint
Write-Host "Setting the environment variables..." Write-Host "Setting the environment variables..."
Add-MachinePathItem -PathItem $GeckoDriverPath Add-MachinePathItem -PathItem $geckoDriverPath
[Environment]::SetEnvironmentVariable("GeckoWebDriver", $GeckoDriverPath, "Machine") [Environment]::SetEnvironmentVariable("GeckoWebDriver", $geckoDriverPath, "Machine")
Invoke-PesterTests -TestFile "Browsers" -TestName "Firefox" Invoke-PesterTests -TestFile "Browsers" -TestName "Firefox"

View File

@@ -35,6 +35,9 @@ Install-Binary `
Update-Environment Update-Environment
git config --system --add safe.directory "*" git config --system --add safe.directory "*"
if ($LASTEXITCODE -ne 0) {
Write-Error "Failed to configure safe.directory for Git with exit code $LASTEXITCODE"
}
# Disable GCM machine-wide # Disable GCM machine-wide
[Environment]::SetEnvironmentVariable("GCM_INTERACTIVE", "Never", "Machine") [Environment]::SetEnvironmentVariable("GCM_INTERACTIVE", "Never", "Machine")

View File

@@ -30,23 +30,35 @@ Add-MachinePathItem "$cabalDir\bin"
Update-Environment Update-Environment
# Get 3 latest versions of GHC # Get 3 latest versions of GHC
$Versions = ghcup list -t ghc -r | Where-Object {$_ -notlike "prerelease"} $versions = ghcup list -t ghc -r | Where-Object { $_ -notlike "prerelease" }
$VersionsOutput = [Version[]]($Versions | ForEach-Object{ $_.Split(' ')[1]; }) $versionsOutput = [version[]]($versions | ForEach-Object { $_.Split(' ')[1]; })
$LatestMajorMinor = $VersionsOutput | Group-Object { $_.ToString(2) } | Sort-Object { [Version] $_.Name } | Select-Object -last 3 $latestMajorMinor = $versionsOutput | Group-Object { $_.ToString(2) } | Sort-Object { [Version] $_.Name } | Select-Object -last 3
$VersionsList = $LatestMajorMinor | ForEach-Object { $_.Group | Select-Object -Last 1 } | Sort-Object $versionsList = $latestMajorMinor | ForEach-Object { $_.Group | Select-Object -Last 1 } | Sort-Object
# The latest version will be installed as a default # The latest version will be installed as a default
foreach ($version in $VersionsList) { foreach ($version in $versionsList) {
Write-Host "Installing ghc $version..." Write-Host "Installing ghc $version..."
ghcup install ghc $version ghcup install ghc $version
if ($LastExitCode -ne 0) {
throw "GHC installation failed with exit code $LastExitCode"
}
ghcup set ghc $version ghcup set ghc $version
if ($LastExitCode -ne 0) {
throw "Setting GHC version failed with exit code $LastExitCode"
}
} }
# Add default version of GHC to path # Add default version of GHC to path
$DefaultGhcVersion = $VersionsList | Select-Object -Last 1 $defaultGhcVersion = $versionsList | Select-Object -Last 1
ghcup set ghc $DefaultGhcVersion ghcup set ghc $defaultGhcVersion
if ($LastExitCode -ne 0) {
throw "Setting default GHC version failed with exit code $LastExitCode"
}
Write-Host 'Installing cabal...' Write-Host 'Installing cabal...'
ghcup install cabal latest ghcup install cabal latest
if ($LastExitCode -ne 0) {
throw "Cabal installation failed with exit code $LastExitCode"
}
Invoke-PesterTests -TestFile 'Haskell' Invoke-PesterTests -TestFile 'Haskell'

View File

@@ -4,29 +4,29 @@
## Supply chain security: checksum validation ## Supply chain security: checksum validation
################################################################################ ################################################################################
$CondaDestination = "C:\Miniconda" $condaDestination = "C:\Miniconda"
$InstallerName = "Miniconda3-latest-Windows-x86_64.exe" $installerName = "Miniconda3-latest-Windows-x86_64.exe"
#region Supply chain security #region Supply chain security
$distributorFileHash = $null $distributorFileHash = $null
$checksums = (Invoke-RestMethod -Uri 'https://repo.anaconda.com/miniconda/' | ConvertFrom-HTML).SelectNodes('//html/body/table/tr') $checksums = (Invoke-RestMethod -Uri 'https://repo.anaconda.com/miniconda/' | ConvertFrom-HTML).SelectNodes('//html/body/table/tr')
foreach ($node in $checksums) { foreach ($node in $checksums) {
if ($node.ChildNodes[1].InnerText -eq $InstallerName) { if ($node.ChildNodes[1].InnerText -eq $installerName) {
$distributorFileHash = $node.ChildNodes[7].InnerText $distributorFileHash = $node.ChildNodes[7].InnerText
} }
} }
if ($null -eq $distributorFileHash) { if ($null -eq $distributorFileHash) {
throw "Unable to find checksum for $InstallerName in https://repo.anaconda.com/miniconda/" throw "Unable to find checksum for $installerName in https://repo.anaconda.com/miniconda/"
} }
#endregion #endregion
Install-Binary ` Install-Binary `
-Url "https://repo.anaconda.com/miniconda/${InstallerName}" ` -Url "https://repo.anaconda.com/miniconda/${installerName}" `
-InstallArgs @("/S", "/AddToPath=0", "/RegisterPython=0", "/D=$CondaDestination") ` -InstallArgs @("/S", "/AddToPath=0", "/RegisterPython=0", "/D=$condaDestination") `
-ExpectedSHA256Sum $distributorFileHash -ExpectedSHA256Sum $distributorFileHash
[Environment]::SetEnvironmentVariable("CONDA", $CondaDestination, "Machine") [Environment]::SetEnvironmentVariable("CONDA", $condaDestination, "Machine")
Invoke-PesterTests -TestFile "Miniconda" Invoke-PesterTests -TestFile "Miniconda"

View File

@@ -4,26 +4,27 @@
#################################################################################### ####################################################################################
# Install mongodb package # Install mongodb package
$toolsetVersion = (Get-ToolsetContent).mongodb.version $toolsetContent = Get-ToolsetContent
$toolsetVersion = $toolsetContent.mongodb.version
$getMongoReleases = Invoke-WebRequest -Uri "mongodb.com/docs/manual/release-notes/$toolsetVersion/" -UseBasicParsing $getMongoReleases = Invoke-WebRequest -Uri "mongodb.com/docs/manual/release-notes/$toolsetVersion/" -UseBasicParsing
$TargetReleases = $getMongoReleases.Links.href | Where-Object {$_ -like "#$toolsetVersion*---*"} $targetReleases = $getMongoReleases.Links.href | Where-Object { $_ -like "#$toolsetVersion*---*" }
$MinorVersions = @() $minorVersions = @()
foreach ($release in $TargetReleases) { foreach ($release in $targetReleases) {
if ($release -notlike "*upcoming*") { if ($release -notlike "*upcoming*") {
$pattern = '\d+\.\d+\.\d+' $pattern = '\d+\.\d+\.\d+'
$version = $release | Select-String -Pattern $pattern -AllMatches | ForEach-Object { $_.Matches } | ForEach-Object { $_.Value } $version = $release | Select-String -Pattern $pattern -AllMatches | ForEach-Object { $_.Matches } | ForEach-Object { $_.Value }
$MinorVersions += $version $minorVersions += $version
} }
} }
$LatestVersion = $MinorVersions[0] $latestVersion = $minorVersions[0]
Install-Binary ` Install-Binary `
-Url "https://fastdl.mongodb.org/windows/mongodb-windows-x86_64-$LatestVersion-signed.msi" ` -Url "https://fastdl.mongodb.org/windows/mongodb-windows-x86_64-$latestVersion-signed.msi" `
-ExtraInstallArgs @('TARGETDIR=C:\PROGRA~1\MongoDB ADDLOCAL=ALL') ` -ExtraInstallArgs @('TARGETDIR=C:\PROGRA~1\MongoDB ADDLOCAL=ALL') `
-ExpectedSignature (Get-ToolsetContent).mongodb.signature -ExpectedSignature $toolsetContent.mongodb.signature
# Add mongodb to the PATH # Add mongodb to the PATH
$mongoPath = (Get-CimInstance Win32_Service -Filter "Name LIKE 'mongodb'").PathName $mongoPath = (Get-CimInstance Win32_Service -Filter "Name LIKE 'mongodb'").PathName

View File

@@ -7,75 +7,104 @@
# https://github.com/msys2/MINGW-packages/blob/master/azure-pipelines.yml # https://github.com/msys2/MINGW-packages/blob/master/azure-pipelines.yml
# https://packages.msys2.org/group/ # https://packages.msys2.org/group/
$dash = "-" * 40 $logPrefix = "`n" + ("-" * 40) + "`n---"
$origPath = $env:PATH $origPath = $env:PATH
function Install-Msys2 { function Install-Msys2 {
# We can't use Resolve-GithubReleaseAssetUrl function here # We can't use Resolve-GithubReleaseAssetUrl function here
# because msys2-installer releases don't have a consistent versioning scheme # because msys2-installer releases don't have a consistent versioning scheme
$assets = (Invoke-RestMethod -Uri "https://api.github.com/repos/msys2/msys2-installer/releases/latest").assets $assets = (Invoke-RestMethod -Uri "https://api.github.com/repos/msys2/msys2-installer/releases/latest").assets
$downloadUri = ($assets | Where-Object { $_.name -match "^msys2-x86_64" -and $_.name.EndsWith(".exe") }).browser_download_url $downloadUri = ($assets | Where-Object { $_.name -match "^msys2-x86_64" -and $_.name.EndsWith(".exe") }).browser_download_url
$installerName = Split-Path $downloadUri -Leaf $installerName = Split-Path $downloadUri -Leaf
# Download the latest msys2 x86_64, filename includes release date # Download the latest msys2 x86_64, filename includes release date
Write-Host "Download msys2 installer $installerName" Write-Host "Download msys2 installer $installerName"
$installerPath = Invoke-DownloadWithRetry $downloadUri $installerPath = Invoke-DownloadWithRetry $downloadUri
#region Supply chain security - MSYS2 #region Supply chain security - MSYS2
$externalHash = Get-ChecksumFromUrl -Type "SHA256" ` $externalHash = Get-ChecksumFromUrl -Type "SHA256" `
-Url ($downloadUri -replace $installerName, "msys2-checksums.txt") ` -Url ($downloadUri -replace $installerName, "msys2-checksums.txt") `
-FileName $installerName -FileName $installerName
Test-FileChecksum $installerPath -ExpectedSHA256Sum $externalHash Test-FileChecksum $installerPath -ExpectedSHA256Sum $externalHash
#endregion #endregion
Write-Host "Starting msys2 installation" Write-Host "Starting msys2 installation"
& $installerPath in --confirm-command --accept-messages --root C:/msys64 & $installerPath in --confirm-command --accept-messages --root C:/msys64
Remove-Item $installerPath if ($LastExitCode -ne 0) {
throw "MSYS2 installation failed with exit code $LastExitCode"
}
Remove-Item $installerPath
} }
function Install-Msys2Packages($Packages) { function Install-Msys2Packages {
if (-not $Packages) { param (
return [Parameter(Mandatory = $true)]
} [AllowEmptyCollection()]
[string[]]$Packages
)
Write-Host "`n$dash Install msys2 packages" if (-not $Packages) {
pacman.exe -S --noconfirm --needed --noprogressbar $Packages return
taskkill /f /fi "MODULES eq msys-2.0.dll" }
Write-Host "`n$dash Remove p7zip/7z package due to conflicts" Write-Host "$logPrefix Install msys2 packages"
pacman.exe -R --noconfirm --noprogressbar p7zip pacman.exe -S --noconfirm --needed --noprogressbar $Packages
if ($LastExitCode -ne 0) {
throw "MSYS2 packages installation failed with exit code $LastExitCode"
}
taskkill /f /fi "MODULES eq msys-2.0.dll"
Write-Host "$logPrefix Remove p7zip/7z package due to conflicts"
pacman.exe -R --noconfirm --noprogressbar p7zip
if ($LastExitCode -ne 0) {
throw "Removal of p7zip/7z package failed with exit code $LastExitCode"
}
} }
function Install-MingwPackages($Packages) { function Install-MingwPackages {
if (-not $Packages) { param (
return [Parameter(Mandatory = $true)]
} [AllowEmptyCollection()]
[object[]] $Packages
)
Write-Host "`n$dash Install mingw packages" if (-not $Packages) {
$archs = $Packages.arch return
}
foreach ($arch in $archs) { Write-Host "$logPrefix Install mingw packages"
Write-Host "Installing $arch packages" $archs = $Packages.arch
$archPackages = $toolsetContent.mingw | Where-Object { $_.arch -eq $arch }
$runtimePackages = $archPackages.runtime_packages.name | ForEach-Object { "${arch}-$_" }
$additionalPackages = $archPackages.additional_packages | ForEach-Object { "${arch}-$_" }
$packagesToInstall = $runtimePackages + $additionalPackages
Write-Host "The following packages will be installed: $packagesToInstall"
pacman.exe -S --noconfirm --needed --noprogressbar $packagesToInstall
}
# clean all packages to decrease image size foreach ($arch in $archs) {
Write-Host "`n$dash Clean packages" Write-Host "Installing $arch packages"
pacman.exe -Scc --noconfirm $archPackages = $toolsetContent.mingw | Where-Object { $_.arch -eq $arch }
$runtimePackages = $archPackages.runtime_packages.name | ForEach-Object { "${arch}-$_" }
$additionalPackages = $archPackages.additional_packages | ForEach-Object { "${arch}-$_" }
$packagesToInstall = $runtimePackages + $additionalPackages
Write-Host "The following packages will be installed: $packagesToInstall"
pacman.exe -S --noconfirm --needed --noprogressbar $packagesToInstall
if ($LastExitCode -ne 0) {
throw "Installation of $arch packages failed with exit code $LastExitCode"
}
}
$pkgs = pacman.exe -Q # clean all packages to decrease image size
Write-Host "$logPrefix Clean packages"
pacman.exe -Scc --noconfirm
if ($LastExitCode -ne 0) {
throw "Cleaning of packages failed with exit code $LastExitCode"
}
foreach ($arch in $archs) $pkgs = pacman.exe -Q
{ if ($LastExitCode -ne 0) {
Write-Host "`n$dash Installed $arch packages" throw "Listing of packages failed with exit code $LastExitCode"
$pkgs | grep ^${arch}- }
}
foreach ($arch in $archs) {
Write-Host "$logPrefix Installed $arch packages"
$pkgs | Select-String -Pattern "^${arch}-"
}
} }
Install-Msys2 Install-Msys2
@@ -83,11 +112,18 @@ Install-Msys2
# Add msys2 bin tools folders to PATH temporary # Add msys2 bin tools folders to PATH temporary
$env:PATH = "C:\msys64\mingw64\bin;C:\msys64\usr\bin;$origPath" $env:PATH = "C:\msys64\mingw64\bin;C:\msys64\usr\bin;$origPath"
Write-Host "`n$dash pacman --noconfirm -Syyuu" Write-Host "$logPrefix pacman --noconfirm -Syyuu"
pacman.exe -Syyuu --noconfirm pacman.exe -Syyuu --noconfirm
if ($LastExitCode -ne 0) {
throw "Updating of packages failed with exit code $LastExitCode"
}
taskkill /f /fi "MODULES eq msys-2.0.dll" taskkill /f /fi "MODULES eq msys-2.0.dll"
Write-Host "`n$dash pacman --noconfirm -Syuu (2nd pass)"
pacman.exe -Syuu --noconfirm Write-Host "$logPrefix pacman --noconfirm -Syuu (2nd pass)"
pacman.exe -Syuu --noconfirm
if ($LastExitCode -ne 0) {
throw "Second pass updating of packages failed with exit code $LastExitCode"
}
taskkill /f /fi "MODULES eq msys-2.0.dll" taskkill /f /fi "MODULES eq msys-2.0.dll"
$toolsetContent = (Get-ToolsetContent).MsysPackages $toolsetContent = (Get-ToolsetContent).MsysPackages

View File

@@ -3,33 +3,33 @@
## Desc: Install Mysql CLI ## Desc: Install Mysql CLI
################################################################################ ################################################################################
# Installing visual c++ redistibutable package. # Installing visual c++ redistributable package.
Install-Binary ` Install-Binary `
-Url 'https://download.microsoft.com/download/0/5/6/056dcda9-d667-4e27-8001-8a0c6971d6b1/vcredist_x64.exe' ` -Url 'https://download.microsoft.com/download/0/5/6/056dcda9-d667-4e27-8001-8a0c6971d6b1/vcredist_x64.exe' `
-InstallArgs @("/install", "/quiet", "/norestart") ` -InstallArgs @("/install", "/quiet", "/norestart") `
-ExpectedSignature '3BDA323E552DB1FDE5F4FBEE75D6D5B2B187EEDC' -ExpectedSignature '3BDA323E552DB1FDE5F4FBEE75D6D5B2B187EEDC'
# Downloading mysql # Downloading mysql
[version] $MysqlVersion = (Get-ToolsetContent).mysql.version [version] $mysqlVersion = (Get-ToolsetContent).mysql.version
$MysqlVersionMajorMinor = $MysqlVersion.ToString(2) $mysqlVersionMajorMinor = $mysqlVersion.ToString(2)
if ($MysqlVersion.Build -lt 0) { if ($mysqlVersion.Build -lt 0) {
$downloadsPageUrl = "https://dev.mysql.com/downloads/mysql/${MysqlVersionMajorMinor}.html" $downloadsPageUrl = "https://dev.mysql.com/downloads/mysql/${mysqlVersionMajorMinor}.html"
$MysqlVersion = Invoke-RestMethod -Uri $downloadsPageUrl -Headers @{ 'User-Agent' = 'curl/8.4.0' } ` $mysqlVersion = Invoke-RestMethod -Uri $downloadsPageUrl -Headers @{ 'User-Agent' = 'curl/8.4.0' } `
| Select-String -Pattern "${MysqlVersionMajorMinor}\.\d+" ` | Select-String -Pattern "${mysqlVersionMajorMinor}\.\d+" `
| ForEach-Object { $_.Matches.Value } | ForEach-Object { $_.Matches.Value }
} }
$MysqlVersionFull = $MysqlVersion.ToString() $mysqlVersionFull = $mysqlVersion.ToString()
$MysqlVersionUrl = "https://cdn.mysql.com/Downloads/MySQL-${MysqlVersionMajorMinor}/mysql-${MysqlVersionFull}-winx64.msi" $mysqlVersionUrl = "https://cdn.mysql.com/Downloads/MySQL-${mysqlVersionMajorMinor}/mysql-${mysqlVersionFull}-winx64.msi"
Install-Binary ` Install-Binary `
-Url $MysqlVersionUrl ` -Url $mysqlVersionUrl `
-ExpectedSignature (Get-ToolsetContent).mysql.signature -ExpectedSignature (Get-ToolsetContent).mysql.signature
# Adding mysql in system environment path # Adding mysql in system environment path
$MysqlPath = $(Get-ChildItem -Path "C:\PROGRA~1\MySQL" -Directory)[0].FullName $mysqlPath = $(Get-ChildItem -Path "C:\PROGRA~1\MySQL" -Directory)[0].FullName
Add-MachinePathItem "${MysqlPath}\bin" Add-MachinePathItem "${mysqlPath}\bin"
Invoke-PesterTests -TestFile "Databases" -TestName "MySQL" Invoke-PesterTests -TestFile "Databases" -TestName "MySQL"

View File

@@ -5,8 +5,8 @@
# .NET 4.8 Dev pack # .NET 4.8 Dev pack
Install-Binary ` Install-Binary `
-Url 'https://download.visualstudio.microsoft.com/download/pr/014120d7-d689-4305-befd-3cb711108212/0307177e14752e359fde5423ab583e43/ndp48-devpack-enu.exe' ` -Url 'https://download.visualstudio.microsoft.com/download/pr/014120d7-d689-4305-befd-3cb711108212/0307177e14752e359fde5423ab583e43/ndp48-devpack-enu.exe' `
-InstallArgs @("Setup", "/passive", "/norestart") ` -InstallArgs @("Setup", "/passive", "/norestart") `
-ExpectedSignature 'C82273A065EC470FB1EBDE846A91E6FFB29E9C12' -ExpectedSignature 'C82273A065EC470FB1EBDE846A91E6FFB29E9C12'
Invoke-PesterTests -TestFile "Tools" -TestName "NET48" Invoke-PesterTests -TestFile "Tools" -TestName "NET48"

View File

@@ -5,6 +5,6 @@
# .NET 4.8 Dev pack # .NET 4.8 Dev pack
Install-Binary ` Install-Binary `
-Url 'https://download.visualstudio.microsoft.com/download/pr/2d6bb6b2-226a-4baa-bdec-798822606ff1/8494001c276a4b96804cde7829c04d7f/ndp48-x86-x64-allos-enu.exe' ` -Url 'https://download.visualstudio.microsoft.com/download/pr/2d6bb6b2-226a-4baa-bdec-798822606ff1/8494001c276a4b96804cde7829c04d7f/ndp48-x86-x64-allos-enu.exe' `
-InstallArgs @("Setup", "/passive", "/norestart") ` -InstallArgs @("Setup", "/passive", "/norestart") `
-ExpectedSignature 'ABDCA79AF9DD48A0EA702AD45260B3C03093FB4B' -ExpectedSignature 'ABDCA79AF9DD48A0EA702AD45260B3C03093FB4B'

View File

@@ -4,9 +4,9 @@
## Supply chain security: NSIS - managed by package manager ## Supply chain security: NSIS - managed by package manager
################################################################################ ################################################################################
$NsisVersion = (Get-ToolsetContent).nsis.version $nsisVersion = (Get-ToolsetContent).nsis.version
Install-ChocoPackage nsis -ArgumentList "--version", "$NsisVersion" Install-ChocoPackage nsis -ArgumentList "--version", "$nsisVersion"
Add-MachinePathItem "${env:ProgramFiles(x86)}\NSIS\" Add-MachinePathItem "${env:ProgramFiles(x86)}\NSIS\"
Update-Environment Update-Environment

View File

@@ -3,9 +3,20 @@
## Desc: Generate and install native images for .NET assemblies ## Desc: Generate and install native images for .NET assemblies
################################################################################ ################################################################################
Write-Host "NGen: Microsoft.PowerShell.Utility.Activities" Write-Host "NGen: install Microsoft.PowerShell.Utility.Activities..."
$null = & $env:SystemRoot\Microsoft.NET\Framework64\v4.0.30319\ngen.exe install "Microsoft.PowerShell.Utility.Activities, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" & $env:SystemRoot\Microsoft.NET\Framework64\v4.0.30319\ngen.exe install "Microsoft.PowerShell.Utility.Activities, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" | Out-Null
Write-Host "NGen: Framework64" if ($LASTEXITCODE -ne 0) {
$null = & $env:SystemRoot\Microsoft.NET\Framework64\v4.0.30319\ngen.exe update throw "Installation of Microsoft.PowerShell.Utility.Activities failed with exit code $LASTEXITCODE"
Write-Host "NGen: Framework" }
$null = & $env:SystemRoot\Microsoft.NET\Framework\v4.0.30319\ngen.exe update
Write-Host "NGen: update x64 native images..."
& $env:SystemRoot\Microsoft.NET\Framework64\v4.0.30319\ngen.exe update | Out-Null
if ($LASTEXITCODE -ne 0) {
throw "Update of x64 native images failed with exit code $LASTEXITCODE"
}
Write-Host "NGen: update x86 native images..."
& $env:SystemRoot\Microsoft.NET\Framework\v4.0.30319\ngen.exe update | Out-Null
if ($LASTEXITCODE -ne 0) {
throw "Update of x86 native images failed with exit code $LASTEXITCODE"
}

View File

@@ -4,24 +4,24 @@
## Must run after python is configured ## Must run after python is configured
################################################################################ ################################################################################
$PrefixPath = 'C:\npm\prefix' $prefixPath = 'C:\npm\prefix'
$CachePath = 'C:\npm\cache' $cachePath = 'C:\npm\cache'
New-Item -Path $PrefixPath -Force -ItemType Directory New-Item -Path $prefixPath -Force -ItemType Directory
New-Item -Path $CachePath -Force -ItemType Directory New-Item -Path $cachePath -Force -ItemType Directory
$defaultVersion = (Get-ToolsetContent).node.default $defaultVersion = (Get-ToolsetContent).node.default
$versionToInstall = Resolve-ChocoPackageVersion -PackageName "nodejs" -TargetVersion $defaultVersion $versionToInstall = Resolve-ChocoPackageVersion -PackageName "nodejs" -TargetVersion $defaultVersion
Install-ChocoPackage nodejs -ArgumentList "--version=$versionToInstall" Install-ChocoPackage "nodejs" -ArgumentList "--version=$versionToInstall"
Add-MachinePathItem $PrefixPath Add-MachinePathItem $prefixPath
Update-Environment Update-Environment
[Environment]::SetEnvironmentVariable("npm_config_prefix", $PrefixPath, "Machine") [Environment]::SetEnvironmentVariable("npm_config_prefix", $prefixPath, "Machine")
$env:npm_config_prefix = $PrefixPath $env:npm_config_prefix = $prefixPath
npm config set cache $CachePath --global npm config set cache $cachePath --global
npm config set registry https://registry.npmjs.org/ npm config set registry https://registry.npmjs.org/
$globalNpmPackages = (Get-ToolsetContent).npm.global_packages $globalNpmPackages = (Get-ToolsetContent).npm.global_packages

View File

@@ -9,7 +9,7 @@ $bits = '64'
$light = $false $light = $false
$installerType = "exe" $installerType = "exe"
$version = (Get-ToolsetContent).openssl.version $version = (Get-ToolsetContent).openssl.version
$installDir = "$Env:ProgramFiles\OpenSSL" $installDir = "$env:ProgramFiles\OpenSSL"
# Fetch available installers list # Fetch available installers list
$jsonUrl = 'https://raw.githubusercontent.com/slproweb/opensslhashes/master/win32_openssl_hashes.json' $jsonUrl = 'https://raw.githubusercontent.com/slproweb/opensslhashes/master/win32_openssl_hashes.json'

View File

@@ -8,6 +8,9 @@ $env:PIPX_BIN_DIR = "${env:ProgramFiles(x86)}\pipx_bin"
$env:PIPX_HOME = "${env:ProgramFiles(x86)}\pipx" $env:PIPX_HOME = "${env:ProgramFiles(x86)}\pipx"
pip install pipx pip install pipx
if ($LASTEXITCODE -ne 0) {
throw "pipx installation failed with exit code $LASTEXITCODE"
}
Add-MachinePathItem "${env:PIPX_BIN_DIR}" Add-MachinePathItem "${env:PIPX_BIN_DIR}"
[Environment]::SetEnvironmentVariable("PIPX_BIN_DIR", $env:PIPX_BIN_DIR, "Machine") [Environment]::SetEnvironmentVariable("PIPX_BIN_DIR", $env:PIPX_BIN_DIR, "Machine")
@@ -19,14 +22,18 @@ Write-Host "Installing pipx packages..."
$pipxToolset = (Get-ToolsetContent).pipx $pipxToolset = (Get-ToolsetContent).pipx
foreach ($tool in $pipxToolset) { foreach ($tool in $pipxToolset) {
if ($tool.python) { if ($tool.python) {
$pythonPath = (Get-Item -Path "${env:AGENT_TOOLSDIRECTORY}\Python\${tool.python}.*\x64\python-${tool.python}*").FullName $pythonPath = (Get-Item -Path "${env:AGENT_TOOLSDIRECTORY}\Python\${tool.python}.*\x64\python-${tool.python}*").FullName
Write-Host "Install ${tool.package} into python ${tool.python}" Write-Host "Install ${tool.package} into python ${tool.python}"
pipx install $tool.package --python $pythonPath pipx install $tool.package --python $pythonPath
} else { } else {
Write-Host "Install ${tool.package} into default python" Write-Host "Install ${tool.package} into default python"
pipx install $tool.package pipx install $tool.package
} }
if ($LASTEXITCODE -ne 0) {
throw "Package ${tool.package} installation failed with exit code $LASTEXITCODE"
}
} }
Invoke-PesterTests -TestFile "PipxPackages" Invoke-PesterTests -TestFile "PipxPackages"

View File

@@ -1,3 +1,8 @@
################################################################################
## File: Install-PostgreSQL.ps1
## Desc: Install PostgreSQL
################################################################################
# Define user and password for PostgreSQL database # Define user and password for PostgreSQL database
$pgUser = "postgres" $pgUser = "postgres"
$pgPwd = "root" $pgPwd = "root"
@@ -10,47 +15,47 @@ $pgPwd = "root"
$toolsetVersion = (Get-ToolsetContent).postgresql.version $toolsetVersion = (Get-ToolsetContent).postgresql.version
$getPostgreReleases = Invoke-WebRequest -Uri "https://git.postgresql.org/gitweb/?p=postgresql.git;a=tags" -UseBasicParsing $getPostgreReleases = Invoke-WebRequest -Uri "https://git.postgresql.org/gitweb/?p=postgresql.git;a=tags" -UseBasicParsing
# Getting all links matched to the pattern (e.g.a=log;h=refs/tags/REL_14) # Getting all links matched to the pattern (e.g.a=log;h=refs/tags/REL_14)
$TargetReleases = $getPostgreReleases.Links.href | Where-Object { $_ -match "a=log;h=refs/tags/REL_$toolsetVersion" } $targetReleases = $getPostgreReleases.Links.href | Where-Object { $_ -match "a=log;h=refs/tags/REL_$toolsetVersion" }
[Int32] $OutNumber = $null [Int32] $outNumber = $null
$MinorVersions = @() $minorVersions = @()
foreach ($release in $TargetReleases) { foreach ($release in $targetReleases) {
$version = $release.split('/')[-1] $version = $release.split('/')[-1]
# Checking if the latest symbol of the release version is actually a number. If yes, add to $MinorVersions array # Checking if the latest symbol of the release version is actually a number. If yes, add to $minorVersions array
if ([Int32]::TryParse($($version.Split('_')[-1]), [ref] $OutNumber)) { if ([Int32]::TryParse($($version.Split('_')[-1]), [ref] $outNumber)) {
$MinorVersions += $OutNumber $minorVersions += $outNumber
} }
} }
# Sorting and getting the last one # Sorting and getting the last one
$TargetMinorVersions = ($MinorVersions | Sort-Object)[-1] $targetMinorVersions = ($minorVersions | Sort-Object)[-1]
# Install latest PostgreSQL # Install latest PostgreSQL
# In order to get rid of error messages (we know we will have them), force ErrorAction to SilentlyContinue # In order to get rid of error messages (we know we will have them), force ErrorAction to SilentlyContinue
$ErrorActionOldValue = $ErrorActionPreference $errorActionOldValue = $ErrorActionPreference
$ErrorActionPreference = 'SilentlyContinue' $ErrorActionPreference = 'SilentlyContinue'
# Starting from number 9 and going down, check if the installer is available. If yes, break the loop. # Starting from number 9 and going down, check if the installer is available. If yes, break the loop.
# If an installer with $TargetMinorVersions is not to be found, the $TargetMinorVersions will be decreased by 1 # If an installer with $targetMinorVersions is not to be found, the $targetMinorVersions will be decreased by 1
$increment = 9 $increment = 9
do { do {
$url = "https://get.enterprisedb.com/postgresql/postgresql-$toolsetVersion.$TargetMinorVersions-$increment-windows-x64.exe" $url = "https://get.enterprisedb.com/postgresql/postgresql-$toolsetVersion.$targetMinorVersions-$increment-windows-x64.exe"
$checkaccess = [System.Net.WebRequest]::Create($url) $checkAccess = [System.Net.WebRequest]::Create($url)
$response = $null $response = $null
$response = $checkaccess.GetResponse() $response = $checkAccess.GetResponse()
if ($response) { if ($response) {
$InstallerUrl = $response.ResponseUri.OriginalString $installerUrl = $response.ResponseUri.OriginalString
} elseif (!$response -and ($increment -eq 0)) { } elseif (!$response -and ($increment -eq 0)) {
$increment = 9 $increment = 9
$TargetMinorVersions-- $targetMinorVersions--
} else { } else {
$increment-- $increment--
} }
} while (!$response) } while (!$response)
# Return the previous value of ErrorAction and invoke Install-Binary function # Return the previous value of ErrorAction and invoke Install-Binary function
$ErrorActionPreference = $ErrorActionOldValue $ErrorActionPreference = $errorActionOldValue
$InstallerArgs = @("--install_runtimes 0", "--superpassword root", "--enable_acledit 1", "--unattendedmodeui none", "--mode unattended") $installerArgs = @("--install_runtimes 0", "--superpassword root", "--enable_acledit 1", "--unattendedmodeui none", "--mode unattended")
Install-Binary ` Install-Binary `
-Url $InstallerUrl ` -Url $installerUrl `
-InstallArgs $InstallerArgs ` -InstallArgs $installerArgs `
-ExpectedSignature (Get-ToolsetContent).postgresql.signature -ExpectedSignature (Get-ToolsetContent).postgresql.signature
# Get Path to pg_ctl.exe # Get Path to pg_ctl.exe

View File

@@ -8,7 +8,7 @@
$installPSModulePath = "C:\\Modules" $installPSModulePath = "C:\\Modules"
if (-not (Test-Path -LiteralPath $installPSModulePath)) { if (-not (Test-Path -LiteralPath $installPSModulePath)) {
Write-Host "Creating ${installPSModulePath} folder to store PowerShell Azure modules..." Write-Host "Creating ${installPSModulePath} folder to store PowerShell Azure modules..."
$null = New-Item -Path $installPSModulePath -ItemType Directory New-Item -Path $installPSModulePath -ItemType Directory | Out-Null
} }
# Get modules content from toolset # Get modules content from toolset

View File

@@ -7,7 +7,7 @@
$ErrorActionPreference = "Stop" $ErrorActionPreference = "Stop"
$tempDir = Join-Path ([System.IO.Path]::GetTempPath()) ([System.IO.Path]::GetRandomFileName()) $tempDir = Join-Path ([System.IO.Path]::GetTempPath()) ([System.IO.Path]::GetRandomFileName())
$null = New-Item -ItemType Directory -Path $tempDir -Force -ErrorAction SilentlyContinue New-Item -ItemType Directory -Path $tempDir -Force -ErrorAction SilentlyContinue | Out-Null
try { try {
$originalValue = [Net.ServicePointManager]::SecurityProtocol $originalValue = [Net.ServicePointManager]::SecurityProtocol
[Net.ServicePointManager]::SecurityProtocol = [Net.ServicePointManager]::SecurityProtocol -bor [Net.SecurityProtocolType]::Tls12 [Net.ServicePointManager]::SecurityProtocol = [Net.ServicePointManager]::SecurityProtocol -bor [Net.SecurityProtocolType]::Tls12

View File

@@ -4,8 +4,7 @@
## Supply chain security: checksum validation ## Supply chain security: checksum validation
################################################################################ ################################################################################
function Install-PyPy function Install-PyPy {
{
param( param(
[String] $PackagePath, [String] $PackagePath,
[String] $Architecture [String] $Architecture
@@ -31,8 +30,7 @@ function Install-PyPy
Write-Host "Put '$pypyFullVersion' to PYPY_VERSION file" Write-Host "Put '$pypyFullVersion' to PYPY_VERSION file"
New-Item -Path "$tempFolder\PYPY_VERSION" -Value $pypyFullVersion | Out-Null New-Item -Path "$tempFolder\PYPY_VERSION" -Value $pypyFullVersion | Out-Null
if ($pythonVersion) if ($pythonVersion) {
{
Write-Host "Installing PyPy $pythonVersion" Write-Host "Installing PyPy $pythonVersion"
$pypyVersionPath = Join-Path -Path $pypyToolcachePath -ChildPath $pythonVersion $pypyVersionPath = Join-Path -Path $pypyToolcachePath -ChildPath $pythonVersion
$pypyArchPath = Join-Path -Path $pypyVersionPath -ChildPath $architecture $pypyArchPath = Join-Path -Path $pypyVersionPath -ChildPath $architecture
@@ -55,25 +53,19 @@ function Install-PyPy
# Create pip.exe if missing # Create pip.exe if missing
$pipPath = Join-Path -Path $pypyArchPath -ChildPath "Scripts/pip.exe" $pipPath = Join-Path -Path $pypyArchPath -ChildPath "Scripts/pip.exe"
if (-not (Test-Path $pipPath)) if (-not (Test-Path $pipPath)) {
{
$pip3Path = Join-Path -Path $pypyArchPath -ChildPath "Scripts/pip3.exe" $pip3Path = Join-Path -Path $pypyArchPath -ChildPath "Scripts/pip3.exe"
Copy-Item -Path $pip3Path -Destination $pipPath Copy-Item -Path $pip3Path -Destination $pipPath
} }
if ($LASTEXITCODE -ne 0) if ($LASTEXITCODE -ne 0) {
{ throw "PyPy installation failed with exit code $LASTEXITCODE"
Throw "Error happened during PyPy installation"
exit 1
} }
Write-Host "Create complete file" Write-Host "Create complete file"
New-Item -ItemType File -Path $pypyVersionPath -Name "$architecture.complete" | Out-Null New-Item -ItemType File -Path $pypyVersionPath -Name "$architecture.complete" | Out-Null
} } else {
else throw "PyPy application is not found. Failed to expand '$packagePath' archive"
{
Write-Host "PyPy application is not found. Failed to expand '$packagePath' archive"
exit 1
} }
} }
@@ -86,36 +78,31 @@ $pypyVersions = Invoke-RestMethod https://downloads.python.org/pypy/versions.jso
# required for html parsing # required for html parsing
$checksums = (Invoke-RestMethod -Uri 'https://www.pypy.org/checksums.html' | ConvertFrom-HTML).SelectNodes('//*[@id="content"]/article/div/pre') $checksums = (Invoke-RestMethod -Uri 'https://www.pypy.org/checksums.html' | ConvertFrom-HTML).SelectNodes('//*[@id="content"]/article/div/pre')
Write-Host "Starting installation PyPy..." Write-Host "Start PyPy installation"
foreach($toolsetVersion in $toolsetVersions.versions) foreach ($toolsetVersion in $toolsetVersions.versions) {
{
# Query latest PyPy version # Query latest PyPy version
$latestMajorPyPyVersion = $pypyVersions | $latestMajorPyPyVersion = $pypyVersions |
Where-Object {$_.python_version.StartsWith("$toolsetVersion") -and $_.stable -eq $true} | Where-Object { $_.python_version.StartsWith("$toolsetVersion") -and $_.stable -eq $true } |
Select-Object -ExpandProperty files -First 1 | Select-Object -ExpandProperty files -First 1 |
Where-Object platform -like "win*" Where-Object platform -like "win*"
if ($latestMajorPyPyVersion) if (-not $latestMajorPyPyVersion) {
{ throw "Failed to query PyPy version '$toolsetVersion'"
$filename = $latestMajorPyPyVersion.filename }
Write-Host "Found PyPy '$filename' package"
$tempPyPyPackagePath = Invoke-DownloadWithRetry $latestMajorPyPyVersion.download_url
#region Supply chain security $filename = $latestMajorPyPyVersion.filename
$distributorFileHash = $null Write-Host "Found PyPy '$filename' package"
foreach ($node in $checksums) { $tempPyPyPackagePath = Invoke-DownloadWithRetry $latestMajorPyPyVersion.download_url
if ($node.InnerText -ilike "*${filename}*") {
$distributorFileHash = $node.InnerText.ToString().Split("`n").Where({ $_ -ilike "*${filename}*" }).Split(' ')[0] #region Supply chain security
} $distributorFileHash = $null
foreach ($node in $checksums) {
if ($node.InnerText -ilike "*${filename}*") {
$distributorFileHash = $node.InnerText.ToString().Split("`n").Where({ $_ -ilike "*${filename}*" }).Split(' ')[0]
} }
Test-FileChecksum $tempPyPyPackagePath -ExpectedSHA256Sum $distributorFileHash }
#endregion Test-FileChecksum $tempPyPyPackagePath -ExpectedSHA256Sum $distributorFileHash
#endregion
Install-PyPy -PackagePath $tempPyPyPackagePath -Architecture $toolsetVersions.arch Install-PyPy -PackagePath $tempPyPyPackagePath -Architecture $toolsetVersions.arch
}
else
{
Write-Host "Failed to query PyPy version '$toolsetVersion'"
exit 1
}
} }

View File

@@ -1,3 +1,8 @@
################################################################################
## File: Install-RootCA.ps1
## Desc: Install Root CA certificates
################################################################################
# https://www.sysadmins.lv/blog-en/how-to-retrieve-certificate-purposes-property-with-cryptoapi-and-powershell.aspx # https://www.sysadmins.lv/blog-en/how-to-retrieve-certificate-purposes-property-with-cryptoapi-and-powershell.aspx
# https://www.sysadmins.lv/blog-en/dump-authroot-and-disallowed-certificates-with-powershell.aspx # https://www.sysadmins.lv/blog-en/dump-authroot-and-disallowed-certificates-with-powershell.aspx
# https://www.sysadmins.lv/blog-en/constraining-extended-key-usages-in-microsoft-windows.aspx # https://www.sysadmins.lv/blog-en/constraining-extended-key-usages-in-microsoft-windows.aspx
@@ -26,7 +31,7 @@ function Add-ExtendedCertType {
function Get-CertificatesWithoutPropId { function Get-CertificatesWithoutPropId {
# List installed certificates # List installed certificates
$certs = Get-ChildItem -Path Cert:\LocalMachine\Root $certs = Get-ChildItem -Path "Cert:\LocalMachine\Root"
Write-Host "Certificates without CERT_NOT_BEFORE_FILETIME_PROP_ID property" Write-Host "Certificates without CERT_NOT_BEFORE_FILETIME_PROP_ID property"
$certsWithoutPropId = @{} $certsWithoutPropId = @{}
@@ -65,12 +70,7 @@ function Import-SSTFromWU {
exit $LASTEXITCODE exit $LASTEXITCODE
} }
try { Import-Certificate -FilePath $sstFile -CertStoreLocation Cert:\LocalMachine\Root
Import-Certificate -FilePath $sstFile -CertStoreLocation Cert:\LocalMachine\Root
} catch {
Write-Host "[Error]: failed to import ROOT CA`n$_"
exit 1
}
} }
function Clear-CertificatesPropId { function Clear-CertificatesPropId {

View File

@@ -19,6 +19,9 @@ Test-FileChecksum $rustupPath -ExpectedSHA256Sum $distributorFileHash
# Install Rust by running rustup-init.exe (disabling the confirmation prompt with -y) # Install Rust by running rustup-init.exe (disabling the confirmation prompt with -y)
& $rustupPath -y --default-toolchain=stable --profile=minimal & $rustupPath -y --default-toolchain=stable --profile=minimal
if ($LASTEXITCODE -ne 0) {
throw "Rust installation failed with exit code $LASTEXITCODE"
}
# Add %USERPROFILE%\.cargo\bin to USER PATH # Add %USERPROFILE%\.cargo\bin to USER PATH
Add-DefaultPathItem "%USERPROFILE%\.cargo\bin" Add-DefaultPathItem "%USERPROFILE%\.cargo\bin"
@@ -33,7 +36,14 @@ rustup target add x86_64-pc-windows-gnu
# Install common tools # Install common tools
rustup component add rustfmt clippy rustup component add rustfmt clippy
if ($LASTEXITCODE -ne 0) {
throw "Rust component installation failed with exit code $LASTEXITCODE"
}
cargo install --locked bindgen-cli cbindgen cargo-audit cargo-outdated cargo install --locked bindgen-cli cbindgen cargo-audit cargo-outdated
if ($LASTEXITCODE -ne 0) {
throw "Rust tools installation failed with exit code $LASTEXITCODE"
}
# Cleanup Cargo crates cache # Cleanup Cargo crates cache
Remove-Item "${env:CARGO_HOME}\registry\*" -Recurse -Force Remove-Item "${env:CARGO_HOME}\registry\*" -Recurse -Force

View File

@@ -14,22 +14,22 @@ $downloadUrl = Resolve-GithubReleaseAssetUrl `
-UrlMatchPattern "stack-*-windows-x86_64.zip" -UrlMatchPattern "stack-*-windows-x86_64.zip"
Write-Host "Download stack archive" Write-Host "Download stack archive"
$StackToolcachePath = Join-Path $Env:AGENT_TOOLSDIRECTORY "stack\$version" $stackToolcachePath = Join-Path $env:AGENT_TOOLSDIRECTORY "stack\$version"
$DestinationPath = Join-Path $StackToolcachePath "x64" $destinationPath = Join-Path $stackToolcachePath "x64"
$StackArchivePath = Invoke-DownloadWithRetry $downloadUrl $stackArchivePath = Invoke-DownloadWithRetry $downloadUrl
#region Supply chain security - Stack #region Supply chain security - Stack
$externalHash = Get-ChecksumFromUrl -Type "SHA256" ` $externalHash = Get-ChecksumFromUrl -Type "SHA256" `
-Url "$downloadUrl.sha256" ` -Url "$downloadUrl.sha256" `
-FileName (Split-Path $downloadUrl -Leaf) -FileName (Split-Path $downloadUrl -Leaf)
Test-FileChecksum $StackArchivePath -ExpectedSHA256Sum $externalHash Test-FileChecksum $stackArchivePath -ExpectedSHA256Sum $externalHash
#endregion #endregion
Write-Host "Expand stack archive" Write-Host "Expand stack archive"
Expand-7ZipArchive -Path $StackArchivePath -DestinationPath $DestinationPath Expand-7ZipArchive -Path $stackArchivePath -DestinationPath $destinationPath
New-Item -Name "x64.complete" -Path $StackToolcachePath New-Item -Name "x64.complete" -Path $stackToolcachePath
Add-MachinePathItem -PathItem $DestinationPath Add-MachinePathItem -PathItem $destinationPath
Invoke-PesterTests -TestFile "Tools" -TestName "Stack" Invoke-PesterTests -TestFile "Tools" -TestName "Stack"

View File

@@ -32,9 +32,8 @@ Function Install-Asset {
} }
# Get toolcache content from toolset # Get toolcache content from toolset
$ToolsToInstall = @("Python", "Node", "Go") $toolsToInstall = @("Python", "Node", "Go")
$tools = Get-ToolsetContent | Select-Object -ExpandProperty toolcache | Where-Object { $toolsToInstall -contains $_.Name }
$tools = Get-ToolsetContent | Select-Object -ExpandProperty toolcache | Where-Object { $ToolsToInstall -contains $_.Name }
foreach ($tool in $tools) { foreach ($tool in $tools) {
# Get versions manifest for current tool # Get versions manifest for current tool

View File

@@ -11,7 +11,13 @@ git clone $Uri $InstallDir -q
# Build and integrate vcpkg # Build and integrate vcpkg
Invoke-Expression "$InstallDir\bootstrap-vcpkg.bat" Invoke-Expression "$InstallDir\bootstrap-vcpkg.bat"
if ($LASTEXITCODE -ne 0) {
throw "vcpkg bootstrap failed with exit code $LASTEXITCODE"
}
Invoke-Expression "$InstallDir\$VcpkgExecPath integrate install" Invoke-Expression "$InstallDir\$VcpkgExecPath integrate install"
if ($LASTEXITCODE -ne 0) {
throw "vcpkg integration failed with exit code $LASTEXITCODE"
}
# Add vcpkg to system environment # Add vcpkg to system environment
Add-MachinePathItem $InstallDir Add-MachinePathItem $InstallDir

View File

@@ -13,12 +13,12 @@ foreach ($feature in $windowsFeatures) {
$resultSuccess = $? $resultSuccess = $?
} else { } else {
Write-Host "Activating Windows Feature '$($feature.name)'..." Write-Host "Activating Windows Feature '$($feature.name)'..."
$Arguments = @{ $arguments = @{
Name = $feature.name Name = $feature.name
IncludeAllSubFeature = [System.Convert]::ToBoolean($feature.includeAllSubFeatures) IncludeAllSubFeature = [System.Convert]::ToBoolean($feature.includeAllSubFeatures)
IncludeManagementTools = [System.Convert]::ToBoolean($feature.includeManagementTools) IncludeManagementTools = [System.Convert]::ToBoolean($feature.includeManagementTools)
} }
$result = Install-WindowsFeature @Arguments $result = Install-WindowsFeature @arguments
$resultSuccess = $result.Success $resultSuccess = $result.Success
} }
@@ -33,3 +33,6 @@ foreach ($feature in $windowsFeatures) {
# it improves Android emulator launch on Windows Server # it improves Android emulator launch on Windows Server
# https://learn.microsoft.com/en-us/windows-server/virtualization/hyper-v/manage/manage-hyper-v-scheduler-types # https://learn.microsoft.com/en-us/windows-server/virtualization/hyper-v/manage/manage-hyper-v-scheduler-types
bcdedit /set hypervisorschedulertype root bcdedit /set hypervisorschedulertype root
if ($LASTEXITCODE -ne 0) {
throw "Failed to set hypervisorschedulertype to root"
}

View File

@@ -25,7 +25,7 @@ function Get-BazeliskVersion {
} }
function Get-BicepVersion { function Get-BicepVersion {
(bicep --version | Out-String) -match "bicep cli version (?<version>\d+\.\d+\.\d+)" | Out-Null (bicep --version | Out-String) -match "bicep cli version (?<version>\d+\.\d+\.\d+)" | Out-Null
$bicepVersion = $Matches.Version $bicepVersion = $Matches.Version
return $bicepVersion return $bicepVersion
} }
@@ -37,13 +37,13 @@ function Get-RVersion {
} }
function Get-CMakeVersion { function Get-CMakeVersion {
($(cmake -version) | Out-String) -match "cmake version (?<version>\d+\.\d+\.\d+)" | Out-Null ($(cmake -version) | Out-String) -match "cmake version (?<version>\d+\.\d+\.\d+)" | Out-Null
$cmakeVersion = $Matches.Version $cmakeVersion = $Matches.Version
return $cmakeVersion return $cmakeVersion
} }
function Get-CodeQLBundleVersion { function Get-CodeQLBundleVersion {
$CodeQLVersionsWildcard = Join-Path $Env:AGENT_TOOLSDIRECTORY -ChildPath "CodeQL" | Join-Path -ChildPath "*" $CodeQLVersionsWildcard = Join-Path $env:AGENT_TOOLSDIRECTORY -ChildPath "CodeQL" | Join-Path -ChildPath "*"
$CodeQLVersionPath = Get-ChildItem $CodeQLVersionsWildcard | Select-Object -First 1 -Expand FullName $CodeQLVersionPath = Get-ChildItem $CodeQLVersionsWildcard | Select-Object -First 1 -Expand FullName
$CodeQLPath = Join-Path $CodeQLVersionPath -ChildPath "x64" | Join-Path -ChildPath "codeql" | Join-Path -ChildPath "codeql.exe" $CodeQLPath = Join-Path $CodeQLVersionPath -ChildPath "x64" | Join-Path -ChildPath "codeql" | Join-Path -ChildPath "codeql.exe"
$CodeQLVersion = & $CodeQLPath version --quiet $CodeQLVersion = & $CodeQLPath version --quiet
@@ -92,7 +92,7 @@ function Get-JQVersion {
} }
function Get-KubectlVersion { function Get-KubectlVersion {
$kubectlVersion = (kubectl version --client --output=json | ConvertFrom-Json).clientVersion.gitVersion.Replace('v','') $kubectlVersion = (kubectl version --client --output=json | ConvertFrom-Json).clientVersion.gitVersion.Replace('v', '')
return $kubectlVersion return $kubectlVersion
} }
@@ -138,7 +138,7 @@ function Get-MercurialVersion {
} }
function Get-NSISVersion { function Get-NSISVersion {
$nsisVersion = &"c:\Program Files (x86)\NSIS\makensis.exe" "/Version" $nsisVersion = & "c:\Program Files (x86)\NSIS\makensis.exe" "/Version"
return $nsisVersion.TrimStart("v") return $nsisVersion.TrimStart("v")
} }
@@ -234,7 +234,7 @@ function Get-AlibabaCLIVersion {
} }
function Get-CloudFoundryVersion { function Get-CloudFoundryVersion {
$(cf version) -match "(?<version>\d+\.\d+\.\d+)" | Out-Null $(cf version) -match "(?<version>\d+\.\d+\.\d+)" | Out-Null
$cfVersion = $Matches.Version $cfVersion = $Matches.Version
return $cfVersion return $cfVersion
} }

View File

@@ -995,7 +995,7 @@ function Update-Environment {
$pathItems = $locations | ForEach-Object { $pathItems = $locations | ForEach-Object {
(Get-Item $_).GetValue('PATH').Split(';') (Get-Item $_).GetValue('PATH').Split(';')
} | Select-Object -Unique } | Select-Object -Unique
$Env:PATH = $pathItems -join ';' $env:PATH = $pathItems -join ';'
# Update other variables # Update other variables
$locations | ForEach-Object { $locations | ForEach-Object {

View File

@@ -5,15 +5,15 @@ Describe "MongoDB" {
@{ ToolName = "mongod" } @{ ToolName = "mongod" }
) { ) {
$toolsetVersion = (Get-ToolsetContent).mongodb.version $toolsetVersion = (Get-ToolsetContent).mongodb.version
(&$ToolName --version)[2].Split('"')[-2] | Should -BeLike "$toolsetVersion*" (& $ToolName --version)[2].Split('"')[-2] | Should -BeLike "$toolsetVersion*"
} }
} }
Context "Service" { Context "Service" {
$mongoService = Get-Service -Name mongodb -ErrorAction Ignore $mongoService = Get-Service -Name mongodb -ErrorAction Ignore
$mongoServiceTests = @{ $mongoServiceTests = @{
Name = $mongoService.Name Name = $mongoService.Name
Status = $mongoService.Status Status = $mongoService.Status
StartType = $mongoService.StartType StartType = $mongoService.StartType
} }
@@ -29,9 +29,9 @@ Describe "MongoDB" {
Describe "PostgreSQL" { Describe "PostgreSQL" {
$psqlTests = @( $psqlTests = @(
@{envVar = "PGROOT"; pgPath = Get-EnvironmentVariable "PGROOT"} @{envVar = "PGROOT"; pgPath = Get-EnvironmentVariable "PGROOT" }
@{envVar = "PGBIN"; pgPath = Get-EnvironmentVariable "PGBIN"} @{envVar = "PGBIN"; pgPath = Get-EnvironmentVariable "PGBIN" }
@{envVar = "PGDATA"; pgPath = Get-EnvironmentVariable "PGDATA"} @{envVar = "PGDATA"; pgPath = Get-EnvironmentVariable "PGDATA" }
) )
Context "Environment variable" { Context "Environment variable" {
@@ -57,8 +57,8 @@ Describe "PostgreSQL" {
Context "Service" { Context "Service" {
$psqlService = Get-Service -Name postgresql* $psqlService = Get-Service -Name postgresql*
$psqlServiceTests = @{ $psqlServiceTests = @{
Name = $psqlService.Name Name = $psqlService.Name
Status = $psqlService.Status Status = $psqlService.Status
StartType = $psqlService.StartType StartType = $psqlService.StartType
} }
@@ -75,9 +75,9 @@ Describe "PostgreSQL" {
It "PostgreSQL version should correspond to the version in the toolset" { It "PostgreSQL version should correspond to the version in the toolset" {
$toolsetVersion = (Get-ToolsetContent).postgresql.version $toolsetVersion = (Get-ToolsetContent).postgresql.version
# Client version # Client version
(&$Env:PGBIN\psql --version).split()[-1] | Should -BeLike "$toolsetVersion*" (& $env:PGBIN\psql --version).split()[-1] | Should -BeLike "$toolsetVersion*"
# Server version # Server version
(&$Env:PGBIN\pg_config --version).split()[-1] | Should -BeLike "$toolsetVersion*" (& $env:PGBIN\pg_config --version).split()[-1] | Should -BeLike "$toolsetVersion*"
} }
} }
} }

View File

@@ -23,19 +23,19 @@ Describe "Bazel" {
Describe "CodeQL Bundle" { Describe "CodeQL Bundle" {
It "Single distribution installed" { It "Single distribution installed" {
$CodeQLVersionsWildcard = Join-Path $Env:AGENT_TOOLSDIRECTORY -ChildPath "CodeQL" | Join-Path -ChildPath "*" $CodeQLVersionsWildcard = Join-Path $env:AGENT_TOOLSDIRECTORY -ChildPath "CodeQL" | Join-Path -ChildPath "*"
$CodeQLVersionPath = Get-ChildItem $CodeQLVersionsWildcard | Should -HaveCount 1 $CodeQLVersionPath = Get-ChildItem $CodeQLVersionsWildcard | Should -HaveCount 1
} }
It "Contains CodeQL executable" { It "Contains CodeQL executable" {
$CodeQLVersionsWildcard = Join-Path $Env:AGENT_TOOLSDIRECTORY -ChildPath "CodeQL" | Join-Path -ChildPath "*" $CodeQLVersionsWildcard = Join-Path $env:AGENT_TOOLSDIRECTORY -ChildPath "CodeQL" | Join-Path -ChildPath "*"
$CodeQLVersionPath = Get-ChildItem $CodeQLVersionsWildcard | Sort-Object -Descending | Select-Object -First 1 -Expand FullName $CodeQLVersionPath = Get-ChildItem $CodeQLVersionsWildcard | Sort-Object -Descending | Select-Object -First 1 -Expand FullName
$CodeQLPath = Join-Path $CodeQLVersionPath -ChildPath "x64" | Join-Path -ChildPath "codeql" | Join-Path -ChildPath "codeql.exe" $CodeQLPath = Join-Path $CodeQLVersionPath -ChildPath "x64" | Join-Path -ChildPath "codeql" | Join-Path -ChildPath "codeql.exe"
"$CodeQLPath version --quiet" | Should -ReturnZeroExitCode "$CodeQLPath version --quiet" | Should -ReturnZeroExitCode
} }
It "Contains CodeQL packs" { It "Contains CodeQL packs" {
$CodeQLVersionsWildcard = Join-Path $Env:AGENT_TOOLSDIRECTORY -ChildPath "CodeQL" | Join-Path -ChildPath "*" $CodeQLVersionsWildcard = Join-Path $env:AGENT_TOOLSDIRECTORY -ChildPath "CodeQL" | Join-Path -ChildPath "*"
$CodeQLVersionPath = Get-ChildItem $CodeQLVersionsWildcard | Sort-Object -Descending | Select-Object -First 1 -Expand FullName $CodeQLVersionPath = Get-ChildItem $CodeQLVersionsWildcard | Sort-Object -Descending | Select-Object -First 1 -Expand FullName
$CodeQLPacksPath = Join-Path $CodeQLVersionPath -ChildPath "x64" | Join-Path -ChildPath "codeql" | Join-Path -ChildPath "qlpacks" $CodeQLPacksPath = Join-Path $CodeQLVersionPath -ChildPath "x64" | Join-Path -ChildPath "codeql" | Join-Path -ChildPath "qlpacks"
$CodeQLPacksPath | Should -Exist $CodeQLPacksPath | Should -Exist
@@ -119,7 +119,7 @@ Describe "NET48" {
Describe "NSIS" { Describe "NSIS" {
It "NSIS" { It "NSIS" {
"makensis /VERSION" | Should -ReturnZeroExitCode "makensis /VERSION" | Should -ReturnZeroExitCode
} }
} }
@@ -201,9 +201,9 @@ Describe "Pipx" {
} }
Describe "Kotlin" { Describe "Kotlin" {
$kotlinPackages = @("kapt", "kotlin", "kotlinc", "kotlin-dce-js", "kotlinc-jvm") $kotlinPackages = @("kapt", "kotlin", "kotlinc", "kotlin-dce-js", "kotlinc-jvm")
It "<toolName> is available" -TestCases ($kotlinPackages | ForEach-Object { @{ toolName = $_ } }) { It "<toolName> is available" -TestCases ($kotlinPackages | ForEach-Object { @{ toolName = $_ } }) {
"$toolName -version" | Should -ReturnZeroExitCode "$toolName -version" | Should -ReturnZeroExitCode
} }
} }

View File

@@ -12,7 +12,7 @@ $toolsExecutables = @{
@{ Binary = "npm"; Arguments = "--version" } @{ Binary = "npm"; Arguments = "--version" }
) )
Go = @( Go = @(
@{ Binary = "bin\go.exe"; Arguments = "version" } @{ Binary = "bin\go.exe"; Arguments = "version" }
) )
Ruby = @( Ruby = @(
@{ Binary = "bin\ruby.exe"; Arguments = "--version" } @{ Binary = "bin\ruby.exe"; Arguments = "--version" }

View File

@@ -17,7 +17,7 @@ Describe "WindowsFeatures" {
Describe "DiskSpace" { Describe "DiskSpace" {
It "The image has enough disk space"{ It "The image has enough disk space"{
$availableSpaceMB = [math]::Round((Get-PSDrive -Name C).Free / 1MB) $availableSpaceMB = [math]::Round((Get-PSDrive -Name C).Free / 1MB)
$minimumFreeSpaceMB = 18 * 1024 $minimumFreeSpaceMB = 18 * 1024
$availableSpaceMB | Should -BeGreaterThan $minimumFreeSpaceMB $availableSpaceMB | Should -BeGreaterThan $minimumFreeSpaceMB
@@ -26,7 +26,7 @@ Describe "DiskSpace" {
Describe "DynamicPorts" { Describe "DynamicPorts" {
It "Test TCP dynamicport start=49152 num=16384" { It "Test TCP dynamicport start=49152 num=16384" {
$tcpPorts = Get-NetTCPSetting | Where-Object {$_.SettingName -ne "Automatic"} | Where-Object { $tcpPorts = Get-NetTCPSetting | Where-Object { $_.SettingName -ne "Automatic" } | Where-Object {
$_.DynamicPortRangeStartPort -ne 49152 -or $_.DynamicPortRangeNumberOfPorts -ne 16384 $_.DynamicPortRangeStartPort -ne 49152 -or $_.DynamicPortRangeNumberOfPorts -ne 16384
} }
@@ -52,7 +52,7 @@ Describe "GDIProcessHandleQuota" {
} }
Describe "Test Signed Drivers" { Describe "Test Signed Drivers" {
It "bcdedit testsigning should be Yes"{ It "bcdedit testsigning should be Yes" {
"$(bcdedit)" | Should -Match "testsigning\s+Yes" "$(bcdedit)" | Should -Match "testsigning\s+Yes"
} }
} }
@@ -64,7 +64,7 @@ Describe "Windows Updates" {
$testCases = Get-WindowsUpdateStates | Sort-Object Title | ForEach-Object { $testCases = Get-WindowsUpdateStates | Sort-Object Title | ForEach-Object {
@{ @{
Title = $_.Title Title = $_.Title
State = $_.State State = $_.State
} }
} }

View File

@@ -145,7 +145,6 @@
"IMAGE_VERSION={{user `image_version`}}", "IMAGE_VERSION={{user `image_version`}}",
"IMAGE_OS={{user `image_os`}}", "IMAGE_OS={{user `image_os`}}",
"AGENT_TOOLSDIRECTORY={{user `agent_tools_directory`}}", "AGENT_TOOLSDIRECTORY={{user `agent_tools_directory`}}",
"ACTIONS_RUNNER_ACTION_ARCHIVE_CACHE=C:\\actionarchivecache\\",
"IMAGEDATA_FILE={{user `imagedata_file`}}" "IMAGEDATA_FILE={{user `imagedata_file`}}"
], ],
"scripts": [ "scripts": [
@@ -360,9 +359,9 @@
{ {
"type": "powershell", "type": "powershell",
"inline": [ "inline": [
"if( Test-Path $Env:SystemRoot\\System32\\Sysprep\\unattend.xml ){ rm $Env:SystemRoot\\System32\\Sysprep\\unattend.xml -Force}", "if( Test-Path $env:SystemRoot\\System32\\Sysprep\\unattend.xml ){ rm $env:SystemRoot\\System32\\Sysprep\\unattend.xml -Force}",
"& $env:SystemRoot\\System32\\Sysprep\\Sysprep.exe /oobe /generalize /quiet /quit", "& $env:SystemRoot\\System32\\Sysprep\\Sysprep.exe /oobe /generalize /quiet /quit",
"while($true) { $imageState = Get-ItemProperty HKLM:\\SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Setup\\State | Select ImageState; if($imageState.ImageState -ne 'IMAGE_STATE_GENERALIZE_RESEAL_TO_OOBE') { Write-Output $imageState.ImageState; Start-Sleep -s 10 } else { break } }" "while($true) { $imageState = Get-ItemProperty HKLM:\\SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Setup\\State | Select ImageState; if($imageState.ImageState -ne 'IMAGE_STATE_GENERALIZE_RESEAL_TO_OOBE') { Write-Output $imageState.ImageState; Start-Sleep -s 10 } else { break } }"
] ]
} }
] ]

View File

@@ -129,7 +129,6 @@
"IMAGE_VERSION={{user `image_version`}}", "IMAGE_VERSION={{user `image_version`}}",
"IMAGE_OS={{user `image_os`}}", "IMAGE_OS={{user `image_os`}}",
"AGENT_TOOLSDIRECTORY={{user `agent_tools_directory`}}", "AGENT_TOOLSDIRECTORY={{user `agent_tools_directory`}}",
"ACTIONS_RUNNER_ACTION_ARCHIVE_CACHE=C:\\actionarchivecache\\",
"IMAGEDATA_FILE={{user `imagedata_file`}}" "IMAGEDATA_FILE={{user `imagedata_file`}}"
], ],
"scripts": [ "scripts": [
@@ -347,9 +346,9 @@
{ {
"type": "powershell", "type": "powershell",
"inline": [ "inline": [
"if( Test-Path $Env:SystemRoot\\System32\\Sysprep\\unattend.xml ){ rm $Env:SystemRoot\\System32\\Sysprep\\unattend.xml -Force}", "if( Test-Path $env:SystemRoot\\System32\\Sysprep\\unattend.xml ){ rm $env:SystemRoot\\System32\\Sysprep\\unattend.xml -Force}",
"& $env:SystemRoot\\System32\\Sysprep\\Sysprep.exe /oobe /generalize /mode:vm /quiet /quit", "& $env:SystemRoot\\System32\\Sysprep\\Sysprep.exe /oobe /generalize /mode:vm /quiet /quit",
"while($true) { $imageState = Get-ItemProperty HKLM:\\SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Setup\\State | Select ImageState; if($imageState.ImageState -ne 'IMAGE_STATE_GENERALIZE_RESEAL_TO_OOBE') { Write-Output $imageState.ImageState; Start-Sleep -s 10 } else { break } }" "while($true) { $imageState = Get-ItemProperty HKLM:\\SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Setup\\State | Select ImageState; if($imageState.ImageState -ne 'IMAGE_STATE_GENERALIZE_RESEAL_TO_OOBE') { Write-Output $imageState.ImageState; Start-Sleep -s 10 } else { break } }"
] ]
} }
] ]