enclosed / sync-notes.js
eienmojiki's picture
Update sync-notes.js
fabe61e verified
const { execSync, exec } = require('child_process');
const fs = require('fs');
const path = require('path');
const cron = require('node-cron');
const WATCH_DIR = path.join(__dirname, 'notes');
function gitPull() {
try {
console.log('Đang thực hiện git pull...');
execSync('git pull', { cwd: WATCH_DIR, stdio: 'inherit' });
console.log('Git pull hoàn tất.');
} catch (error) {
console.error('Lỗi khi thực hiện git pull:', error.message);
// Có thể xử lý lỗi ở đây, ví dụ: cố gắng merge hoặc reset
}
}
function gitStatusHasChanges(callback) {
exec('git status --porcelain', { cwd: WATCH_DIR }, (err, stdout, stderr) => {
if (err) {
console.error('Lỗi khi chạy git status:', err);
callback(false);
return;
}
callback(stdout.trim().length > 0);
});
}
function gitCommitAndPush(callback) {
const now = new Date();
const timeString = now.toISOString();
exec('git add .', { cwd: WATCH_DIR }, (err, stdout, stderr) => {
if (err) {
console.error('Lỗi khi chạy git add:', err);
callback(false);
return;
}
exec(`git commit -m "Database Sync - ${timeString}"`, { cwd: WATCH_DIR }, (err2, stdout2, stderr2) => {
if (err2) {
if (stderr2.includes('nothing to commit')) {
console.log('Không có thay đổi để commit.');
callback(true); // Coi như thành công vì không có gì để commit
} else {
console.error('Lỗi khi chạy git commit:', err2);
callback(false);
}
return;
}
exec('git push', { cwd: WATCH_DIR }, (err3, stdout3, stderr3) => {
if (err3) {
console.error('Lỗi khi chạy git push:', err3);
callback(false);
return;
}
console.log('Thay đổi đã được đẩy thành công vào lúc', timeString);
callback(true);
});
});
});
}
function initialSync() {
console.log('Đang thực hiện đồng bộ hóa ban đầu...');
gitStatusHasChanges((hasChanges) => {
if (hasChanges) {
console.log('Phát hiện thay đổi cục bộ, đang commit và đẩy...');
gitCommitAndPush((success) => {
if (success) {
gitPull();
} else {
console.error('Không thể đẩy thay đổi cục bộ. Bỏ qua git pull.');
}
});
} else {
console.log('Không có thay đổi cục bộ. Đang thực hiện git pull.');
gitPull();
}
});
}
function startWatching() {
console.log(`Bắt đầu theo dõi thư mục: ${WATCH_DIR}`);
// Lên lịch chạy mỗi phút
cron.schedule('* * * * *', () => {
gitStatusHasChanges((hasChanges) => {
if (hasChanges) {
console.log('Phát hiện thay đổi, đang commit và đẩy...');
gitCommitAndPush((success) => {
if (success) {
gitPull();
}
});
} else {
console.log('Không phát hiện thay đổi.');
gitPull(); // Vẫn pull định kỳ để đảm bảo cập nhật từ xa
}
});
});
}
// Thực hiện đồng bộ hóa ban đầu một lần khi script khởi động
initialSync();
// Sau đó bắt đầu theo dõi định kỳ
startWatching();