/** * 恢复脚本 - 从备份目录恢复源 JS 文件 * * 使用方法: * node restore.js * * 此脚本会从 .backup 目录恢复所有备份的源文件 */ const fs = require('fs'); const path = require('path'); // 获取项目根目录(脚本在 scripts/encrypt 目录下,需要向上两级) const projectRoot = path.resolve(__dirname, '../..'); // 备份目录 const backupDir = path.join(projectRoot, '.backup'); const backupInfoPath = path.join(backupDir, 'backup-info.json'); console.log('开始恢复源文件...\n'); // 检查备份目录是否存在 if (!fs.existsSync(backupDir)) { console.error('❌ 错误:备份目录不存在!'); console.error(` 路径: ${backupDir}`); console.error('\n💡 提示:如果没有备份,请从 Git 仓库恢复文件'); process.exit(1); } // 检查备份信息文件 if (!fs.existsSync(backupInfoPath)) { console.warn('⚠️ 警告:备份信息文件不存在,将尝试恢复所有 .js 文件\n'); } let restoredCount = 0; let notFoundCount = 0; let errorCount = 0; // 读取备份信息 let filesToRestore = []; if (fs.existsSync(backupInfoPath)) { try { const backupInfo = JSON.parse(fs.readFileSync(backupInfoPath, 'utf8')); filesToRestore = backupInfo.files || []; console.log(`📋 从备份信息读取到 ${filesToRestore.length} 个文件\n`); } catch (error) { console.warn(`⚠️ 无法读取备份信息文件: ${error.message}\n`); } } // 如果没有备份信息,扫描备份目录 if (filesToRestore.length === 0) { console.log('📂 扫描备份目录...\n'); function scanDir(dir, baseDir = '') { const files = []; const entries = fs.readdirSync(dir, { withFileTypes: true }); for (const entry of entries) { const fullPath = path.join(dir, entry.name); const relativePath = path.join(baseDir, entry.name); if (entry.isDirectory()) { files.push(...scanDir(fullPath, relativePath)); } else if (entry.isFile() && entry.name.endsWith('.js')) { files.push(relativePath); } } return files; } filesToRestore = scanDir(backupDir); console.log(`📋 扫描到 ${filesToRestore.length} 个备份文件\n`); } if (filesToRestore.length === 0) { console.error('❌ 错误:没有找到任何备份文件!'); process.exit(1); } // 恢复文件 filesToRestore.forEach(filePath => { try { const backupPath = path.join(backupDir, filePath); const restorePath = path.join(projectRoot, filePath); // 检查备份文件是否存在 if (!fs.existsSync(backupPath)) { console.warn(`⚠️ 备份文件不存在: ${filePath}`); notFoundCount++; return; } // 确保目标目录存在 const restoreDir = path.dirname(restorePath); if (!fs.existsSync(restoreDir)) { fs.mkdirSync(restoreDir, { recursive: true }); } // 复制文件 fs.copyFileSync(backupPath, restorePath); console.log(`✅ 已恢复: ${filePath}`); restoredCount++; } catch (error) { console.error(`❌ 恢复失败: ${filePath}`); console.error(` 错误: ${error.message}`); errorCount++; } }); console.log('\n' + '='.repeat(50)); console.log(`恢复完成!`); console.log(` 已恢复: ${restoredCount}`); console.log(` 未找到: ${notFoundCount}`); console.log(` 错误: ${errorCount}`); console.log('='.repeat(50)); if (errorCount > 0) { console.log('\n⚠️ 有文件恢复失败,请检查错误信息'); process.exit(1); } else { console.log('\n✅ 恢复完成!源文件已从备份目录恢复'); console.log('\n💡 提示:'); console.log(' - 备份文件仍保留在 .backup 目录'); console.log(' - 如需删除备份,请手动删除 .backup 目录'); }