[CmdletBinding()] param( [switch]$TestOnly, [switch]$Clean, [switch]$SkipFormat ) $ErrorActionPreference = "Stop" $ProxyUrl = "http://127.0.0.1:10808" $env:HTTP_PROXY = $ProxyUrl $env:HTTPS_PROXY = $ProxyUrl $env:NO_PROXY = "localhost,127.0.0.1" $ProjectRoot = $PSScriptRoot $DistDir = Join-Path $ProjectRoot "dist" $OutputPath = Join-Path $DistDir "GoWallpaper.exe" $ResourcePath = Join-Path $ProjectRoot "rsrc_windows_amd64.syso" function Invoke-External { param( [Parameter(Mandatory = $true)] [string]$Command, [Parameter(Mandatory = $true)] [string[]]$Arguments ) & $Command @Arguments if ($LASTEXITCODE -ne 0) { throw "命令执行失败(退出码 $LASTEXITCODE):$Command $($Arguments -join ' ')" } } Push-Location $ProjectRoot try { if ($Clean) { if (Test-Path -LiteralPath $DistDir) { Remove-Item -LiteralPath $DistDir -Recurse -Force } if (Test-Path -LiteralPath $ResourcePath) { Remove-Item -LiteralPath $ResourcePath -Force } Write-Host "清理完成。" if (-not $TestOnly) { return } } if (-not (Get-Command go -ErrorAction SilentlyContinue)) { throw "未找到 Go,请先安装 Go 并将其加入 PATH。" } if (-not $SkipFormat) { $GoFiles = @(Get-ChildItem -LiteralPath $ProjectRoot -Filter "*.go" -File | ForEach-Object { $_.FullName }) if ($GoFiles.Count -gt 0) { Write-Host "[1/4] 格式化 Go 源码..." Invoke-External -Command "gofmt" -Arguments (@("-w") + $GoFiles) } } Write-Host "[2/4] 运行测试..." Invoke-External -Command "go" -Arguments @("test", "./...") if ($TestOnly) { Write-Host "测试通过。" return } if (-not (Get-Command rsrc -ErrorAction SilentlyContinue)) { throw "未找到 rsrc。请先安装:go install github.com/akavel/rsrc@latest" } Write-Host "[3/4] 生成 Windows manifest 资源..." Invoke-External -Command "rsrc" -Arguments @("-manifest", "app.manifest", "-o", $ResourcePath) if (-not (Test-Path -LiteralPath $DistDir)) { New-Item -ItemType Directory -Path $DistDir | Out-Null } Write-Host "[4/4] 构建 Windows GUI 程序..." Invoke-External -Command "go" -Arguments @("build", "-ldflags=-H windowsgui -s -w", "-trimpath", "-o", $OutputPath, ".") Write-Host "构建完成:$OutputPath" } finally { Pop-Location }