如何处理Powershell中的Git错误(最好兼容V5)

问题描述 投票:0回答:1

我以前从未在 PowerShell 中编程过,但我用 JS 编写过不少代码,所以我对编程并不陌生。我正在尝试重新创建 Bash 脚本来自动下载 BitBurner(GitHub 上的开源游戏)并构建它(假设自上次运行脚本以来已有新的提交)。

我现在主要进行测试,以大致了解最终脚本所需的内容,并且我一直致力于处理 Git 错误,我现在关注的主要问题是

fatal: not a git repository (or any of the parent directories): .git
。目前我可以检查 Git 是否未安装以及文件夹是否不存在,但我想再检查一次以查看该文件夹是否是有效的 Git 存储库,以防文件夹为空或 .git 文件夹因任何原因被删除.

我当前的代码是这样的:

$ErrorActionPreference = 'stop';

$bbGamePath = 'G:/BitBurnerGame';

try {
    git --version; # Do nothing with this. This is a quick check to see if Git is installed or not
    Set-Location $bbGamePath;
    if (!(git fetch --dry-run -eq '')) {
         if ($LASTEXITCODE -eq 128) { 
            Write-Error -Message 'Not a valid git repository.'
        };
    }
} catch [System.Management.Automation.CommandNotFoundException] {
    Write-Host -ForegroundColor Red 'Git is not installed!';
    # Should catch the Git Not Installed error, I can probably find this one.
} catch [System.Management.Automation.ItemNotFoundException] {
    Write-Host -ForegroundColor Yellow 'Folder not found!';
    # Should catch the error of the folder not existing, Clone from the repo and continue from here.
} catch {
    Write-Host -ForegroundColor Yellow 'Error 128';
    # Secondary to the above error, should throw if the folder exists but is not a valid git repository folder (AKA the .git folder does NOT exist)
}
Set-Location D:/;

我一直在尝试寻找某种类似于

catch [System.Management.Automation.ItemNotFoundException]
的解决方案,但因为
git
是一个外部 cmdlet,似乎没有办法特别做到这一点?显然我可以保持原样,但我想要一个像前两个捕获一样的解决方案。

顺便说一句,最终的计划是向公众发布这个脚本,这就是我处理所有这些案例的原因。

powershell error-handling automation
1个回答
0
投票

我不确定这是否值得付出努力,但您可以定义一个自定义异常

class
来表示非回购错误条件和
throw
它的一个实例,然后您可以
catch

$ErrorActionPreference = 'Stop'
$bbGamePath = 'G:/BitBurnerGame'

# Custom exception class.
class NotaGitRepoException: Exception {
  NotaGitRepoException([string] $Path) : base("Not a git repository: $Path") {}
}

try {
  # Create a temporary file to capture stderr output in.
  $stderrTempFile = New-TemporaryFile 
  $null = git --version
  Set-Location $bbGamePath
  git fetch --dry-run 2>$stderrTempFile
  if ($LASTEXITCODE -eq 128) { throw ([NotaGitRepoException]::new($PWD)) }
  elseif ($LASTEXITCODE) { throw } # any other error reported by git
}
catch [System.Management.Automation.CommandNotFoundException] {
  Write-Host -ForegroundColor Red 'Git is not installed!'
}
catch [System.Management.Automation.ItemNotFoundException] {
  Write-Host -ForegroundColor Yellow 'Folder not found!'
}
catch [NotaGitRepoException] {
  Write-Host -ForegroundColor Yellow $_
}
catch {
  Write-Host -ForegroundColor Yellow "Unexpected git error ${LASTEXITCODE}: $((Get-Content -Raw -LiteralPath $stderrTempFile).Trim()))"
}
finally {
  # Clean up.
  Remove-Item -ErrorAction Ignore -LiteralPath $stderrTempFile
}
© www.soinside.com 2019 - 2024. All rights reserved.