# 构建缓存管理脚本 # 功能:保存和恢复 node_modules 缓存,加速 Docker 构建 # 状态:旧构建缓存方案,不是当前 Git 增量部署的默认前置步骤 param( [ValidateSet('save', 'check', 'clean')] [string]$Action = 'check' ) $CacheDir = ".build-cache" $CacheFile = "$CacheDir/node_modules.tar.gz" $HashFile = "$CacheDir/package-lock.json.hash" # 确保缓存目录存在 if (-not (Test-Path $CacheDir)) { New-Item -ItemType Directory -Path $CacheDir -Force | Out-Null } # 计算 package-lock.json 的哈希值 function Get-PackageLockHash { if (Test-Path "package-lock.json") { $hash = Get-FileHash "package-lock.json" -Algorithm MD5 return $hash.Hash } return $null } # 检查缓存是否有效 function Test-CacheValid { if (-not (Test-Path $CacheFile)) { return $false } if (-not (Test-Path $HashFile)) { return $false } $currentHash = Get-PackageLockHash $cachedHash = Get-Content $HashFile -Raw return $currentHash -eq $cachedHash.Trim() } # 保存缓存 function Save-Cache { Write-Host "📦 保存 node_modules 缓存..." -ForegroundColor Cyan if (-not (Test-Path "node_modules")) { Write-Host "❌ node_modules 不存在,无法保存缓存" -ForegroundColor Red return } # 保存哈希值 $hash = Get-PackageLockHash $hash | Out-File $HashFile -Encoding UTF8 -NoNewline # 压缩 node_modules Write-Host " 压缩中(这可能需要 1-2 分钟)..." -ForegroundColor Yellow tar -czf $CacheFile node_modules 2>&1 | Out-Null if ($LASTEXITCODE -eq 0) { $size = (Get-Item $CacheFile).Length / 1MB Write-Host "✅ 缓存已保存:$([Math]::Round($size, 2)) MB" -ForegroundColor Green Write-Host " 哈希值:$hash" -ForegroundColor Gray } else { Write-Host "❌ 缓存保存失败" -ForegroundColor Red } } # 检查缓存状态 function Check-Cache { Write-Host "🔍 检查构建缓存状态" -ForegroundColor Cyan Write-Host "" $currentHash = Get-PackageLockHash Write-Host "当前 package-lock.json 哈希:$currentHash" -ForegroundColor Gray if (Test-Path $HashFile) { $cachedHash = Get-Content $HashFile -Raw Write-Host "缓存 package-lock.json 哈希:$($cachedHash.Trim())" -ForegroundColor Gray } else { Write-Host "缓存 package-lock.json 哈希:不存在" -ForegroundColor Gray } Write-Host "" if (Test-CacheValid) { $size = (Get-Item $CacheFile).Length / 1MB Write-Host "✅ 缓存有效($([Math]::Round($size, 2)) MB)" -ForegroundColor Green Write-Host " 构建时将使用缓存,预计时间:10-20 秒" -ForegroundColor Green } else { if (Test-Path $CacheFile) { Write-Host "⚠️ 缓存已过期(package-lock.json 已变化)" -ForegroundColor Yellow } else { Write-Host "⚠️ 缓存不存在" -ForegroundColor Yellow } Write-Host " 构建时将重新下载依赖,预计时间:60-90 秒" -ForegroundColor Yellow } } # 清理缓存 function Clean-Cache { Write-Host "🧹 清理构建缓存" -ForegroundColor Cyan if (Test-Path $CacheFile) { Remove-Item $CacheFile -Force Write-Host "✅ 已删除:$CacheFile" -ForegroundColor Green } if (Test-Path $HashFile) { Remove-Item $HashFile -Force Write-Host "✅ 已删除:$HashFile" -ForegroundColor Green } Write-Host "✅ 缓存已清理" -ForegroundColor Green } # 执行操作 switch ($Action) { 'save' { Save-Cache } 'check' { Check-Cache } 'clean' { Clean-Cache } }