'use strict'; const fs = require('node:fs'); const path = require('node:path'); const { spawnSync } = require('node:child_process'); const ROOT = path.resolve(__dirname, '..'); const LOCAL_CONFIG_PATH = path.join(ROOT, 'config', 'deploy.config.local.cjs'); const EXAMPLE_CONFIG_PATH = path.join(ROOT, 'config', 'deploy.config.example.cjs'); const DEFAULT_ENV = 'production'; const DEFAULT_EGG_MINIMAL_INCLUDE_PATHS = [ 'app.js', 'app/**', 'package.json', 'package-lock.json', ]; const DEFAULT_POST_DEPLOY_COMMANDS = [ 'npm install --production', 'npm run stop || true', 'npm start', ]; function quoteForBash(value) { return `'${String(value).replace(/'/g, `'"'"'`)}'`; } function isGitAvailable() { const result = spawnSync('git', [ 'rev-parse', '--git-dir' ], { cwd: ROOT, encoding: 'utf8', stdio: 'pipe', shell: false, }); return result.status === 0; } /** * 检查是否有未提交的更改 */ function hasUncommittedChanges() { if (!isGitAvailable()) return false; const output = runCommandSafe('git', [ 'status', '--porcelain' ]); return output.trim().length > 0; } function runCommand(command, args, options = {}) { const result = spawnSync(command, args, { cwd: options.cwd || ROOT, encoding: 'utf8', stdio: options.stdio || 'pipe', shell: false, }); if (result.error) { throw result.error; } if (result.status !== 0) { const stderr = (result.stderr || '').trim(); const stdout = (result.stdout || '').trim(); throw new Error(stderr || stdout || `${command} exited with code ${result.status}`); } return (result.stdout || '').trim(); } /** * 安全执行命令,失败时返回空字符串而不是抛出异常 */ function runCommandSafe(command, args, options = {}) { const result = spawnSync(command, args, { cwd: options.cwd || ROOT, encoding: 'utf8', stdio: 'pipe', shell: false, }); if (result.error || result.status !== 0) { return ''; } return (result.stdout || '').trim(); } function ensureCommandAvailable(command, installHint) { const result = spawnSync(command, [], { cwd: ROOT, encoding: 'utf8', stdio: 'pipe', shell: false, }); if (result.error && result.error.code === 'ENOENT') { throw new Error(`${command} 不可用。${installHint}`); } } function getNowStamp() { const now = new Date(); const pad = value => String(value).padStart(2, '0'); return `${now.getFullYear()}${pad(now.getMonth() + 1)}${pad(now.getDate())}${pad(now.getHours())}${pad(now.getMinutes())}${pad(now.getSeconds())}`; } function ensureTempDeployDir() { const tempDir = path.join(ROOT, 'tmp', 'deploy'); fs.mkdirSync(tempDir, { recursive: true }); return tempDir; } function isPlaceholder(value) { if (!value) { return true; } return String(value).includes('__FILL_'); } function normalizeDeployConfig(config, envName) { const deployRoot = config.deployRoot || '/www/wwwroot/services.printer'; const privateKeyPath = config.privateKeyPath ? path.resolve(ROOT, config.privateKeyPath) : ''; const sshOptions = Array.isArray(config.sshOptions) ? [ ...config.sshOptions ] : []; const preserveDirs = Array.isArray(config.preserveDirs) ? [ ...config.preserveDirs ] : [ 'config' ]; if (!preserveDirs.includes('config')) { preserveDirs.push('config'); } if (!sshOptions.some(option => /^IdentitiesOnly=/i.test(option))) { sshOptions.push('IdentitiesOnly=yes'); } if (!sshOptions.some(option => /^PreferredAuthentications=/i.test(option))) { sshOptions.push('PreferredAuthentications=publickey'); } if (!sshOptions.some(option => /^PubkeyAuthentication=/i.test(option))) { sshOptions.push('PubkeyAuthentication=yes'); } if (!sshOptions.some(option => /^PasswordAuthentication=/i.test(option))) { sshOptions.push('PasswordAuthentication=no'); } if (!sshOptions.some(option => /^KbdInteractiveAuthentication=/i.test(option))) { sshOptions.push('KbdInteractiveAuthentication=no'); } if (!sshOptions.some(option => /^BatchMode=/i.test(option))) { sshOptions.push('BatchMode=yes'); } if (!sshOptions.some(option => /^ConnectTimeout=/i.test(option))) { sshOptions.push('ConnectTimeout=10'); } const configuredPostDeployCommands = Array.isArray(config.postDeployCommands) && config.postDeployCommands.length > 0 ? [ ...config.postDeployCommands ] : [ ...DEFAULT_POST_DEPLOY_COMMANDS ]; if (!configuredPostDeployCommands.some(cmd => /^npm\s+install\s+--production(?:\s|$)/i.test(String(cmd).trim()))) { configuredPostDeployCommands.unshift('npm install --production'); } return { envName, host: config.host, port: Number(config.port || 22), username: config.username, privateKeyPath, deployRoot, controlDir: `${deployRoot}/.deploy`, incomingDir: `${deployRoot}/.deploy/incoming`, backupDir: `${deployRoot}/.deploy/backups`, stateDir: `${deployRoot}/.deploy/state`, sharedDirs: Array.isArray(config.sharedDirs) ? config.sharedDirs : [ 'logs', 'run', 'tmp' ], preserveDirs, keepBackups: Number(config.keepBackups || 5), preDeployCommands: Array.isArray(config.preDeployCommands) ? config.preDeployCommands : [], postDeployCommands: configuredPostDeployCommands, healthCheckUrl: config.healthCheckUrl || '', deployIncludePaths: Array.isArray(config.deployIncludePaths) && config.deployIncludePaths.length > 0 ? config.deployIncludePaths : DEFAULT_EGG_MINIMAL_INCLUDE_PATHS, deployExcludePaths: Array.isArray(config.deployExcludePaths) ? config.deployExcludePaths : [ 'config/**' ], sshOptions, }; } function validateDeployConfig(config, configPath, envName) { if (!config) { throw new Error(`${configPath} 中未找到 ${envName} 配置。`); } const missing = []; if (isPlaceholder(config.host)) missing.push('host'); if (isPlaceholder(config.username)) missing.push('username'); if (isPlaceholder(config.privateKeyPath)) missing.push('privateKeyPath'); if (missing.length > 0) { throw new Error(`请先完善 SSH 配置字段: ${missing.join(', ')}。配置文件: ${configPath}`); } const resolvedPrivateKeyPath = path.resolve(ROOT, config.privateKeyPath); if (!fs.existsSync(resolvedPrivateKeyPath)) { throw new Error(`SSH 私钥不存在: ${resolvedPrivateKeyPath}。请先修正 config/deploy.config.local.cjs 中的 privateKeyPath。`); } } function loadDeployConfig(envName = DEFAULT_ENV) { if (!fs.existsSync(LOCAL_CONFIG_PATH)) { throw new Error(`缺少本地部署配置 ${LOCAL_CONFIG_PATH}。请复制 ${EXAMPLE_CONFIG_PATH} 并填入 SSH 信息。`); } delete require.cache[LOCAL_CONFIG_PATH]; const loaded = require(LOCAL_CONFIG_PATH); const config = loaded[envName]; validateDeployConfig(config, LOCAL_CONFIG_PATH, envName); return normalizeDeployConfig(config, envName); } function buildSshBaseArgs(config) { const args = [ '-p', String(config.port), '-i', config.privateKeyPath ]; for (const option of config.sshOptions) { args.push('-o', option); } return args; } function runSsh(config, remoteScript, options = {}) { const args = [ ...buildSshBaseArgs(config), `${config.username}@${config.host}`, `bash -c ${quoteForBash(remoteScript)}`, ]; return runCommand('ssh', args, { stdio: options.stdio || 'inherit', }); } function runScp(config, localPath, remotePath) { const args = [ '-P', String(config.port), '-i', config.privateKeyPath ]; for (const option of config.sshOptions) { args.push('-o', option); } args.push( localPath, `${config.username}@${config.host}:${remotePath}`, ); return runCommand('scp', args, { stdio: 'inherit' }); } function normalizeRule(rule) { return String(rule || '').replace(/\\/g, '/').trim(); } function pathMatchesRule(filePath, rule) { const normalizedPath = String(filePath || '').replace(/\\/g, '/'); const normalizedRule = normalizeRule(rule); if (!normalizedRule) { return false; } if (normalizedRule.endsWith('/**')) { const prefix = normalizedRule.slice(0, -3); return normalizedPath === prefix || normalizedPath.startsWith(`${prefix}/`); } if (normalizedRule.endsWith('/')) { return normalizedPath.startsWith(normalizedRule); } return normalizedPath === normalizedRule; } /** * 递归遍历目录获取所有文件(非 git 模式回退方案) */ function walkDir(dir, basePath) { const results = []; const entries = fs.readdirSync(dir, { withFileTypes: true }); for (const entry of entries) { const fullPath = path.join(dir, entry.name); const relativePath = path.relative(basePath, fullPath).replace(/\\/g, '/'); if (entry.isDirectory()) { const skipDirs = [ '.git', 'node_modules', 'logs', 'run', 'tmp', '.deploy', '.vscode', '.idea' ]; if (skipDirs.includes(entry.name)) continue; results.push(...walkDir(fullPath, basePath)); } else { results.push(relativePath); } } return results; } function listDeployableFiles(config) { const includeRules = Array.isArray(config && config.deployIncludePaths) ? config.deployIncludePaths : DEFAULT_EGG_MINIMAL_INCLUDE_PATHS; const excludeRules = Array.isArray(config && config.deployExcludePaths) ? config.deployExcludePaths : [ 'config/**' ]; let allFiles; if (isGitAvailable()) { const output = runCommandSafe('git', [ 'ls-files', '--cached', '--others', '--exclude-standard' ]); allFiles = output .split(/\r?\n/) .map(item => item.trim()) .filter(Boolean) .filter(item => !item.startsWith('.git/')) .filter(item => fs.existsSync(path.join(ROOT, item))); } else { console.warn('[WARN] 未检测到 Git 仓库,使用文件系统遍历模式。建议初始化 Git 仓库以获得更精确的发布文件列表。'); allFiles = walkDir(ROOT, ROOT); } return Array.from(new Set( allFiles .filter(item => includeRules.some(rule => pathMatchesRule(item, rule))) .filter(item => !excludeRules.some(rule => pathMatchesRule(item, rule))) )); } function buildArchive(stamp, config) { const tempDir = ensureTempDeployDir(); const listPath = path.join(tempDir, `deploy-files-${stamp}.txt`); const archivePath = path.join(tempDir, `release-${stamp}.tar.gz`); const files = listDeployableFiles(config); if (files.length === 0) { throw new Error('git ls-files 未返回可发布文件,无法生成发布包。'); } fs.writeFileSync(listPath, files.join('\n') + '\n', 'utf8'); runCommand('tar', [ '-czf', archivePath, '-T', listPath ], { stdio: 'inherit' }); return { archivePath, listPath, }; } function buildRemoteCleanupGuard(sharedDirs, preserveDirs = []) { const preserved = [ '.deploy', ...sharedDirs, ...preserveDirs ]; return preserved.map(item => `! -name ${quoteForBash(item)}`).join(' '); } module.exports = { ROOT, buildArchive, buildRemoteCleanupGuard, ensureCommandAvailable, getNowStamp, hasUncommittedChanges, isGitAvailable, loadDeployConfig, quoteForBash, runCommand, runCommandSafe, runScp, runSsh, };