const { execSync } = require('child_process'); const path = require('path'); const fs = require('fs'); const os = require('os'); const isWindows = os.platform() === 'win32'; // 配置目标Git仓库信息 const config = { repoUrl: 'http://git2.haodian.cn/xiaoyu/hcb.git', // 目标仓库地址 branch: 'master', // 目标分支 distPath: path.resolve(__dirname, './dist'), // 构建产物目录 // commitMessage: `Auto-deploy at ${new Date().toISOString()}` commitMessage: `Auto-deploy at ${new Date().toLocaleString('sv-SE')}`, // 提交信息 gitPath: isWindows ? 'E:\\' : '/Users/0fun/work/', //仓库本地保存路径 dirName: 'hcb' //仓库文件夹名 }; /** * 同步递归复制目录及其内容(覆盖目标) * @param {string} source - 源目录路径 * @param {string} target - 目标目录路径 */ function copyDirectorySync(source, target) { // 检查源路径是否存在 if (!fs.existsSync(source)) { throw new Error(`源路径不存在: ${source}`); } // 确保目标目录存在 if (!fs.existsSync(target)) { fs.mkdirSync(target, { recursive: true }); } // 读取源目录内容 const entries = fs.readdirSync(source, { withFileTypes: true }); // 处理每个文件/目录 for (const entry of entries) { const sourcePath = path.join(source, entry.name); const targetPath = path.join(target, entry.name); if (entry.isDirectory()) { // 递归复制子目录 copyDirectorySync(sourcePath, targetPath); } else { // 复制文件(覆盖现有文件) fs.copyFileSync(sourcePath, targetPath); } } } // try { // const sourceDir = './dist'; // const targetDir = 'E:\\pinan_dist'; // // copyDirectorySync(sourceDir, targetDir); // console.log('复制完成!'); // } catch (err) { // console.error('复制过程中出错:', err); // } // process.exit(0); try { // 检查dist目录是否存在 if (!fs.existsSync(config.distPath)) { throw new Error('dist目录不存在,请先执行构建命令'); } const gitRealPath = path.join(config.gitPath, config.dirName); console.log('仓库本地路径:', gitRealPath); if (!fs.existsSync(config.gitPath)) { console.log('创建git仓库目录'); fs.mkdirSync(config.gitPath, { recursive: true }); } if (!fs.existsSync(path.join(gitRealPath, '.git'))) { console.log('初始化git仓库'); process.chdir(config.gitPath); execSync( `git clone --single-branch -b master ${config.repoUrl} ${config.dirName}` ); } if (!fs.existsSync(path.join(gitRealPath, '.git'))) { throw new Error('仓库初始化失败,请检查仓库路径是否正确'); } process.chdir(gitRealPath); console.log('更新仓库'); execSync(`git pull --rebase origin ${config.branch}`); //同步递归复制 copyDirectorySync(config.distPath, gitRealPath); console.log(`${config.distPath} 复制到 ${gitRealPath}`); // process.chdir(config.distPath); // 添加所有文件 execSync('git add .'); // 提交更改 try { execSync(`git commit -m "${config.commitMessage}"`); } catch (e) { console.log(e); console.log('没有需要提交的更改'); process.exit(0); } // 推送到目标仓库 execSync(`git push origin ${config.branch}`); console.log('推送仓库成功!'); process.exit(0); } catch (error) { console.error('推送仓库失败:', error.message); process.exit(1); }