# PowerShell 构建脚本 - 支持多平台交叉编译
$ErrorActionPreference = "Stop"
# 切换到项目根目录
$ScriptDir = Split-Path -Parent $MyInvocation.MyCommand.Path
$ProjectRoot = Split-Path -Parent (Split-Path -Parent $ScriptDir)
Set-Location $ProjectRoot
# 创建输出目录
$OutputDir = "target\release"
New-Item -ItemType Directory -Force -Path $OutputDir | Out-Null
Write-Host "开始构建多平台二进制文件...`n" -ForegroundColor Blue
# 定义目标平台
$Targets = @(
"x86_64-unknown-linux-gnu", # Linux x86_64 (glibc)
"aarch64-unknown-linux-gnu", # Linux ARM64 (glibc)
"x86_64-pc-windows-msvc", # Windows x86_64
"x86_64-apple-darwin", # macOS Intel
"aarch64-apple-darwin" # macOS Apple Silicon
)
# 安装目标平台工具链
function Install-Targets {
Write-Host "检查并安装目标平台工具链...`n" -ForegroundColor Yellow
foreach ($target in $Targets) {
$installed = rustup target list --installed | Select-String -Pattern "^$target$"
if (-not $installed) {
Write-Host "安装 $target..." -ForegroundColor Yellow
rustup target add $target
}
}
Write-Host ""
}
# 检查是否安装了 cross 工具
function Test-Cross {
return (Get-Command cross -ErrorAction SilentlyContinue) -ne $null
}
# 构建指定目标平台
function Build-Target {
param($target)
Write-Host "正在构建 $target..." -ForegroundColor Blue
$logFile = "build_$($target -replace '-', '_').log"
# 对于 glibc 目标,优先使用 cross 工具(如果可用)
$useCross = $false
if ($target -like "*linux-gnu*") {
if (Test-Cross) {
$useCross = $true
Write-Host " 使用 cross 工具构建 glibc 目标..." -ForegroundColor Yellow
} else {
Write-Host " 提示: 安装 cross 工具可以更好地支持 glibc 交叉编译" -ForegroundColor Yellow
Write-Host " 安装命令: cargo install cross --git https://github.com/cross-rs/cross" -ForegroundColor Yellow
}
}
try {
if ($useCross) {
cross build --release --target $target 2>&1 | Tee-Object -FilePath $logFile
} else {
cargo build --release --target $target 2>&1 | Tee-Object -FilePath $logFile
}
Write-Host "✓ $target 构建成功`n" -ForegroundColor Green
# 复制二进制文件到输出目录
$binaryName = "secra-plugin-backend"
if ($target -like "*windows*") {
$binaryName = "$binaryName.exe"
}
$sourcePath = "target\$target\release\$binaryName"
$destPath = "$OutputDir\$binaryName-$target"
if (Test-Path $sourcePath) {
Copy-Item $sourcePath $destPath
Write-Host " 二进制文件已复制到: $destPath`n" -ForegroundColor Green
}
}
catch {
Write-Host "✗ $target 构建失败`n" -ForegroundColor Yellow
}
}
# 主函数
function Main {
# 检查是否安装了 rustup
if (-not (Get-Command rustup -ErrorAction SilentlyContinue)) {
Write-Host "错误: 未找到 rustup,请先安装 Rust 工具链" -ForegroundColor Red
exit 1
}
# 安装目标平台
Install-Targets
# 构建所有平台
foreach ($target in $Targets) {
Build-Target $target
}
Write-Host "构建完成!二进制文件位于: $OutputDir" -ForegroundColor Green
Write-Host "构建的文件列表:" -ForegroundColor Blue
Get-ChildItem $OutputDir | Where-Object { $_.Name -like "*secra-plugin-backend*" } | Format-Table Name, Length
}
# 如果提供了参数,只构建指定的平台
if ($args.Count -gt 0) {
Install-Targets
foreach ($target in $args) {
Build-Target $target
}
}
else {
Main
}