Skip to content

Commit 4ef3c23

Browse files
committed
fix: enhance error handling in github-sync-main.ps1
Added error handling for git commands in the sync process to ensure that failures during 'git switch', 'git pull', and 'git push' are logged and the script exits gracefully. This improves the robustness of the synchronization script.
1 parent 0918426 commit 4ef3c23

1 file changed

Lines changed: 23 additions & 1 deletion

File tree

scripts/github-sync-main.ps1

Lines changed: 23 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,7 @@ param(
77
)
88

99
$ErrorActionPreference = "Stop"
10+
# $ErrorActionPreference does not apply to external commands (e.g. git). We check $LASTEXITCODE after each git call in the -Sync block.
1011
$repoRoot = (Get-Item $PSScriptRoot).Parent.FullName
1112
Set-Location $repoRoot
1213

@@ -30,13 +31,34 @@ $out += ""
3031
if ($Sync) {
3132
$out += "=== Syncing main ==="
3233
git switch main 2>&1 | ForEach-Object { $out += $_ }
34+
if ($LASTEXITCODE -ne 0) {
35+
$out += "ERROR: git switch main failed (exit $LASTEXITCODE). Sync aborted to avoid running pull/push on current branch."
36+
$text = $out -join "`r`n"
37+
$text | Out-File -FilePath $logPath -Encoding utf8
38+
Write-Host $text
39+
exit $LASTEXITCODE
40+
}
3341
git pull origin main --rebase 2>&1 | ForEach-Object { $out += $_ }
42+
if ($LASTEXITCODE -ne 0) {
43+
$out += "ERROR: git pull failed (exit $LASTEXITCODE)."
44+
$text = $out -join "`r`n"
45+
$text | Out-File -FilePath $logPath -Encoding utf8
46+
Write-Host $text
47+
exit $LASTEXITCODE
48+
}
3449
git push origin main 2>&1 | ForEach-Object { $out += $_ }
50+
if ($LASTEXITCODE -ne 0) {
51+
$out += "ERROR: git push failed (exit $LASTEXITCODE)."
52+
$text = $out -join "`r`n"
53+
$text | Out-File -FilePath $logPath -Encoding utf8
54+
Write-Host $text
55+
exit $LASTEXITCODE
56+
}
3557
$out += "Done."
3658
} else {
3759
$out += "To sync main (pull + push), run: .\scripts\github-sync-main.ps1 -Sync"
3860
}
3961

4062
$text = $out -join "`r`n"
4163
$text | Out-File -FilePath $logPath -Encoding utf8
42-
Write-Host $text
64+
Write-Host $text

0 commit comments

Comments
 (0)