Skip to content

Commit

Permalink
chore: print console logs continuously
Browse files Browse the repository at this point in the history
  • Loading branch information
shaketbaby committed Dec 29, 2023
1 parent 2bda50b commit d6a5c74
Show file tree
Hide file tree
Showing 10 changed files with 69 additions and 109 deletions.
27 changes: 5 additions & 22 deletions src/editors/playgroundController.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,6 @@ import { ProgressLocation } from 'vscode';
import vm from 'vm';
import os from 'os';
import transpiler from 'bson-transpilers';
import util from 'util';

import type ActiveConnectionCodeLensProvider from './activeConnectionCodeLensProvider';
import type PlaygroundSelectedCodeActionProvider from './playgroundSelectedCodeActionProvider';
Expand Down Expand Up @@ -159,6 +158,8 @@ export default class PlaygroundController {
}
);

languageServerController._consoleOutputChannel = this._outputChannel;

const onDidChangeActiveTextEditor = (
editor: vscode.TextEditor | undefined
) => {
Expand Down Expand Up @@ -467,7 +468,7 @@ export default class PlaygroundController {
// If a user clicked the cancel button terminate all playground scripts.
this._languageServerController.cancelAll();

return { outputLines: undefined, result: undefined };
return { result: undefined };
});

// Run all playground scripts.
Expand All @@ -483,10 +484,7 @@ export default class PlaygroundController {
} catch (error) {
log.error('Evaluating playground with cancel modal failed', error);

return {
outputLines: undefined,
result: undefined,
};
return { result: undefined };
}
}

