Skip to content

Commit 673de02

Browse files
committed
PSv5 backward compatibility for Invoke-WebRequest
1 parent 1037a1a commit 673de02

File tree

2 files changed

+23
-7
lines changed

2 files changed

+23
-7
lines changed

Tests/CommonToolUtilities.Tests.ps1

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -253,9 +253,11 @@ Describe "CommonToolUtilities.psm1" {
253253
It "Should throw an error if download fails" {
254254
$errorMessage = "Response status code does not indicate success: 404 (Not Found)."
255255
Mock Invoke-WebRequest { Throw $errorMessage } -ModuleName "CommonToolUtilities"
256+
Mock Start-Sleep -ModuleName "CommonToolUtilities"
256257

257258
{ Get-InstallationFile -FileParameters $Script:MockFiles } | Should -Throw "Failed to download asset*"
258-
$Error[1].Exception.Message | Should -BeLike "Failed to download assets for `"v2.0.0-rc.1`". Couldn`'t download `"v2.0.0-rc.1`" release assets.*"
259+
Should -Invoke Invoke-WebRequest -Times 3 -Scope It -ModuleName "CommonToolUtilities"
260+
$Error[1].Exception.Message | Should -BeLike "Failed to download assets for `"v2.0.0-rc.1`". Couldn`'t download `"v2.0.0-rc.1`" release assets*"
259261
}
260262
}
261263

containers-toolkit/Private/CommonToolUtilities.psm1

Lines changed: 20 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -205,12 +205,26 @@ function Get-InstallationFile {
205205
begin {
206206
function Receive-File {
207207
param($params)
208-
try {
209-
Invoke-WebRequest -Uri $params.Uri -OutFile $params.DownloadPath -UseBasicParsing -MaximumRetryCount 3 -RetryIntervalSec 60
210-
}
211-
catch {
212-
Throw "Couldn't download `"$($params.Feature)`" release assets. `"$($params.Uri)`".`n$($_.Exception.Message)"
213-
}
208+
209+
$MaximumRetryCount = 3
210+
$RetryIntervalSec = 60
211+
$lastError = $null # Store the last exception
212+
213+
do {
214+
try {
215+
Invoke-WebRequest -Uri $params.Uri -OutFile $params.DownloadPath -UseBasicParsing
216+
return
217+
}
218+
catch {
219+
$lastError = $_ # Store the last error for proper exception handling
220+
Write-Warning "Failed to download `"$($params.Feature)`" release assets. Retrying... ($MaximumRetryCount retries left)"
221+
Start-Sleep -Seconds $RetryIntervalSec
222+
$MaximumRetryCount -= 1
223+
}
224+
} until ($MaximumRetryCount -eq 0)
225+
226+
# Throw the last encountered error after all retries fail
227+
Throw "Couldn't download `"$($params.Feature)`" release assets from `"$($params.Uri)`".`n$($lastError.Exception.Message)"
214228
}
215229

216230
function DownloadAssets {

0 commit comments

Comments
 (0)