Repository navigation
Expand file tree
/
Copy pathdeploy_api.js
More file actions
813 lines (715 loc) · 32.1 KB
/
Copy pathdeploy_api.js
File metadata and controls
813 lines (715 loc) · 32.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
const path = require('path');
const fs = require('hexo-fs');
const fse = require('fs-extra');
const { exec, spawn } = require('child_process');
const utils = require('./utils');
const yaml = require('js-yaml');
const { copySourceProject } = require('./source_sync');
// A partial form submission must never erase an already saved credential.
const keepCredential = (value, previous) => value === undefined || value === '******' ? previous : value;
module.exports = function (app, hexo, use, db) {
// 使用传入的统一数据库实例,而不是创建自己的
if (!db || !db.deployStatusDb) {
throw new Error('[Hexo Pro]: 部署API需要数据库实例');
}
const deployStatusDb = db.deployStatusDb;
// 去除 ANSI 转义序列,避免前端显示乱码(如 wrangler 输出的颜色码)
function stripAnsi(str) {
if (typeof str !== 'string') return str;
return str.replace(/\x1b\[[0-9;]*[a-zA-Z]/g, '');
}
// 脱敏辅助函数
function maskSensitiveConfig(config) {
const masked = {
...config,
token: config.token ? '******' : ''
};
if (masked.cloudflare) {
masked.cloudflare = {
...masked.cloudflare,
apiToken: masked.cloudflare.apiToken ? '******' : ''
};
}
if (masked.edgeone) {
masked.edgeone = {
...masked.edgeone,
apiToken: masked.edgeone.apiToken ? '******' : ''
};
}
return masked;
}
// 获取部署配置
use('deploy/config', function (req, res) {
try {
const configPath = path.join(hexo.base_dir, 'deploy_config.json');
let config = {
deployType: 'github',
enabledPlatforms: ['github'],
repository: '',
branch: 'main',
message: 'Site updated: {{ now("YYYY-MM-DD HH:mm:ss") }}',
token: '',
cloudflare: {
accountId: '',
projectName: '',
apiToken: ''
},
edgeone: {
projectName: '',
apiToken: '',
env: 'production'
},
lastDeployTime: ''
};
if (fs.existsSync(configPath)) {
try {
const savedConfig = JSON.parse(fs.readFileSync(configPath));
config = maskSensitiveConfig({
...config,
...savedConfig
});
} catch (e) {
console.error('解析部署配置文件失败:', e);
}
}
res.done(config);
} catch (error) {
console.error('获取部署配置失败:', error);
res.send(500, '获取部署配置失败');
}
});
// 保存部署配置
use('deploy/save-config', function (req, res, next) {
if (req.method !== 'POST') return next();
try {
if (!req.body) {
return res.send(400, '缺少配置信息');
}
const configPath = path.join(hexo.base_dir, 'deploy_config.json');
let existingConfig = {};
if (fs.existsSync(configPath)) {
try {
existingConfig = JSON.parse(fs.readFileSync(configPath));
} catch (e) {
console.error('解析现有部署配置文件失败:', e);
}
}
// 合并配置,保留现有敏感信息(如果新配置中没有提供)
const newConfig = {
...existingConfig,
...req.body,
token: keepCredential(req.body.token, existingConfig.token),
enabledPlatforms: Array.isArray(req.body.enabledPlatforms)
? req.body.enabledPlatforms
: (existingConfig.enabledPlatforms || ['github'])
};
// 合并 cloudflare 配置,保留 apiToken
if (req.body.cloudflare) {
const existingCf = existingConfig.cloudflare || {};
newConfig.cloudflare = {
...existingCf,
...req.body.cloudflare,
apiToken: keepCredential(req.body.cloudflare.apiToken, existingCf.apiToken)
};
}
// 合并 edgeone 配置,保留 apiToken
if (req.body.edgeone) {
const existingEo = existingConfig.edgeone || {};
newConfig.edgeone = {
...existingEo,
...req.body.edgeone,
apiToken: keepCredential(req.body.edgeone.apiToken, existingEo.apiToken)
};
}
// 保存到文件
fs.writeFileSync(configPath, JSON.stringify(newConfig, null, 2));
// 仅 github 类型时更新 _config.yml 中的 deploy 配置
if (!newConfig.deployType || newConfig.deployType === 'github') {
updateHexoConfig(hexo.base_dir, newConfig);
}
res.done(maskSensitiveConfig(newConfig));
} catch (error) {
console.error('保存部署配置失败:', error);
res.send(500, '保存部署配置失败');
}
});
// 执行部署 - 改为异步方式,支持多平台、请求体传入配置
use('deploy/execute', function (req, res, next) {
if (req.method !== 'POST') return next();
try {
// 检查是否正在部署
deployStatusDb.findOne({ type: 'status' }, (err, status) => {
if (err) {
return res.send(500, '获取部署状态失败');
}
if (status && status.isDeploying) {
return res.send(400, '部署正在进行中,请等待完成');
}
const configPath = path.join(hexo.base_dir, 'deploy_config.json');
let config = {};
// 若请求体传入 config,先合并保存
if (req.body && req.body.config) {
let existingConfig = {};
if (fs.existsSync(configPath)) {
try {
existingConfig = JSON.parse(fs.readFileSync(configPath));
} catch (e) {
console.error('解析现有部署配置文件失败:', e);
}
}
const newConfig = {
...existingConfig,
...req.body.config,
token: keepCredential(req.body.config.token, existingConfig.token)
};
if (req.body.config.cloudflare) {
const existingCf = existingConfig.cloudflare || {};
newConfig.cloudflare = {
...existingCf,
...req.body.config.cloudflare,
apiToken: keepCredential(req.body.config.cloudflare.apiToken, existingCf.apiToken)
};
}
if (req.body.config.edgeone) {
const existingEo = existingConfig.edgeone || {};
newConfig.edgeone = {
...existingEo,
...req.body.config.edgeone,
apiToken: keepCredential(req.body.config.edgeone.apiToken, existingEo.apiToken)
};
}
try {
fs.writeFileSync(configPath, JSON.stringify(newConfig, null, 2));
if (!newConfig.deployType || newConfig.deployType === 'github') {
updateHexoConfig(hexo.base_dir, newConfig);
}
} catch (e) {
console.error('保存部署配置失败:', e);
return res.send(500, '保存部署配置失败');
}
config = newConfig;
} else if (fs.existsSync(configPath)) {
try {
config = JSON.parse(fs.readFileSync(configPath));
} catch (e) {
console.error('解析部署配置文件失败:', e);
return res.send(500, '解析部署配置失败');
}
} else {
return res.send(400, '部署配置不存在,请先填写并保存配置');
}
// 解析部署目标:deployTargets 优先,兼容 deployType
let deployTargets = req.body && req.body.deployTargets;
if (!deployTargets && req.body && req.body.deployType) {
deployTargets = [req.body.deployType];
}
if (!Array.isArray(deployTargets)) {
deployTargets = [config.deployType || 'github'];
}
deployTargets = deployTargets.filter(t => t === 'github' || t === 'cloudflare-pages' || t === 'edgeone-pages');
if (deployTargets.length === 0) {
return res.send(400, '请指定至少一个部署目标');
}
if (deployTargets.includes('github') && !config.repository) {
return res.send(400, '缺少仓库地址');
}
if (deployTargets.includes('cloudflare-pages')) {
const cf = config.cloudflare || {};
if (!cf.accountId || !cf.projectName || !cf.apiToken) {
return res.send(400, '缺少 Cloudflare Pages 配置(Account ID / Project Name / API Token)');
}
}
if (deployTargets.includes('edgeone-pages')) {
const eo = config.edgeone || {};
if (!eo.projectName || !eo.apiToken) {
return res.send(400, '缺少 EdgeOne Pages 配置(项目名称 / API Token)');
}
}
const skipGenerate = req.body && req.body.skipGenerate === true;
deployStatusDb.update(
{ type: 'status' },
{
$set: {
isDeploying: true,
progress: 0,
stage: 'started',
logs: ['deploy.started'],
error: null
}
},
{},
(err) => {
if (err) {
console.error('更新部署状态失败:', err);
return res.send(500, '更新部署状态失败');
}
res.done({
success: true,
message: '部署已开始,请通过状态 API 查询进度',
isDeploying: true
});
executeDeployAsync(hexo.base_dir, deployStatusDb, config, skipGenerate, deployTargets);
}
);
});
} catch (error) {
console.error('执行部署失败:', error);
res.send(500, `执行部署失败: ${error.message}`);
}
});
// 检查部署状态 - 增强版
use('deploy/status', function (req, res) {
try {
deployStatusDb.findOne({ type: 'status' }, (err, status) => {
if (err) {
return res.send(500, '获取部署状态失败');
}
if (!status) {
return res.done({
isDeploying: false,
progress: 0,
stage: 'idle',
lastDeployTime: '未知',
logs: [],
hasDeployGit: fs.existsSync(path.join(hexo.base_dir, '.deploy_git'))
});
}
// 检查 .deploy_git 目录是否存在
const hasDeployGit = fs.existsSync(path.join(hexo.base_dir, '.deploy_git'));
res.done({
...status,
hasDeployGit
});
});
} catch (error) {
console.error('获取部署状态失败:', error);
res.send(500, '获取部署状态失败');
}
});
// 辅助函数:格式化日期时间
function formatDateTime(dateString) {
const date = new Date(dateString);
const year = date.getFullYear();
const month = String(date.getMonth() + 1).padStart(2, '0');
const day = String(date.getDate()).padStart(2, '0');
const hours = String(date.getHours()).padStart(2, '0');
const minutes = String(date.getMinutes()).padStart(2, '0');
const seconds = String(date.getSeconds()).padStart(2, '0');
return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
}
// 辅助函数:更新 Hexo 配置文件中的 deploy 部分
function updateHexoConfig(baseDir, deployConfig) {
try {
const hexoConfigPath = path.join(baseDir, '_config.yml');
// 读取现有配置
let hexoConfigContent = fse.readFileSync(hexoConfigPath, 'utf-8');
let hexoConfig;
try {
hexoConfig = yaml.load(hexoConfigContent);
} catch (e) {
console.error('解析 Hexo 配置文件失败:', e);
throw new Error('解析 Hexo 配置文件失败');
}
// 构建新的 deploy 配置
const repoUrl = deployConfig.token
? `https://${deployConfig.token}@github.com/${deployConfig.repository}.git`
: `https://github.com/${deployConfig.repository}.git`;
// 更新 deploy 配置
hexoConfig.deploy = {
type: 'git',
repo: repoUrl,
branch: deployConfig.branch,
message: deployConfig.message
};
// 将配置写回文件
const newConfigContent = yaml.dump(hexoConfig);
fs.writeFileSync(hexoConfigPath, newConfigContent, 'utf-8');
console.log('已更新 _config.yml 中的部署配置');
} catch (error) {
console.error('更新 Hexo 配置文件失败:', error);
throw error;
}
}
// 辅助函数:处理提交消息模板
function processCommitMessage(message) {
// 替换 {{ now("YYYY-MM-DD HH:mm:ss") }} 格式
return message.replace(/\{\{\s*now\(["']([^"']+)["']\)\s*\}\}/g, (match, format) => {
const now = new Date();
// 简单的日期格式化
const year = now.getFullYear();
const month = String(now.getMonth() + 1).padStart(2, '0');
const day = String(now.getDate()).padStart(2, '0');
const hours = String(now.getHours()).padStart(2, '0');
const minutes = String(now.getMinutes()).padStart(2, '0');
const seconds = String(now.getSeconds()).padStart(2, '0');
return format
.replace('YYYY', year)
.replace('MM', month)
.replace('DD', day)
.replace('HH', hours)
.replace('mm', minutes)
.replace('ss', seconds);
});
}
// 辅助函数:异步执行部署过程
function executeDeployAsync(baseDir, deployStatusDb, config, skipGenerate, deployTargets) {
deployTargets = deployTargets || [config.deployType || 'github'];
const updateStatus = (update) => {
return new Promise((resolve, reject) => {
deployStatusDb.update(
{ type: 'status' },
{ $set: update },
{},
(err) => {
if (err) {
console.error('更新部署状态失败:', err);
reject(err);
} else {
resolve();
}
}
);
});
};
const redact = message => {
let text = stripAnsi(String(message));
for (const token of [config.token, config.cloudflare?.apiToken, config.edgeone?.apiToken].filter(Boolean)) {
text = text.split(token).join('[已隐藏凭据]').split(encodeURIComponent(token)).join('[已隐藏凭据]');
}
return text.replace(/https?:\/\/[^\s/@]+@github\.com/gi, 'https://github.com');
};
const addLog = (message) => {
const cleanMessage = redact(message);
console.log(cleanMessage);
deployStatusDb.findOne({ type: 'status' }, (err, status) => {
if (!err && status) {
const logs = [...status.logs, cleanMessage];
deployStatusDb.update(
{ type: 'status' },
{ $set: { logs: logs } },
{}
);
}
});
};
const runCommand = (command, args, options) => {
return new Promise((resolve, reject) => {
let finalCommand = command;
let finalArgs = args;
let mergedOptions = {
...options,
shell: command !== 'git',
env: { ...process.env, GIT_TERMINAL_PROMPT: '0' },
windowsVerbatimArguments: false
};
addLog(`run command: ${finalCommand} ${finalArgs.join(' ')}`);
const proc = spawn(finalCommand, finalArgs, mergedOptions);
let stderr = '';
proc.stdout.on('data', (data) => {
addLog(data.toString().trim());
});
proc.stderr.on('data', (data) => {
const message = data.toString().trim();
stderr = (stderr + '\n' + message).slice(-4000);
if (message.includes('Waiting for the debugger to disconnect')) {
addLog(message);
} else {
addLog(`error: ${message}`);
}
});
proc.on('close', (code) => {
if (code === 0) {
resolve();
} else {
const authFailure = /could not read Username|Authentication failed|Invalid username or token/i.test(stderr);
reject(new Error(authFailure ? 'GitHub 身份验证失败,请重新填写并保存访问凭据后再试' : redact(stderr.trim() || `命令执行失败,退出码: ${code}`)));
}
});
proc.on('error', (err) => {
addLog(`Process error: ${err.message}`);
reject(err);
});
});
};
// 自定义 Git 部署函数
const customGitDeploy = async (baseDir, config, skipGenerate = false) => {
const deployDir = path.join(baseDir, '.deploy_git');
const publicDir = path.resolve(baseDir, hexo.config.public_dir || 'public');
// 构建仓库URL
const repoUrl = config.token
? `https://x-access-token:${encodeURIComponent(config.token)}@github.com/${config.repository}.git`
: `https://github.com/${config.repository}.git`;
// 处理提交消息
const commitMessage = processCommitMessage(config.message || 'Site updated');
addLog('deploy.git.preparing');
if (!skipGenerate) {
// 标准模式:检查 public 目录是否存在
if (!fs.existsSync(publicDir)) {
throw new Error('public 目录不存在,请先运行 hexo generate');
}
}
// 初始化或更新 .deploy_git 目录
if (skipGenerate) {
// 跳过生成模式:重新初始化部署目录以避免历史记录中的敏感信息
if (fs.existsSync(deployDir)) {
addLog('deploy.git.cleaning.old.deploy.dir');
await fse.remove(deployDir);
}
addLog('deploy.git.init.fresh.repo');
await runCommand('git', ['clone', '--depth', '1', repoUrl, '.deploy_git'], { cwd: baseDir });
// 切换到指定分支
try {
await runCommand('git', ['checkout', config.branch || 'main'], { cwd: deployDir });
} catch (error) {
// 如果分支不存在,创建新分支
addLog(`deploy.git.creating.branch: ${config.branch || 'main'}`);
await runCommand('git', ['checkout', '-b', config.branch || 'main'], { cwd: deployDir });
}
} else {
// 标准模式:正常的git操作
if (!fs.existsSync(deployDir)) {
addLog('deploy.git.cloning');
await runCommand('git', ['clone', repoUrl, '.deploy_git'], { cwd: baseDir });
} else {
addLog('deploy.git.updating');
// 检查并设置 origin remote
try {
// 检查 origin remote 是否存在
await runCommand('git', ['remote', 'get-url', 'origin'], { cwd: deployDir });
} catch (error) {
// origin 不存在,添加它
addLog('deploy.git.adding.origin');
await runCommand('git', ['remote', 'add', 'origin', repoUrl], { cwd: deployDir });
}
// 确保 origin URL 是正确的
try {
await runCommand('git', ['remote', 'set-url', 'origin', repoUrl], { cwd: deployDir });
} catch (error) {
addLog('deploy.git.remote.set.url.failed');
}
// 切换到指定分支
try {
await runCommand('git', ['checkout', config.branch || 'main'], { cwd: deployDir });
} catch (error) {
// 如果分支不存在,创建新分支
addLog(`deploy.git.creating.branch: ${config.branch || 'main'}`);
await runCommand('git', ['checkout', '-b', config.branch || 'main'], { cwd: deployDir });
}
// 拉取最新更改
try {
await runCommand('git', ['pull', 'origin', config.branch || 'main'], { cwd: deployDir });
} catch (error) {
addLog('deploy.git.pull.failed.continuing');
}
}
}
addLog('deploy.git.copying.files');
// 清空 deploy 目录(除了 .git)
const files = await fse.readdir(deployDir);
for (const file of files) {
if (file !== '.git') {
await fse.remove(path.join(deployDir, file));
}
}
if (skipGenerate) {
await copySourceProject(baseDir, deployDir, { publicDir });
addLog('deploy.git.config.cleaned');
} else {
// 标准模式:复制 public 目录内容到 deploy 目录
await fse.copy(publicDir, deployDir, {
filter: (src, dest) => {
// 不复制 .git 目录
return !src.includes('.git');
}
});
}
addLog('deploy.git.adding.files');
// Git 操作
await runCommand('git', ['add', '.'], { cwd: deployDir });
// 检查是否有变更
try {
await runCommand('git', ['diff', '--staged', '--quiet'], { cwd: deployDir });
addLog('deploy.git.no.changes');
return; // 没有变更,直接返回
} catch (error) {
// 有变更,继续提交
addLog('deploy.git.committing');
}
await runCommand('git', ['commit', '-m', commitMessage], { cwd: deployDir });
addLog('deploy.git.pushing');
await runCommand('git', ['push', 'origin', config.branch || 'main'], { cwd: deployDir });
addLog('deploy.git.success');
};
// Cloudflare Pages Direct Upload 部署函数
const cloudflarePagesDeploy = async (baseDir, config) => {
const publicDir = path.join(baseDir, 'public');
const cf = config.cloudflare;
if (!fs.existsSync(publicDir)) {
throw new Error('public 目录不存在,请先运行 hexo generate');
}
addLog('deploy.cloudflare.preparing');
const env = {
...process.env,
CLOUDFLARE_ACCOUNT_ID: cf.accountId,
CLOUDFLARE_API_TOKEN: cf.apiToken
};
addLog('deploy.cloudflare.uploading');
await runCommand('npx', [
'wrangler', 'pages', 'deploy', publicDir,
'--project-name', cf.projectName
], { cwd: baseDir, env });
addLog('deploy.cloudflare.success');
};
// EdgeOne Pages Direct Upload 部署函数
const edgeonePagesDeploy = async (baseDir, config) => {
const publicDir = path.join(baseDir, 'public');
const eo = config.edgeone;
if (!fs.existsSync(publicDir)) {
throw new Error('public 目录不存在,请先运行 hexo generate');
}
addLog('deploy.edgeone.preparing');
const args = [
'edgeone', 'pages', 'deploy', publicDir,
'-n', eo.projectName,
'-t', eo.apiToken
];
if (eo.env && eo.env === 'preview') {
args.push('-e', 'preview');
}
addLog('deploy.edgeone.uploading');
await runCommand('npx', args, { cwd: baseDir });
addLog('deploy.edgeone.success');
};
// Other platforms may need a build while GitHub still receives the selected source snapshot.
const needGenerate = deployTargets.includes('cloudflare-pages') ||
deployTargets.includes('edgeone-pages') ||
(deployTargets.includes('github') && !skipGenerate);
(async () => {
try {
if (!needGenerate) {
addLog('deploy.skip.generate.mode');
await updateStatus({ stage: 'deploying', progress: 30 });
} else {
await updateStatus({ stage: 'cleaning', progress: 10 });
addLog('deploy.cleaning');
await runCommand('npx', ['hexo', 'clean'], { cwd: baseDir });
await updateStatus({ stage: 'generating', progress: 30 });
addLog('deploy.generating');
await runCommand('npx', ['hexo', 'generate'], { cwd: baseDir });
await updateStatus({ stage: 'deploying', progress: 60 });
}
for (let i = 0; i < deployTargets.length; i++) {
const target = deployTargets[i];
const progressBase = 60 + Math.floor((i / deployTargets.length) * 35);
await updateStatus({ progress: progressBase });
if (target === 'cloudflare-pages') {
addLog('deploy.cloudflare.deploying');
await cloudflarePagesDeploy(baseDir, config);
} else if (target === 'edgeone-pages') {
addLog('deploy.edgeone.deploying');
await edgeonePagesDeploy(baseDir, config);
} else {
addLog('deploy.deploying');
await customGitDeploy(baseDir, config, skipGenerate);
}
}
const now = new Date();
const formattedTime = formatDateTime(now);
config.lastDeployTime = now.toISOString();
fs.writeFileSync(
path.join(baseDir, 'deploy_config.json'),
JSON.stringify(config, null, 2)
);
await updateStatus({
isDeploying: false,
progress: 100,
stage: 'completed',
lastDeployTime: formattedTime
});
addLog('deploy.success');
} catch (error) {
console.error('部署过程出错:', error);
await updateStatus({
isDeploying: false,
stage: 'failed',
error: error.message
});
addLog('deploy.failed');
addLog(error.message);
}
})();
}
// 重置部署状态
use('deploy/reset-status', function (req, res, next) {
if (req.method !== 'POST') return next();
try {
deployStatusDb.update(
{ type: 'status' },
{
$set: {
isDeploying: false,
progress: 0,
stage: 'idle',
error: null,
logs: ['deploy.status.reset']
}
},
{},
(err) => {
if (err) {
console.error('重置部署状态失败:', err);
return res.send(500, '重置部署状态失败');
}
res.done({
success: true,
message: 'deploy.status.reset'
});
}
);
} catch (error) {
console.error('重置部署状态失败:', error);
res.send(500, `重置部署状态失败: ${error.message}`);
}
});
// 清理部署目录
use('deploy/cleanup', function (req, res, next) {
if (req.method !== 'POST') return next();
try {
const deployDir = path.join(hexo.base_dir, '.deploy_git');
if (fs.existsSync(deployDir)) {
fse.removeSync(deployDir);
// 同时重置部署状态
deployStatusDb.update(
{ type: 'status' },
{
$set: {
isDeploying: false,
progress: 0,
stage: 'idle',
error: null,
logs: ['deploy.cleanup.success']
}
},
{},
(err) => {
if (err) {
console.error('重置部署状态失败:', err);
}
}
);
res.done({
success: true,
message: '部署目录已清理,下次部署将重新克隆仓库'
});
} else {
res.done({
success: true,
message: '部署目录不存在,无需清理'
});
}
} catch (error) {
console.error('清理部署目录失败:', error);
res.send(500, `清理部署目录失败: ${error.message}`);
}
});
};