feat: Limit config backups to 3 most recent files

Modified the backupConfigFile function to automatically clean up old backups,
keeping only the 3 most recent backup files. This prevents the config directory
from accumulating excessive backup files over time.

The implementation:
- Creates timestamped backups as before
- After each new backup, scans for existing backups
- Sorts backups by timestamp (newest first)
- Deletes all but the 3 most recent backups
- Gracefully handles cleanup errors with warnings

🤖 Generated with [Claude Code](https://claude.ai/code)

Co-Authored-By: Claude <noreply@anthropic.com>
This commit is contained in:
musistudio
2025-07-30 21:59:10 +08:00
parent 3a12fdffb1
commit 3cb086fc57

View File

@@ -1,6 +1,7 @@
import fs from "node:fs/promises";
import readline from "node:readline";
import JSON5 from "json5";
import path from "node:path";
import {
CONFIG_FILE,
DEFAULT_CONFIG,
@@ -91,6 +92,30 @@ export const backupConfigFile = async () => {
const timestamp = new Date().toISOString().replace(/[:.]/g, '-');
const backupPath = `${CONFIG_FILE}.${timestamp}.bak`;
await fs.copyFile(CONFIG_FILE, backupPath);
// Clean up old backups, keeping only the 3 most recent
try {
const configDir = path.dirname(CONFIG_FILE);
const configFileName = path.basename(CONFIG_FILE);
const files = await fs.readdir(configDir);
// Find all backup files for this config
const backupFiles = files
.filter(file => file.startsWith(configFileName) && file.endsWith('.bak'))
.sort()
.reverse(); // Sort in descending order (newest first)
// Delete all but the 3 most recent backups
if (backupFiles.length > 3) {
for (let i = 3; i < backupFiles.length; i++) {
const oldBackupPath = path.join(configDir, backupFiles[i]);
await fs.unlink(oldBackupPath);
}
}
} catch (cleanupError) {
console.warn("Failed to clean up old backups:", cleanupError);
}
return backupPath;
}
} catch (error) {