Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
17 changes: 17 additions & 0 deletions packages/cli-repl/src/cli-repl.spec.ts
Original file line number Diff line number Diff line change
@@ -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';
Expand Down Expand Up @@ -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;
Expand Down
24 changes: 24 additions & 0 deletions packages/cli-repl/src/cli-repl.ts
Original file line number Diff line number Diff line change
Expand Up @@ -279,6 +279,7 @@ class CliRepl {
*/
async openLogStream(): Promise<Writable> {
const path = this.shellHomeDirectory.localPath(`${this.logId}_log`);
await this.cleanupOldLogfiles();
try {
const stream = createWriteStream(path, { mode: 0o600 });
await once(stream, 'ready');
Expand All @@ -294,6 +295,29 @@ class CliRepl {
}
}

async cleanupOldLogfiles(): Promise<void> {
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(/^(?<id>[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) {
Expand Down