Skip to content

Commit

Permalink
Adding try/catch logic to Write-VcsStatus
Browse files Browse the repository at this point in the history
Adding try/catch logic to Write-VcsStatus so that if one of the scriptblocks that has been added to the VcsPromptStatuses array fails the other scriptblocks are still invoked and the effect on the user's prompt is minimized

Use of the ErrorVariable parameter during invocation is to also capture any errors that were written to the error stream
  • Loading branch information
paulmarsy committed May 22, 2015
1 parent 4d95124 commit 2eb11c2
Showing 1 changed file with 25 additions and 2 deletions.
27 changes: 25 additions & 2 deletions GitPrompt.ps1
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,9 @@ $global:GitPromptSettings = New-Object PSObject -Property @{
UntrackedText = ' !'
UntrackedForegroundColor = [ConsoleColor]::DarkRed
UntrackedBackgroundColor = $Host.UI.RawUI.BackgroundColor

ErrorForegroundColor = [ConsoleColor]::Red
ErrorBackgroundColor = $Host.UI.RawUI.BackgroundColor

ShowStatusWhenZero = $true

Expand Down Expand Up @@ -167,12 +170,32 @@ function Write-GitStatus($status) {
if(!(Test-Path Variable:Global:VcsPromptStatuses)) {
$Global:VcsPromptStatuses = @()
}
function Global:Write-VcsStatus { $Global:VcsPromptStatuses | foreach { & $_ } }

function Global:Write-VcsStatus {
$Global:VcsPromptStatuses | foreach {
$vcsPromptErrors = $null
try {
Invoke-Command -ScriptBlock $_ -ErrorVariable vcsPromptErrors 2>$null
}
catch {
$vcsPromptErrors = $_
}
if ($vcsPromptErrors.Length -gt 0) {
$vcsPromptErrors | % { Write-Error -ErrorRecord $_ -ErrorAction SilentlyContinue }
$s = $Global:GitPromptSettings
if ($s) {
Write-Prompt $s.BeforeText -BackgroundColor $s.BeforeBackgroundColor -ForegroundColor $s.BeforeForegroundColor
Write-Prompt "Error" -BackgroundColor $s.ErrorBackgroundColor -ForegroundColor $s.ErrorForegroundColor
Write-Prompt $s.AfterText -BackgroundColor $s.AfterBackgroundColor -ForegroundColor $s.AfterForegroundColor
}
}
}
}

# Add scriptblock that will execute for Write-VcsStatus
$PoshGitVcsPrompt = {
$Global:GitStatus = Get-GitStatus
Write-GitStatus $GitStatus
}
}
$Global:VcsPromptStatuses += $PoshGitVcsPrompt
$ExecutionContext.SessionState.Module.OnRemove = { $Global:VcsPromptStatuses = $Global:VcsPromptStatuses | ? { $_ -ne $PoshGitVcsPrompt} }

0 comments on commit 2eb11c2

Please sign in to comment.