diff --git a/packages/cli-repl/src/cli-repl.spec.ts b/packages/cli-repl/src/cli-repl.spec.ts index aae8ed0643..6e68a21aef 100644 --- a/packages/cli-repl/src/cli-repl.spec.ts +++ b/packages/cli-repl/src/cli-repl.spec.ts @@ -1,4 +1,5 @@ import { MongoshInternalError } from '@mongosh/errors'; +import bson from 'bson'; import { once } from 'events'; import { promises as fs } from 'fs'; import http from 'http'; @@ -276,6 +277,22 @@ describe('CliRepl', () => { await onerror; }); + it('removes old log files', async() => { + const oldlogfile = path.join(tmpdir.path, '60a0064774d771e863d9a1e1_log'); + const newerlogfile = path.join(tmpdir.path, `${new bson.ObjectId()}_log`); + await fs.writeFile(oldlogfile, 'ignoreme'); + await fs.writeFile(newerlogfile, 'ignoreme'); + cliRepl = new CliRepl(cliReplOptions); + await cliRepl.start('', {}); + await fs.stat(newerlogfile); + try { + await fs.stat(oldlogfile); + expect.fail('missed exception'); + } catch (err) { + expect(err.code).to.equal('ENOENT'); + } + }); + it('verifies the Node.js version', async() => { const origVersionCheckEnvVar = process.env.MONGOSH_SKIP_NODE_VERSION_CHECK; delete process.env.MONGOSH_SKIP_NODE_VERSION_CHECK; diff --git a/packages/cli-repl/src/cli-repl.ts b/packages/cli-repl/src/cli-repl.ts index 989e14297a..155d41b4c4 100644 --- a/packages/cli-repl/src/cli-repl.ts +++ b/packages/cli-repl/src/cli-repl.ts @@ -279,6 +279,7 @@ class CliRepl { */ async openLogStream(): Promise { const path = this.shellHomeDirectory.localPath(`${this.logId}_log`); + await this.cleanupOldLogfiles(); try { const stream = createWriteStream(path, { mode: 0o600 }); await once(stream, 'ready'); @@ -294,6 +295,29 @@ class CliRepl { } } + async cleanupOldLogfiles(): Promise { + const dir = this.shellHomeDirectory.localPath(''); + let dirHandle; + try { + dirHandle = await fs.opendir(dir); + } catch { + return; + } + for await (const dirent of dirHandle) { + if (!dirent.isFile()) continue; + const { id } = dirent.name.match(/^(?[a-f0-9]{24})_log$/i)?.groups ?? {}; + if (!id) continue; + // Delete files older than 30 days + if (new bson.ObjectId(id).generationTime < (Date.now() / 1000) - 30 * 86400) { + try { + await fs.unlink(path.join(dir, dirent.name)); + } catch (err) { + this.bus.emit('mongosh:error', err); + } + } + } + } + warnAboutInaccessibleFile(err: Error, path?: string): void { this.bus.emit('mongosh:error', err); if (this.warnedAboutInaccessibleFiles) {