Skip to content

Commit

Permalink
Throw when script error (#74)
Browse files Browse the repository at this point in the history
  • Loading branch information
Trenly committed Oct 13, 2021
1 parent 48818d7 commit 4a437bd
Showing 1 changed file with 44 additions and 19 deletions.
63 changes: 44 additions & 19 deletions Tools/YamlCreate.ps1
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ if ($help) {
}

# Set settings directory on basis of Operating System
$script:SettingsPath = Join-Path $(if ([System.Environment]::OSVersion.Platform -match 'Win') {$env:LOCALAPPDATA} else {$env:HOME+'/.config'} ) -ChildPath 'YamlCreate'
$script:SettingsPath = Join-Path $(if ([System.Environment]::OSVersion.Platform -match 'Win') { $env:LOCALAPPDATA } else { $env:HOME + '/.config' } ) -ChildPath 'YamlCreate'
# Check for settings directory and create it if none exists
if (!(Test-Path $script:SettingsPath)) { New-Item -ItemType 'Directory' -Force -Path $script:SettingsPath | Out-Null }
# Check for settings file and create it if none exists
Expand Down Expand Up @@ -71,7 +71,13 @@ if (-not(Get-Module -ListAvailable -Name powershell-yaml)) {
Install-PackageProvider -Name NuGet -MinimumVersion 2.8.5.201 -Force
Install-Module -Name powershell-yaml -Force -Repository PSGallery -Scope CurrentUser
} catch {
Throw "Unmet dependency. 'powershell-yaml' unable to be installed successfully."
# If there was an exception while installing powershell-yaml, pass it as an InternalException for further debugging
throw [UnmetDependencyException]::new("'powershell-yaml' unable to be installed successfully", $_.Exception)
} finally {
# Double check that it was installed properly
if (-not(Get-Module -ListAvailable -Name powershell-yaml)) {
throw [UnmetDependencyException]::new("'powershell-yaml' is not found")
}
}
}

Expand All @@ -88,8 +94,8 @@ try {
$InstallerEntryProperties = (ConvertTo-Yaml $InstallerSchema.definitions.Installer.properties | ConvertFrom-Yaml -Ordered).Keys
$InstallerDependencyProperties = (ConvertTo-Yaml $InstallerSchema.definitions.Dependencies.properties | ConvertFrom-Yaml -Ordered).Keys
} catch {
Write-Host 'Error downloading schemas. Please run the script again.' -ForegroundColor Red
exit 1
# Here we want to pass the exception as an inner exception for debugging if necessary
throw [System.Net.WebException]::new('Manifest schemas could not be downloaded. Try running the script again', $_.Exception)
}

