diff --git a/src/utils/index.ts b/src/utils/index.ts index ed9dd4f..1581679 100644 --- a/src/utils/index.ts +++ b/src/utils/index.ts @@ -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) {