<# .SYNOPSIS 一键提交并推送当前项目到 git 远程仓库。 .DESCRIPTION 面向「本地改完 → 提交 → 推到 Gitea」这一条固定流程。 提交信息统一为「更新:yyyy-MM-dd HH:mm」格式。 认证方式按以下优先级自动选择: 1. 本机已由 git 凭据助手记住的凭据(推荐,日常免密) 2. 环境变量 GIT_TOKEN / GIT_PASSWORD(令牌或密码) 脚本不会把密码写进 .git/config:推送完成后无论成败都会把远程地址 还原成不带凭据的形式。 .PARAMETER Message 自定义提交信息。不指定则用「更新:yyyy-MM-dd HH:mm」。 .PARAMETER Path 只提交指定文件或目录(相对当前目录)。不指定则提交全部变更。 .PARAMETER NoPush 只提交不推送。 .PARAMETER Force 强制推送(--force-with-lease),用于需要改写远程历史的场景。 .PARAMETER Remote 远程名称,默认 origin。 .EXAMPLE .\git-push.ps1 提交全部变更并推送,提交信息自动带当前时间。 .EXAMPLE .\git-push.ps1 -Path "static/" 只提交 static 目录。 .EXAMPLE .\git-push.ps1 -Message "修复批次筛选残留" 用自定义提交信息。 #> [CmdletBinding()] param( [string]$Message, [string]$Path, [switch]$NoPush, [switch]$Force, [string]$Remote = "origin" ) $ErrorActionPreference = "Stop" Set-StrictMode -Version Latest # git 可能没进 PATH,这里补上常见安装位置 function Initialize-GitPath { if (Get-Command git -ErrorAction SilentlyContinue) { return } $candidates = @( "C:\Program Files\Git\cmd", "C:\Program Files\Git\ucrt64\bin", "C:\Program Files (x86)\Git\cmd", "$env:LOCALAPPDATA\Programs\Git\cmd" ) foreach ($c in $candidates) { if (Test-Path (Join-Path $c "git.exe")) { $env:Path += ";$c" if (Get-Command git -ErrorAction SilentlyContinue) { return } } } throw "未找到 git,请先安装 Git for Windows 并加入 PATH" } function Write-Step($text) { Write-Host "==> $text" -ForegroundColor Cyan } function Write-Ok($text) { Write-Host " $text" -ForegroundColor Green } function Write-Warn2($text){ Write-Host " $text" -ForegroundColor Yellow } # 推送失败时读取错误输出,用于识别「远程有本地没有的提交」这类情况 function Invoke-GitCapture { param([string[]]$Args) $out = & git @Args 2>&1 return @{ Output = ($out | Out-String).Trim(); Code = $LASTEXITCODE } } Initialize-GitPath # ---------------------------------------------------------------- 前置校验 Write-Step "检查仓库状态" if (-not (Test-Path ".git")) { throw "当前目录不是 git 仓库。请先在项目根目录执行 git init" } $remoteUrl = (& git remote get-url $Remote 2>$null) if ($LASTEXITCODE -ne 0 -or -not $remoteUrl) { throw "远程 '$Remote' 未配置。请先执行:git remote add $Remote <仓库地址>" } Write-Ok "远程 $Remote = $remoteUrl" $branch = (& git branch --show-current).Trim() if (-not $branch) { # 可能是空仓库首次提交,退回到 HEAD 的存在性判断 $branch = "main" Write-Warn2 "当前不在任何分支上,将使用 main" } Write-Ok "当前分支 = $branch" # ---------------------------------------------------------------- 暂存 Write-Step "暂存变更" if ($Path) { if (-not (Test-Path $Path)) { throw "指定路径不存在:$Path" } & git add -- $Path } else { & git add -A } if ($LASTEXITCODE -ne 0) { throw "git add 失败" } # 强制成数组:git 只返回一行时 PowerShell 会给出字符串而非数组,导致 .Count 报错 $staged = @((& git diff --cached --name-only) | Where-Object { $_ }) if ($staged.Count -eq 0) { Write-Warn2 "没有需要提交的变更,流程结束" exit 0 } $shownStaged = $staged | Select-Object -First 50 $shownStaged | ForEach-Object { Write-Ok " $_" } if ($staged.Count -gt 50) { Write-Warn2 "(共 $($staged.Count) 个文件,以上仅列出前 50 个)" } # ---------------------------------------------------------------- 提交 Write-Step "创建提交" if (-not $Message) { $Message = "更新:{0}" -f (Get-Date -Format "yyyy-MM-dd HH:mm") } Write-Ok "提交信息 = $Message" # 提交信息用 -F - 从标准输入读,避免中文和特殊字符被 shell 二次解析 $Message | & git commit -q -F - if ($LASTEXITCODE -ne 0) { throw "git commit 失败" } $head = (& git log --format="%h %s" -n 1).Trim() Write-Ok $head if ($NoPush) { Write-Step "已指定 -NoPush,停止在提交这一步" exit 0 } # ---------------------------------------------------------------- 认证准备 # 目的:把带凭据的 URL 仅临时用于本次 push,结束后还原,避免明文落进 .git/config $pushUrl = $remoteUrl $tempCred = $false $helper = (& git config --get credential.helper 2>$null) $hasHelper = ($LASTEXITCODE -eq 0 -and $helper) if (-not $hasHelper) { $cred = $null if ($env:GIT_TOKEN) { $cred = "zbc:$($env:GIT_TOKEN)" } elseif ($env:GIT_PASSWORD) { $cred = "zbc:$($env:GIT_PASSWORD)" } elseif ($env:GIT_USER) { $cred = $env:GIT_USER } if ($cred -and $remoteUrl -match '^https://(?:[^@/]*@)?(.*)$') { $hostPart = $Matches[1] $pushUrl = "https://$cred@$hostPart" $tempCred = $true Write-Warn2 "未配置凭据助手,本次使用环境变量中的凭据推送" } } # ---------------------------------------------------------------- 推送 Write-Step "推送到远程" $pushArgs = @("push") if ($Force) { $pushArgs += "--force-with-lease" } $pushArgs += @($pushUrl, $branch) $result = Invoke-GitCapture -Args $pushArgs # 输出里若回显了带凭据的地址,遮蔽掉 $shown = $result.Output if ($tempCred) { $escaped = [regex]::Escape(($pushUrl -replace '^https://[^@]*@', 'https://')) $shown = $shown -replace [regex]::Escape($pushUrl), 'https://<已隐藏凭据>' } if ($result.Code -eq 0) { Write-Ok $shown } else { Write-Warn2 $shown # 常见失败:远程有本地没有的提交,先拉再推 if ($shown -match 'non-fast-forward|fetch first|rejected') { Write-Step "远程有新提交,先合并再重试" & git pull $Remote $branch --no-rebase --no-edit if ($LASTEXITCODE -ne 0) { throw "git pull 失败,请手动处理冲突" } $pushArgs = @("push") if ($Force) { $pushArgs += "--force-with-lease" } $pushArgs += @($pushUrl, $branch) $result = Invoke-GitCapture -Args $pushArgs if ($result.Code -ne 0) { Write-Warn2 $result.Output throw "推送仍然失败" } Write-Ok "重试推送成功" } else { throw "推送失败" } } # ---------------------------------------------------------------- 收尾 if ($tempCred) { Write-Step "清理临时凭据" & git remote set-url $Remote $remoteUrl 2>$null | Out-Null $leftover = (& git config --local --get-regexp "remote\.$Remote\.url" 2>$null) if ($leftover -match '@') { Write-Warn2 "远程地址中可能仍有凭据,请手动检查 .git/config" } else { Write-Ok "远程地址已还原为不带凭据的形式" } } Write-Step "完成" & git log --oneline -n 3 | ForEach-Object { Write-Ok $_ } & git status --short | ForEach-Object { if ($_) { Write-Ok $_ } }