printServer/scripts/deploy-linux.ps1
2026-03-29 19:32:28 +08:00

143 lines
4.5 KiB
PowerShell

param(
[string]$ConfigPath = 'scripts/deploy.config.json',
[string]$ArtifactPath = '',
[switch]$DryRun
)
$ErrorActionPreference = 'Stop'
$root = Split-Path -Parent (Split-Path -Parent $MyInvocation.MyCommand.Path)
function Assert-Command([string]$Name) {
if (-not (Get-Command $Name -ErrorAction SilentlyContinue)) {
throw "$Name not found in PATH"
}
}
function Run-External([string]$Command, [string[]]$CommandArgs) {
$argPreview = ($CommandArgs | ForEach-Object { if ($_ -match '\s') { '"' + $_ + '"' } else { $_ } }) -join ' '
Write-Host ("[deploy] exec: " + $Command + " " + $argPreview)
& $Command @CommandArgs
if ($LASTEXITCODE -ne 0) {
throw "$Command failed with exit code $LASTEXITCODE"
}
}
function Resolve-Artifact([string]$ExplicitPath, [string]$Pattern) {
if (-not [string]::IsNullOrWhiteSpace($ExplicitPath)) {
$resolved = Resolve-Path -Path $ExplicitPath -ErrorAction SilentlyContinue
if (-not $resolved) {
throw "artifact not found: $ExplicitPath"
}
return $resolved.Path
}
if ([string]::IsNullOrWhiteSpace($Pattern)) {
$Pattern = 'dist/printServer-*-setup.exe'
}
$glob = Join-Path $root $Pattern
$latest = Get-ChildItem -Path $glob -File -ErrorAction SilentlyContinue |
Sort-Object LastWriteTime -Descending |
Select-Object -First 1
if (-not $latest) {
throw "no artifact matched pattern: $Pattern"
}
return $latest.FullName
}
function To-PosixPath([string]$PathValue) {
return $PathValue.Replace('\\', '/')
}
$configFile = Join-Path $root $ConfigPath
if (-not (Test-Path $configFile)) {
throw "deploy config not found: $configFile"
}
$config = Get-Content -Path $configFile -Raw | ConvertFrom-Json
$serverHost = [string]$config.host
$user = [string]$config.user
$sshKeyPath = [string]$config.sshKeyPath
$remoteDir = [string]$config.remoteDir
$baseUrl = [string]$config.baseUrl
$artifactPattern = [string]$config.artifactPattern
$keepReleases = [int]$config.keepReleases
if ($keepReleases -lt 1) {
$keepReleases = 5
}
foreach ($required in @('host', 'user', 'sshKeyPath', 'remoteDir', 'baseUrl')) {
if ([string]::IsNullOrWhiteSpace([string]$config.$required)) {
throw "missing required deploy config field: $required"
}
}
$artifact = Resolve-Artifact -ExplicitPath $ArtifactPath -Pattern $artifactPattern
$fileName = Split-Path -Leaf $artifact
$artifactHash = (Get-FileHash -Path $artifact -Algorithm SHA256).Hash
$artifactVersion = ''
$versionMatch = [regex]::Match($fileName, '(\d+\.\d+\.\d+)')
if ($versionMatch.Success) {
$artifactVersion = $versionMatch.Groups[1].Value
}
Assert-Command 'ssh'
Assert-Command 'scp'
$sshTarget = "$user@$serverHost"
$keyPathPosix = To-PosixPath $sshKeyPath
$sshArgsBase = @(
'-i', $keyPathPosix,
'-o', 'BatchMode=yes',
'-o', 'StrictHostKeyChecking=accept-new'
)
$remoteDirQuoted = "'" + $remoteDir.Replace("'", "'\\''") + "'"
$remoteDirNormalized = $remoteDir.TrimEnd('/')
$remoteFilePath = "$remoteDirNormalized/$fileName"
$remoteSpec = "${sshTarget}:$remoteFilePath"
$minKeepIndex = $keepReleases + 1
Write-Host "[deploy] artifact: $artifact"
Write-Host "[deploy] target: $remoteSpec"
Write-Host "[deploy] keep releases: $keepReleases"
if ($DryRun) {
Write-Host '[deploy] dry-run enabled, no upload executed'
exit 0
}
Run-External -Command 'ssh' -CommandArgs ($sshArgsBase + @($sshTarget, "mkdir -p $remoteDirQuoted"))
Run-External -Command 'scp' -CommandArgs ($sshArgsBase + @($artifact, $remoteSpec))
$cleanupCmd = "cd $remoteDirQuoted ; ls -1t printServer-*-setup.exe 2>/dev/null | tail -n +$minKeepIndex | xargs -r rm -f"
Run-External -Command 'ssh' -CommandArgs ($sshArgsBase + @($sshTarget, $cleanupCmd))
$tempMetaFile = Join-Path $env:TEMP ("printserver-latest-" + [guid]::NewGuid().ToString('N') + ".json")
$metaObject = [PSCustomObject]@{
version = $artifactVersion
file = $fileName
url = ($baseUrl.TrimEnd('/') + '/' + $fileName)
sha256 = $artifactHash
publishedAtUtc = (Get-Date).ToUniversalTime().ToString('yyyy-MM-ddTHH:mm:ssZ')
}
$metaObject | ConvertTo-Json -Depth 3 | Set-Content -Path $tempMetaFile -Encoding UTF8
try {
$remoteMetaSpec = "${sshTarget}:$remoteDirNormalized/latest.json"
Run-External -Command 'scp' -CommandArgs ($sshArgsBase + @($tempMetaFile, $remoteMetaSpec))
} finally {
if (Test-Path $tempMetaFile) {
Remove-Item -Path $tempMetaFile -Force
}
}
$link = $baseUrl.TrimEnd('/') + '/' + $fileName
Write-Host "[deploy] done"
Write-Host "[deploy] url: $link"