Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Refactor all git calls to capture STDERR properly #183

Closed
wants to merge 15 commits into from
Closed
Show file tree
Hide file tree
Changes from 12 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion CheckVersion.ps1
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ if (!(Get-Command git -TotalCount 1 -ErrorAction SilentlyContinue)) {
}

$requiredVersion = [Version]'1.7.2'
if ((git --version 2> $null) -match '(?<ver>\d+(?:\.\d+)+)') {
if ((safeexec { git --version }) -match '(?<ver>\d+(?:\.\d+)+)') {
$version = [Version]$Matches['ver']
}
if ($version -lt $requiredVersion) {
Expand Down
70 changes: 70 additions & 0 deletions Exec.ps1
Original file line number Diff line number Diff line change
@@ -0,0 +1,70 @@
#requires -version 2.0

[CmdletBinding()]
param
(
)

$script:ErrorActionPreference = "Stop"
Set-StrictMode -Version Latest
function PSScriptRoot { $MyInvocation.ScriptName | Split-Path }

trap { throw $Error[0] }

function Invoke-NativeApplication
{
param
(
[ScriptBlock] $ScriptBlock,
[int[]] $AllowedExitCodes = @(0),
[switch] $IgnoreExitCode
)

$backupErrorActionPreference = $ErrorActionPreference

$ErrorActionPreference = "Continue"
try
{
if (Test-CalledFromPrompt)
{
$wrapperScriptBlock = { & $ScriptBlock }
}
else
{
$wrapperScriptBlock = { & $ScriptBlock 2>&1 }
}

& $wrapperScriptBlock | ForEach-Object -Process `
{
$isError = $_ -is [System.Management.Automation.ErrorRecord]
"$_" | Add-Member -Name IsError -MemberType NoteProperty -Value $isError -PassThru
}
if ((-not $IgnoreExitCode) -and (Test-Path -Path Variable:LASTEXITCODE) -and ($AllowedExitCodes -notcontains $LASTEXITCODE))
{
throw "Execution failed with exit code $LASTEXITCODE"
}
}
finally
{
$ErrorActionPreference = $backupErrorActionPreference
}
}

function Invoke-NativeApplicationSafe
{
param
(
[ScriptBlock] $ScriptBlock
)

Invoke-NativeApplication -ScriptBlock $ScriptBlock -IgnoreExitCode | `
Where-Object -FilterScript { -not $_.IsError }
}

function Test-CalledFromPrompt
{
(Get-PSCallStack)[-2].Command -eq "prompt"
}

Set-Alias -Name exec -Value Invoke-NativeApplication
Set-Alias -Name safeexec -Value Invoke-NativeApplicationSafe
2 changes: 1 addition & 1 deletion GitPrompt.ps1
Original file line number Diff line number Diff line change
Expand Up @@ -133,7 +133,7 @@ function Write-GitStatus($status) {
Write-Prompt $s.AfterText -BackgroundColor $s.AfterBackgroundColor -ForegroundColor $s.AfterForegroundColor

if ($WindowTitleSupported -and $s.EnableWindowTitle) {
if( -not $Global:PreviousWindowTitle ) {
if (-not (Test-Path -Path Variable:Global:PreviousWindowTitle)) {
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Can you apply this strict revision to elseif ( $Global:PreviousWindowTitle ) below? Getting this:

The variable '$Global:PreviousWindowTitle' cannot be retrieved because it has not been set.

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed

$Global:PreviousWindowTitle = $Host.UI.RawUI.WindowTitle
}
$repoName = Split-Path -Leaf (Split-Path $status.GitDir)
Expand Down
25 changes: 13 additions & 12 deletions GitTabExpansion.ps1
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@ function script:gitCmdOperations($commands, $command, $filter) {

$script:someCommands = @('add','am','annotate','archive','bisect','blame','branch','bundle','checkout','cherry','cherry-pick','citool','clean','clone','commit','config','describe','diff','difftool','fetch','format-patch','gc','grep','gui','help','init','instaweb','log','merge','mergetool','mv','notes','prune','pull','push','rebase','reflog','remote','rerere','reset','revert','rm','shortlog','show','stash','status','submodule','svn','tag','whatchanged')
try {
if ((git help -a 2>&1 | Select-String flow) -ne $null) {
if ((safeexec { git help -a } | Select-String flow) -ne $null) {
$script:someCommands += 'flow'
}
}
Expand All @@ -43,7 +43,7 @@ function script:gitCommands($filter, $includeAliases) {
if (-not $global:GitTabSettings.AllCommands) {
$cmdList += $someCommands -like "$filter*"
} else {
$cmdList += git help --all |
$cmdList += safeexec{ git help --all } |
where { $_ -match '^ \S.*' } |
foreach { $_.Split(' ', [StringSplitOptions]::RemoveEmptyEntries) } |
where { $_ -like "$filter*" }
Expand All @@ -56,7 +56,7 @@ function script:gitCommands($filter, $includeAliases) {
}

function script:gitRemotes($filter) {
git remote |
safeexec { git remote } |
where { $_ -like "$filter*" }
}

Expand All @@ -66,36 +66,36 @@ function script:gitBranches($filter, $includeHEAD = $false) {
$prefix = $matches['from']
$filter = $matches['to']
}
$branches = @(git branch --no-color | foreach { if($_ -match "^\*?\s*(?<ref>.*)") { $matches['ref'] } }) +
@(git branch --no-color -r | foreach { if($_ -match "^ (?<ref>\S+)(?: -> .+)?") { $matches['ref'] } }) +
$branches = @(safeexec { git branch --no-color } | foreach { if($_ -match "^\*?\s*(?<ref>.*)") { $matches['ref'] } }) +
@(safeexec { git branch --no-color -r } | foreach { if($_ -match "^ (?<ref>\S+)(?: -> .+)?") { $matches['ref'] } }) +
@(if ($includeHEAD) { 'HEAD','FETCH_HEAD','ORIG_HEAD','MERGE_HEAD' })
$branches |
where { $_ -ne '(no branch)' -and $_ -like "$filter*" } |
foreach { $prefix + $_ }
}

function script:gitFeatures($filter, $command){
$featurePrefix = git config --local --get "gitflow.prefix.$command"
$branches = @(git branch --no-color | foreach { if($_ -match "^\*?\s*$featurePrefix(?<ref>.*)") { $matches['ref'] } })
$featurePrefix = safeexec { git config --local --get "gitflow.prefix.$command" }
$branches = @(safeexec { git branch --no-color } | foreach { if($_ -match "^\*?\s*$featurePrefix(?<ref>.*)") { $matches['ref'] } })
$branches |
where { $_ -ne '(no branch)' -and $_ -like "$filter*" } |
foreach { $prefix + $_ }
}

function script:gitRemoteBranches($remote, $ref, $filter) {
git branch --no-color -r |
safeexec { git branch --no-color -r } |
where { $_ -like " $remote/$filter*" } |
foreach { $ref + ($_ -replace " $remote/","") }
}

function script:gitStashes($filter) {
(git stash list) -replace ':.*','' |
(safeexec { git stash list } ) -replace ':.*','' |
where { $_ -like "$filter*" } |
foreach { "'$_'" }
}

function script:gitTfsShelvesets($filter) {
(git tfs shelve-list) |
(safeexec { git tfs shelve-list }) |
where { $_ -like "$filter*" } |
foreach { "'$_'" }
}
Expand Down Expand Up @@ -135,7 +135,7 @@ function script:gitDeleted($filter) {
}

function script:gitAliases($filter) {
git config --get-regexp ^alias\. | foreach {
safeexec { git config --get-regexp ^alias\. } | foreach {
if($_ -match "^alias\.(?<alias>\S+) .*") {
$alias = $Matches['alias']
if($alias -like "$filter*") {
Expand All @@ -146,7 +146,7 @@ function script:gitAliases($filter) {
}

function script:expandGitAlias($cmd, $rest) {
if((git config --get-regexp "^alias\.$cmd`$") -match "^alias\.$cmd (?<cmd>[^!].*)`$") {
if((safeexec { git config --get-regexp "^alias\.$cmd`$" }) -match "^alias\.$cmd (?<cmd>[^!].*)`$") {
return "git $($Matches['cmd'])$rest"
} else {
return "git $cmd$rest"
Expand Down Expand Up @@ -299,6 +299,7 @@ if (Test-Path Function:\TabExpansion) {
}

function TabExpansion($line, $lastWord) {
"line: $line, lastWord: $lastWord" > c:\dev\333.txt
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Debugging?

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed

$lastBlock = [regex]::Split($line, '[|;]')[-1].TrimStart()

switch -regex ($lastBlock) {
Expand Down
34 changes: 17 additions & 17 deletions GitUtils.ps1
Original file line number Diff line number Diff line change
Expand Up @@ -46,15 +46,15 @@ function Get-GitBranch($gitDir = $(Get-GitDirectory), [Diagnostics.Stopwatch]$sw
}

$b = Invoke-NullCoalescing `
{ dbg 'Trying symbolic-ref' $sw; git symbolic-ref HEAD 2>$null } `
{ dbg 'Trying symbolic-ref' $sw; safeexec { git symbolic-ref HEAD } } `
{ '({0})' -f (Invoke-NullCoalescing `
{
dbg 'Trying describe' $sw
switch ($Global:GitPromptSettings.DescribeStyle) {
'contains' { git describe --contains HEAD 2>$null }
'branch' { git describe --contains --all HEAD 2>$null }
'describe' { git describe HEAD 2>$null }
default { git describe --tags --exact-match HEAD 2>$null }
'contains' { safeexec { git describe --contains HEAD } }
'branch' { safeexec { git describe --contains --all HEAD } }
'describe' { safeexec { git describe HEAD } }
default { safeexec { git describe --tags --exact-match HEAD } }
}
} `
{
Expand All @@ -63,10 +63,10 @@ function Get-GitBranch($gitDir = $(Get-GitDirectory), [Diagnostics.Stopwatch]$sw

if (Test-Path $gitDir\HEAD) {
dbg 'Reading from .git\HEAD' $sw
$ref = Get-Content $gitDir\HEAD 2>$null
$ref = Get-Content $gitDir\HEAD -ErrorAction SilentlyContinue
} else {
dbg 'Trying rev-parse' $sw
$ref = git rev-parse HEAD 2>$null
$ref = safeexec { git rev-parse HEAD }
}

if ($ref -match 'ref: (?<ref>.+)') {
Expand All @@ -81,9 +81,9 @@ function Get-GitBranch($gitDir = $(Get-GitDirectory), [Diagnostics.Stopwatch]$sw
}

dbg 'Inside git directory?' $sw
if ('true' -eq $(git rev-parse --is-inside-git-dir 2>$null)) {
if ('true' -eq $(safeexec { git rev-parse --is-inside-git-dir })) {
dbg 'Inside git directory' $sw
if ('true' -eq $(git rev-parse --is-bare-repository 2>$null)) {
if ('true' -eq $(safeexec { git rev-parse --is-bare-repository })) {
$c = 'BARE:'
} else {
$b = 'GIT_DIR!'
Expand Down Expand Up @@ -118,7 +118,7 @@ function Get-GitStatus($gitDir = (Get-GitDirectory)) {

if($settings.EnableFileStatus -and !$(InDisabledRepository)) {
dbg 'Getting status' $sw
$status = git -c color.status=false status --short --branch 2>$null
$status = safeexec { git -c color.status=false status --short --branch }
} else {
$status = @()
}
Expand Down Expand Up @@ -295,7 +295,7 @@ function Start-SshAgent([switch]$Quiet) {
function Get-SshPath($File = 'id_rsa')
{
$home = Resolve-Path (Invoke-NullCoalescing $Env:HOME ~)
Resolve-Path (Join-Path $home ".ssh\$File") -ErrorAction SilentlyContinue 2> $null
Resolve-Path (Join-Path $home ".ssh\$File") -ErrorAction SilentlyContinue
}

# Add a key to the SSH agent
Expand Down Expand Up @@ -345,17 +345,17 @@ function Stop-SshAgent() {
}

function Update-AllBranches($Upstream = 'master', [switch]$Quiet) {
$head = git rev-parse --abbrev-ref HEAD
git checkout -q $Upstream
$branches = (git branch --no-color --no-merged) | where { $_ -notmatch '^\* ' }
$head = exec { git rev-parse --abbrev-ref HEAD }
exec { git checkout -q $Upstream }
$branches = (exec { git branch --no-color --no-merged }) | where { $_ -notmatch '^\* ' }
foreach ($line in $branches) {
$branch = $line.SubString(2)
if (!$Quiet) { Write-Host "Rebasing $branch onto $Upstream..." }
git rebase -q $Upstream $branch > $null 2> $null
safeexec { git rebase -q $Upstream $branch } > $null
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Why use safeexec here when the surrounding calls all use exec?

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Because the original call had 2> $null, so we should swallow all errors, that's what safeexec does

Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

So it did - thanks for clarifying.

if ($LASTEXITCODE) {
git rebase --abort
exec { git rebase --abort }
Write-Warning "Rebase failed for $branch"
}
}
git checkout -q $head
exec { git checkout -q $head }
}
2 changes: 1 addition & 1 deletion TortoiseGit.ps1
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@ function tgit {
$args[1..$args.length] | % { $newArgs += $_ }
}

& $Global:TortoiseGitSettings.TortoiseGitPath $newArgs
exec { & $Global:TortoiseGitSettings.TortoiseGitPath $newArgs }
}
}

Expand Down
1 change: 1 addition & 0 deletions posh-git.psm1
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
if (Get-Module posh-git) { return }

Push-Location $psScriptRoot
. .\Exec.ps1
.\CheckVersion.ps1 > $null

. .\Utils.ps1
Expand Down