#!/bin/bash # 生产环境磁盘长期优化脚本 # 作者:张翔 # 日期:2026-03-30 echo "🚀 开始执行生产环境磁盘长期优化..." # 1. 优化Git仓库(清理大文件历史) echo "🔍 优化Git仓库..." if [ -d ".git" ]; then # 查找Git历史中的大文件 echo "📊 Git历史大文件分析:" git rev-list --objects --all | \ git cat-file --batch-check='%(objecttype) %(objectname) %(objectsize) %(rest)' | \ sed -n 's/^blob //p' | \ sort --numeric-sort --key=2 | \ tail -10 | \ cut -c 1-12,41- | \ $(command -v gnumfmt || echo numfmt) --field=2 --to=iec-i --suffix=B --padding=7 --round=nearest echo "💡 如需清理Git历史大文件,请运行:" echo " git filter-branch --tree-filter 'rm -f 大文件路径' HEAD" echo " git reflog expire --expire=now --all && git gc --prune=now --aggressive" fi # 2. 优化依赖包管理 echo "📦 优化依赖包管理..." if [ -f "package.json" ]; then # 检查是否有未使用的依赖 echo "🔍 检查未使用的依赖..." npx depcheck 2>/dev/null || echo "⚠️ depcheck未安装,跳过依赖检查" # 检查是否有重复依赖 echo "🔍 检查重复依赖..." npm ls 2>/dev/null | grep "deduped" || echo "✅ 依赖包已优化" # 建议:使用pnpm或yarn进行依赖管理以减少磁盘占用 echo "💡 建议使用pnpm替代npm,可节省40-50%磁盘空间" fi # 3. 配置构建优化 echo "🔧 配置构建优化..." if [ -f "next.config.ts" ]; then echo "💡 Next.js构建优化建议:" echo " - 启用构建缓存:配置experimental.turbo.buildCaching" echo " - 优化图片处理:使用next/image的优化配置" echo " - 启用代码分割:合理配置dynamic imports" fi # 4. 设置自动化清理机制 echo "🤖 设置自动化清理机制..." # 创建定时清理脚本 cat > /tmp/cleanup-cron.sh << 'EOF' #!/bin/bash # 自动化磁盘清理脚本(可加入crontab) LOG_FILE="./logs/cleanup-$(date +%Y%m%d).log" echo "[$(date)] 开始自动化清理" >> "$LOG_FILE" # 清理构建缓存 find . -name "*.tsbuildinfo" -delete 2>/dev/null find . -name "build.log" -delete 2>/dev/null # 清理测试报告(保留最近3天) find . -name "playwright-report" -type d -mtime +3 -exec rm -rf {} \; 2>/dev/null find . -name "coverage" -type d -mtime +3 -exec rm -rf {} \; 2>/dev/null find . -name "test-results" -type d -mtime +3 -exec rm -rf {} \; 2>/dev/null # 清理日志文件(保留最近7天) find ./logs -name "*.log" -type f -mtime +7 -delete 2>/dev/null echo "[$(date)] 清理完成" >> "$LOG_FILE" EOF chmod +x /tmp/cleanup-cron.sh mv /tmp/cleanup-cron.sh ./scripts/auto-cleanup.sh echo "✅ 自动化清理脚本已创建:./scripts/auto-cleanup.sh" # 5. 配置.gitignore优化 echo "📋 优化.gitignore配置..." if [ -f ".gitignore" ]; then # 检查是否已包含必要的忽略规则 if ! grep -q "playwright-report" .gitignore; then echo "playwright-report" >> .gitignore echo "✅ 已添加playwright-report到.gitignore" fi if ! grep -q "coverage" .gitignore; then echo "coverage" >> .gitignore echo "✅ 已添加coverage到.gitignore" fi if ! grep -q "test-results" .gitignore; then echo "test-results" >> .gitignore echo "✅ 已添加test-results到.gitignore" fi if ! grep -q "*.tsbuildinfo" .gitignore; then echo "*.tsbuildinfo" >> .gitignore echo "✅ 已添加*.tsbuildinfo到.gitignore" fi fi # 6. 显示优化建议 echo "" echo "📊 长期优化建议汇总:" echo "✅ 1. Git优化:清理历史大文件,使用git filter-branch" echo "✅ 2. 依赖管理:使用pnpm替代npm,定期检查未使用依赖" echo "✅ 3. 构建优化:配置Next.js构建缓存和代码分割" echo "✅ 4. 自动化:设置定时清理脚本,避免磁盘占用累积" echo "✅ 5. 配置优化:完善.gitignore,避免提交大文件" echo "" echo "🚀 长期优化方案已配置完成!" echo "💡 下一步:运行立即清理脚本,然后实施长期优化措施"