filter TrimString {
Expand Down Expand Up @@ -204,7 +210,9 @@ Function Write-Colors {
[Parameter(Mandatory = $true, Position = 1)]
[string[]] $Colors
)
If ($TextStrings.Count -ne $Colors.Count) { Throw 'Invalid Function Parameters. Arguments must be of equal length' }
If ($TextStrings.Count -ne $Colors.Count) {
throw [System.ArgumentException]::new('Invalid Function Parameters. Arguments must be of equal length')
}
$_index = 0
Foreach ($String in $TextStrings) {
Write-Host -ForegroundColor $Colors[$_index] -NoNewline $String
Expand Down Expand Up @@ -276,7 +284,9 @@ Function TestUrlValidity {
$HTTP_Request = [System.Net.WebRequest]::Create($URL)
$HTTP_Response = $HTTP_Request.GetResponse()
$HTTP_Status = [int]$HTTP_Response.StatusCode
} catch {}
} catch {
# Take no action here; If there is an exception, we will treat it like a 404
}
If ($null -eq $HTTP_Response) { $HTTP_Status = 404 }
Else { $HTTP_Response.Close() }

Expand Down Expand Up @@ -370,8 +380,8 @@ Function Read-Installer-Values {
try {
$WebClient.DownloadFile($InstallerUrl, $script:dest)
} catch {
Write-Host 'Error downloading file. Please run the script again.' -ForegroundColor Red
exit 1
# Here we also want to pass the exception through for potential debugging
throw [System.Net.WebException]::new('The file could not be downloaded. Try running the script again', $_.Exception)
} finally {
Write-Host "Time taken: $((Get-Date).Subtract($start_time).Seconds) second(s)" -ForegroundColor Green

Expand Down Expand Up @@ -551,6 +561,7 @@ Function Read-Installer-Values {
$PackageFamilyName = $InstalledPkg.PackageFamilyName
Remove-AppxPackage $InstalledPkg.PackageFullName
} catch {
# Take no action here, we just want to catch the exceptions as a precaution
Out-Null
} finally {
if (String.Validate $PackageFamilyName -IsNull) {
Expand Down Expand Up @@ -750,8 +761,8 @@ Function Read-Installer-Values-Minimal {
try {
$WebClient.DownloadFile($($_NewInstaller.InstallerUrl), $script:dest)
} catch {
Write-Host 'Error downloading file. Please run the script again.' -ForegroundColor Red
exit 1
# Here we also want to pass the exception through for potential debugging
throw [System.Net.WebException]::new('The file could not be downloaded. Try running the script again', $_.Exception)
} finally {
# Get the Sha256
$_NewInstaller['InstallerSha256'] = (Get-FileHash -Path $script:dest -Algorithm SHA256).Hash
Expand Down Expand Up @@ -782,6 +793,7 @@ Function Read-Installer-Values-Minimal {
$PackageFamilyName = $InstalledPkg.PackageFamilyName
Remove-AppxPackage $InstalledPkg.PackageFullName
} catch {
# Take no action here, we just want to catch the exceptions as a precaution
Out-Null
} finally {
if (String.Validate -not $PackageFamilyName -IsNull) {
Expand Down Expand Up @@ -1408,7 +1420,10 @@ Function AddYamlListParameter {
if ($Parameter -eq 'InstallerSuccessCodes') {
try {
$Value = [int]$Value
} catch {}
} catch {
# If we can't cast the value to an integer, it doesn't matter
# Continue using the value as is
}
}
$_Values += $Value
}
Expand Down Expand Up @@ -1756,7 +1771,7 @@ if (($script:Option -eq 'QuickUpdateVersion') -and ($ScriptSettings.SuppressQuic
switch ( KeypressMenu -Prompt $_menu['Prompt'] -Entries $_menu['Entries'] -DefaultString $_menu['DefaultString'] -HelpText $_menu['HelpText'] -HelpTextColor $_menu['HelpTextColor']) {
'Y' { Write-Host -ForegroundColor DarkYellow -Object "`n`nContinuing with Quick Update" }
'N' { $script:Option = 'New'; Write-Host -ForegroundColor DarkYellow -Object "`n`nSwitched to Full Update Experience" }
default { Write-Host; exit 1 }
default { Write-Host; exit }
}
}
Write-Host
Expand Down Expand Up @@ -1821,7 +1836,7 @@ if ($ScriptSettings.ContinueWithExistingPRs -ne 'always') {
}
switch ( KeypressMenu -Prompt $_menu['Prompt'] -Entries $_menu['Entries'] -DefaultString $_menu['DefaultString'] -HelpText $_menu['HelpText'] -HelpTextColor $_menu['HelpTextColor'] ) {
'Y' { Write-Host }
default { Write-Host; exit 1 }
default { Write-Host; exit }
}
}
}
Expand All @@ -1848,7 +1863,7 @@ if ($script:Option -in @('NewLocale'; 'EditMetadata'; 'RemoveManifest')) {
Write-Host
Write-Host -ForegroundColor 'Red' -Object 'Could not find required manifests, input a version containing required manifests or "exit" to cancel'
$PromptVersion = Read-Host -Prompt 'Version' | TrimString
if ($PromptVersion -eq 'exit') { exit 1 }
if ($PromptVersion -eq 'exit') { exit }
if (Test-Path -Path "$AppFolder\..\$PromptVersion") {
$script:OldManifests = Get-ChildItem -Path "$AppFolder\..\$PromptVersion"
}
Expand All @@ -1875,6 +1890,7 @@ if (!$LastVersion) {
Write-Host -ForegroundColor 'DarkYellow' -Object "Found Existing Version: $LastVersion"
$script:OldManifests = Get-ChildItem -Path "$AppFolder\..\$LastVersion"
} catch {
# Take no action here, we just want to catch the exceptions as a precaution
Out-Null
}
}
Expand Down Expand Up @@ -1922,7 +1938,7 @@ if ($OldManifests.Name -eq "$PackageIdentifier.installer.yaml" -and $OldManifest
$script:OldLocaleManifest = ConvertFrom-Yaml -Yaml ($(Get-Content -Path $(Resolve-Path "$AppFolder\..\$LastVersion\$PackageIdentifier.locale.$PackageLocale.yaml") -Encoding UTF8) -join "`n") -Ordered
$script:OldVersionManifest = ConvertFrom-Yaml -Yaml ($(Get-Content -Path $(Resolve-Path "$AppFolder\..\$LastVersion\$PackageIdentifier.yaml") -Encoding UTF8) -join "`n") -Ordered
} elseif ($OldManifests.Name -eq "$PackageIdentifier.yaml") {
if ($script:Option -eq 'NewLocale') { Throw 'Error: MultiManifest Required' }
if ($script:Option -eq 'NewLocale') { throw [ManifestException]::new('MultiManifest Required') }
$script:OldManifestType = 'MultiManifest'
$script:OldSingletonManifest = ConvertFrom-Yaml -Yaml ($(Get-Content -Path $(Resolve-Path "$AppFolder\..\$LastVersion\$PackageIdentifier.yaml") -Encoding UTF8) -join "`n") -Ordered
# Create new empty manifests
Expand Down Expand Up @@ -1971,7 +1987,7 @@ if ($OldManifests.Name -eq "$PackageIdentifier.installer.yaml" -and $OldManifest
}
}
} else {
if ($script:Option -ne 'New') { Throw "Error: Version $LastVersion does not contain the required manifests" }
if ($script:Option -ne 'New') { throw [ManifestException]::new("Version $LastVersion does not contain the required manifests") }
$script:OldManifestType = 'None'
}

Expand Down Expand Up @@ -2067,8 +2083,8 @@ Switch ($script:Option) {
try {
$WebClient.DownloadFile($($_Installer.InstallerUrl), $script:dest)
} catch {
Write-Host 'Error downloading file. Please run the script again.' -ForegroundColor Red
exit 1
# Here we also want to pass the exception through for potential debugging
throw [System.Net.WebException]::new('The file could not be downloaded. Try running the script again', $_.Exception)
} finally {
# Get the Sha256
$_Installer['InstallerSha256'] = (Get-FileHash -Path $script:dest -Algorithm SHA256).Hash
Expand Down Expand Up @@ -2099,6 +2115,7 @@ Switch ($script:Option) {
$PackageFamilyName = $InstalledPkg.PackageFamilyName
Remove-AppxPackage $InstalledPkg.PackageFullName
} catch {
# Take no action here, we just want to catch the exceptions as a precaution
Out-Null
} finally {
if (String.Validate -not $PackageFamilyName -IsNull) {
Expand Down Expand Up @@ -2241,7 +2258,7 @@ if ($PromptSubmit -eq '0') {
}
} else {
Write-Host
Exit
exit
}

# Error levels for the ReturnValue class
Expand Down Expand Up @@ -2330,3 +2347,11 @@ Class ReturnValue {
}
}
}

class UnmetDependencyException : Exception {
UnmetDependencyException([string] $message) : base($message) {}
UnmetDependencyException([string] $message, [Exception] $exception) : base($message, $exception) {}
}
class ManifestException : Exception {
ManifestException([string] $message) : base($message) {}
}

0 comments on commit 4a437bd

Please sign in to comment.