Expand Down Expand Up @@ -572,22 +570,7 @@ export default class PlaygroundController {
const evaluateResponse: ShellEvaluateResult =
await this._evaluateWithCancelModal();

if (evaluateResponse?.outputLines?.length) {
for (const line of evaluateResponse.outputLines) {
this._outputChannel.appendLine(
typeof line.content === 'string'
? line.content
: util.inspect(line.content)
);
}

this._outputChannel.show(true);
}

if (
!evaluateResponse ||
(!evaluateResponse.outputLines && !evaluateResponse.result)
) {
if (!evaluateResponse || !evaluateResponse.result) {
return false;
}

Expand Down
15 changes: 15 additions & 0 deletions src/language/languageServerController.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ import {
} from 'vscode-languageclient/node';
import type { ExtensionContext } from 'vscode';
import { workspace } from 'vscode';
import util from 'util';

import { createLogger } from '../logging';
import type {
Expand All @@ -37,6 +38,7 @@ export default class LanguageServerController {
_currentConnectionId: string | null = null;
_currentConnectionString?: string;
_currentConnectionOptions?: MongoClientOptions;
_consoleOutputChannel?: vscode.OutputChannel;

constructor(context: ExtensionContext) {
this._context = context;
Expand Down Expand Up @@ -151,6 +153,19 @@ export default class LanguageServerController {
void vscode.window.showErrorMessage(messsage);
}
);

this._client.onNotification(
ServerCommands.SHOW_CONSOLE_OUTPUT,
(outputs) => {
for (const line of outputs) {
this._consoleOutputChannel?.appendLine(
typeof line === 'string' ? line : util.inspect(line)
);
}

this._consoleOutputChannel?.show(true);
}
);
}

deactivate(): Thenable<void> | undefined {
Expand Down
15 changes: 11 additions & 4 deletions src/language/mongoDBService.ts
Original file line number Diff line number Diff line change
Expand Up @@ -267,9 +267,16 @@ export default class MongoDBService {
)
);

worker?.on(
'message',
({ error, data }: { data?: ShellEvaluateResult; error?: any }) => {
worker?.on('message', ({ name, payload }) => {
if (name === ServerCommands.SHOW_CONSOLE_OUTPUT) {
void this._connection.sendNotification(name, payload);
}

if (name === ServerCommands.EXECUTE_CODE_FROM_PLAYGROUND) {
const { error, data } = payload as {
data?: ShellEvaluateResult;
error?: any;
};
if (error) {
this._connection.console.error(
`WORKER error: ${util.inspect(error)}`
Expand All @@ -283,7 +290,7 @@ export default class MongoDBService {
resolve(data);
});
}
);
});

worker.postMessage({
name: ServerCommands.EXECUTE_CODE_FROM_PLAYGROUND,
Expand Down
1 change: 1 addition & 0 deletions src/language/serverCommands.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ export enum ServerCommands {
CLEAR_CACHED_COMPLETIONS = 'CLEAR_CACHED_COMPLETIONS',
MONGODB_SERVICE_CREATED = 'MONGODB_SERVICE_CREATED',
INITIALIZE_MONGODB_SERVICE = 'INITIALIZE_MONGODB_SERVICE',
SHOW_CONSOLE_OUTPUT = 'SHOW_CONSOLE_OUTPUT',
}

export type PlaygroundRunParameters = {
Expand Down
25 changes: 10 additions & 15 deletions src/language/worker.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,6 @@ import { ServerCommands } from './serverCommands';

import type {
ShellEvaluateResult,
PlaygroundDebug,
WorkerEvaluate,
MongoClientOptions,
} from '../types/playgroundType';
Expand Down Expand Up @@ -52,19 +51,14 @@ const execute = async (
try {
// Create a new instance of the runtime for each playground evaluation.
const runtime = new ElectronRuntime(serviceProvider);
const outputLines: PlaygroundDebug = [];

// Collect console.log() output.
runtime.setEvaluationListener({
onPrint(values: EvaluationResult[]) {
for (const { type, printable } of values) {
outputLines.push({
type,
content: printable,
namespace: null,
language: null,
});
}
parentPort?.postMessage({
name: ServerCommands.SHOW_CONSOLE_OUTPUT,
payload: values.map((v) => v.printable),
});
},
});

Expand All @@ -83,7 +77,7 @@ const execute = async (
language: getLanguage({ type, printable }),
};

return { data: { outputLines, result } };
return { data: { result } };
} catch (error) {
return { error };
} finally {
Expand All @@ -93,13 +87,14 @@ const execute = async (

const handleMessageFromParentPort = async ({ name, data }): Promise<void> => {
if (name === ServerCommands.EXECUTE_CODE_FROM_PLAYGROUND) {
parentPort?.postMessage(
await execute(
parentPort?.postMessage({
name: ServerCommands.EXECUTE_CODE_FROM_PLAYGROUND,
payload: await execute(
data.codeToEvaluate,
data.connectionString,
data.connectionOptions
)
);
),
});
}
};

Expand Down
42 changes: 10 additions & 32 deletions src/test/suite/editors/playgroundController.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -332,10 +332,7 @@ suite('Playground Controller Test Suite', function () {
const result =
await testPlaygroundController._evaluateWithCancelModal();

expect(result).to.deep.equal({
outputLines: undefined,
result: undefined,
});
expect(result).to.deep.equal({ result: undefined });
});

test('playground controller loads the active editor on start', () => {
Expand Down Expand Up @@ -405,9 +402,9 @@ suite('Playground Controller Test Suite', function () {
let outputChannelShowStub: SinonStub;

beforeEach(function () {
outputChannelAppendLineStub = sinon.stub();
outputChannelClearStub = sinon.stub();
outputChannelShowStub = sinon.stub();
outputChannelAppendLineStub = sandbox.stub();
outputChannelClearStub = sandbox.stub();
outputChannelShowStub = sandbox.stub();

const mockOutputChannel = {
appendLine: outputChannelAppendLineStub,
Expand All @@ -422,40 +419,20 @@ suite('Playground Controller Test Suite', function () {
showInformationMessageStub.resolves('Yes');
});

test('show the output in the vscode output channel as a string', async () => {
const outputLines = [
'test',
{ pineapple: 'yes' },
['porcupine', { anObject: true }],
].map((content) => ({ content }));
test('clear output channel when evaluating', async () => {
sandbox.replace(
testPlaygroundController,
'_evaluateWithCancelModal',
sandbox.stub().resolves({
outputLines,
result: '123',
})
);

expect(outputChannelClearStub).to.not.be.called;
expect(outputChannelShowStub).to.not.be.called;
expect(outputChannelAppendLineStub).to.not.be.called;

await testPlaygroundController.runAllPlaygroundBlocks();

expect(outputChannelClearStub).to.be.calledOnce;
expect(outputChannelShowStub).to.be.calledOnce;
expect(outputChannelAppendLineStub.calledThrice).to.be.true;
expect(outputChannelAppendLineStub.firstCall.args[0]).to.equal(
'test'
);
// Make sure we're not printing anything like [object Object].
expect(outputChannelAppendLineStub.secondCall.args[0]).to.equal(
"{ pineapple: 'yes' }"
);
expect(outputChannelAppendLineStub.thirdCall.args[0]).to.equal(
"[ 'porcupine', { anObject: true } ]"
);
});
});

Expand All @@ -464,10 +441,7 @@ suite('Playground Controller Test Suite', function () {
sandbox.replace(
testPlaygroundController,
'_evaluateWithCancelModal',
sandbox.stub().resolves({
outputLines: [],
result: '123',
})
sandbox.stub().resolves({ result: '123' })
);
sandbox.replace(
testPlaygroundController,
Expand All @@ -479,6 +453,10 @@ suite('Playground Controller Test Suite', function () {
test('show a confirmation message if mdb.confirmRunAll is true', async () => {
showInformationMessageStub.resolves('Yes');

await vscode.workspace
.getConfiguration('mdb')
.update('confirmRunAll', true);

const result =
await testPlaygroundController.runAllPlaygroundBlocks();

Expand Down
Loading

0 comments on commit d6a5c74

Please sign in to comment.