| 376 | * Remove old backups with the given prefix from a specified directory. | 376 | * Remove old backups with the given prefix from a specified directory. |
| 377 | * @param {string} directory The root directory to remove backups from. | 377 | * @param {string} directory The root directory to remove backups from. |
| 378 | * @param {string} prefix File prefix to filter backups by. | 378 | * @param {string} prefix File prefix to filter backups by. |
| | 379 | * @param {number?} limit Maximum number of backups to keep. If null, the limit is determined by the `numberOfBackups` config value. |
| 379 | */ | 380 | */ |
| 380 | export function removeOldBackups(directory, prefix) { | 381 | export function removeOldBackups(directory, prefix, limit = null) { |
| 381 | const MAX_BACKUPS = Number(getConfigValue('numberOfBackups', 50)); | 382 | const MAX_BACKUPS = limit ?? Number(getConfigValue('numberOfBackups', 50)); |
| 382 | | 383 | |
| 383 | let files = fs.readdirSync(directory).filter(f => f.startsWith(prefix)); | 384 | let files = fs.readdirSync(directory).filter(f => f.startsWith(prefix)); |
| 384 | if (files.length > MAX_BACKUPS) { | 385 | if (files.length > MAX_BACKUPS) { |
| 385 | files = files.map(f => path.join(directory, f)); | 386 | files = files.map(f => path.join(directory, f)); |
| 386 | files.sort((a, b) => fs.statSync(a).mtimeMs - fs.statSync(b).mtimeMs); | 387 | files.sort((a, b) => fs.statSync(a).mtimeMs - fs.statSync(b).mtimeMs); |
| 387 | | 388 | |
| 388 | fs.rmSync(files[0]); | 389 | while (files.length > MAX_BACKUPS) { |
| | 390 | const oldest = files.shift(); |
| | 391 | if (!oldest) { |
| | 392 | break; |
| | 393 | } |
| | 394 | |
| | 395 | fs.rmSync(oldest); |
| | 396 | } |
| 389 | } | 397 | } |
| 390 | } | 398 | } |
| 391 | | 399 | |