-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathgithub.js
More file actions
90 lines (76 loc) · 3.56 KB
/
Copy pathgithub.js
File metadata and controls
90 lines (76 loc) · 3.56 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
const { execSync } = require('child_process');
const fs = require('fs');
const path = require('path');
function isNewer(local, remote) {
const l = local.replace(/[^0-9.]/g, '').split('.').map(Number);
const r = remote.replace(/[^0-9.]/g, '').split('.').map(Number);
for (let i = 0; i < Math.max(l.length, r.length); i++) {
const lVal = l[i] || 0;
const rVal = r[i] || 0;
if (rVal > lVal) return true;
if (rVal < lVal) return false;
}
return false;
}
async function checkAndUpdate() {
console.log('🔄 正在檢查更新 請稍後...');
try {
try {
execSync('git --version', { stdio: 'ignore' });
} catch (e) {
console.log('⚠️ 伺服器未安裝 Git,跳過自動更新。');
return;
}
try {
execSync('git rev-parse --is-inside-work-tree', { stdio: 'ignore' });
} catch (e) {
execSync('git init', { stdio: 'ignore' });
execSync('git branch -m main', { stdio: 'ignore' });
execSync('git remote add origin https://github.com/kairo0916/cloudcat-bot.git', { stdio: 'ignore' });
}
const versionPath = path.join(__dirname, 'version.txt');
let localVersion = '0.0.0';
if (fs.existsSync(versionPath)) {
localVersion = fs.readFileSync(versionPath, 'utf8').trim();
}
const response = await fetch('https://raw.githubusercontent.com/kairo0916/cloudcat-bot/main/version.txt');
if (!response.ok) throw new Error('無法連接到 GitHub 獲取版本資訊');
const remoteVersion = (await response.text()).trim();
if (isNewer(localVersion, remoteVersion)) {
console.log(`\n✨ 有新的版本更新!(v${remoteVersion})`);
execSync('git fetch origin main', { stdio: 'ignore' });
let packageChanged = false;
try {
execSync('git rev-parse HEAD', { stdio: 'ignore' });
const diffOutput = execSync('git diff --name-only HEAD origin/main').toString().trim();
const changedFiles = diffOutput ? diffOutput.split('\n') : [];
if (changedFiles.includes('package.json')) packageChanged = true;
console.log('📦 正在下載並覆蓋:');
if (changedFiles.length > 0) {
changedFiles.forEach(file => {
console.log(`✔ ${file}`);
});
} else {
console.log('✔ (僅版本號變更)');
}
} catch (e) {
console.log('📦 正在進行首次全面同步 (強制覆蓋本地檔案)...');
packageChanged = true;
}
// 💥 終極殺招:放棄本地所有修改,強制與遠端完全一致!
execSync('git reset --hard origin/main', { stdio: 'ignore' });
if (packageChanged) {
console.log('\n📦 發現更新中包含核心模組變動,正在自動安裝...');
execSync('npm install', { stdio: 'inherit' });
}
console.log('\n✅ 更新完成!正在自動重啟...\n');
process.exit(0);
} else {
console.log(`✅ 目前已是最新版本 (v${localVersion}),跳過更新。\n`);
}
} catch (error) {
console.error('❌ 檢查更新時發生錯誤:', error.message);
console.log('⚠️ 放棄更新,繼續啟動機器人...\n');
}
}
module.exports = checkAndUpdate;