Skip to content

Commit

Permalink
Merge pull request #30 from MetabobProject/sprint-3-improvements
Browse files Browse the repository at this point in the history
Sprint 3 improvements
  • Loading branch information
AviGopal authored Feb 21, 2024
2 parents 056c300 + e22f2a8 commit 798c3bd
Show file tree
Hide file tree
Showing 36 changed files with 1,082 additions and 746 deletions.
2 changes: 1 addition & 1 deletion .vscode/launch.json
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@
],
"sourceMaps": true,
"outFiles": [
"${workspaceFolder}/build/**/*.js",
"${workspaceRoot}/ext-src/**/*.ts",
"!**/node_modules/**"
]
}
Expand Down
8 changes: 4 additions & 4 deletions ext-src/commands/AnalyzeDocument.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import CONSTANTS from '../constants';
import Util from '../utils';
import { getExtensionEventEmitter } from '../events';


export function activateAnalyzeCommand(context: vscode.ExtensionContext): void {
const command = CONSTANTS.analyzeDocumentCommand;

Expand Down Expand Up @@ -54,8 +55,9 @@ export function activateAnalyzeCommand(context: vscode.ExtensionContext): void {

debugChannel.appendLine(`Metabob: Starting Analysis for ${documentMetaData.filePath}`);


Util.withProgress<SubmitRepresentationResponse>(
handleDocumentAnalyze(documentMetaData, sessionToken, analyzeState),
handleDocumentAnalyze(documentMetaData, sessionToken, analyzeState, context),
CONSTANTS.analyzeCommandProgressMessage,
).then(response => {
if (response.status === 'pending' || response.status === 'running') {
Expand All @@ -69,11 +71,9 @@ export function activateAnalyzeCommand(context: vscode.ExtensionContext): void {
}

Util.withProgress<SubmitRepresentationResponse>(
handleDocumentAnalyze(documentMetaData, sessionToken, analyzeState, inflightJobId),
handleDocumentAnalyze(documentMetaData, sessionToken, analyzeState, context, inflightJobId,),
CONSTANTS.analyzeCommandQueueMessage,
).then(response => {
debugChannel.appendLine(response.status);

switch (response.status) {
case 'failed':
case 'complete': {
Expand Down
68 changes: 57 additions & 11 deletions ext-src/commands/DetailDocument.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,11 @@
import * as vscode from 'vscode';
import CONSTANTS from '../constants';
import _debug from '../debug';
import { CurrentQuestion, CurrentQuestionState } from '../state';
import { Analyze, CurrentQuestion, CurrentQuestionState, Session } from '../state';
import { Problem } from '../types';
import { getExtensionEventEmitter } from '../events';
import { FeedbackSuggestionPayload, feedbackService } from '../services';
import Utils from '../utils';

export function activateDetailSuggestionCommand(context: vscode.ExtensionContext): void {
const command = CONSTANTS.showDetailSuggestionCommand;
Expand All @@ -14,14 +16,41 @@ export function activateDetailSuggestionCommand(context: vscode.ExtensionContext
vuln: Problem;
jobId: string;
}) => {
const key = `${args.path}@@${args.id}`;
const setAnalyzeState = new Analyze(context);
const analyzeStateValue = new Analyze(context).get()?.value;
const sessionToken = new Session(context).get()?.value;
const extensionEventEmitter = getExtensionEventEmitter();

_debug.appendLine(`Detail initiated for ${args.path} with Problem ${args.id} `);
const currentQuestionState = new CurrentQuestion(context);
const payload: CurrentQuestionState = {
path: args.path,
id: args.id,
vuln: args.vuln,
isFix: false,
isReset: false,

const documentMetaData = Utils.getFileNameFromCurrentEditor();

if (!documentMetaData) {
vscode.window.showErrorMessage(CONSTANTS.editorNotSelectorError);
return
}

if (!sessionToken || !analyzeStateValue) {
extensionEventEmitter.fire({
type: 'CURRENT_FILE',
data: { ...documentMetaData.editor.document },
});
vscode.window.showErrorMessage(CONSTANTS.editorNotSelectorError);
return;
}

vscode.commands.executeCommand('recommendation-panel-webview.focus');

const copiedAnalyzeValue = { ...analyzeStateValue };
copiedAnalyzeValue[key].isDiscarded = copiedAnalyzeValue[key].isDiscarded || false;
copiedAnalyzeValue[key].isEndorsed = copiedAnalyzeValue[key].isEndorsed || false;
copiedAnalyzeValue[key].isViewed = true;

const readSuggestionPayload: FeedbackSuggestionPayload = {
problemId: args.id,
discarded: copiedAnalyzeValue[key].isDiscarded || false,
endorsed: copiedAnalyzeValue[key].isEndorsed || false,
};

setTimeout(() => {
Expand All @@ -35,10 +64,27 @@ export function activateDetailSuggestionCommand(context: vscode.ExtensionContext
isReset: false,
},
});
}, 2000);

await currentQuestionState.set(payload);
vscode.commands.executeCommand('recommendation-panel-webview.focus');
getExtensionEventEmitter().fire({
type: 'Analysis_Completed',
data: {
shouldResetRecomendation: true,
shouldMoveToAnalyzePage: false,
...copiedAnalyzeValue,
},
});

extensionEventEmitter.fire({
type: 'CURRENT_FILE',
data: { ...documentMetaData.editor.document },
});
}, 500);

await setAnalyzeState.set(copiedAnalyzeValue);

await Promise.allSettled([
feedbackService.readSuggestion(readSuggestionPayload, sessionToken),
]);
};

context.subscriptions.push(vscode.commands.registerCommand(command, commandHandler));
Expand Down
99 changes: 55 additions & 44 deletions ext-src/commands/DiscardSuggestion.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,10 @@
import * as vscode from 'vscode';
import { CurrentQuestion, Analyze, Session, AnalyseMetaData } from '../state';
import { GenerateDecorations, decorationType } from '../helpers/GenerateDecorations';
import { CurrentQuestion, Analyze, Session } from '../state';
import { FeedbackSuggestionPayload, feedbackService } from '../services';
import { getExtensionEventEmitter } from '../events';
import CONSTANTS from '../constants';
import Utils from '../utils';
import { Problem } from '../types';
import _debug from '../debug';

export type DiscardCommandHandler = { id: string; path: string };
Expand All @@ -12,39 +13,38 @@ export function activateDiscardCommand(context: vscode.ExtensionContext): void {
const command = CONSTANTS.discardSuggestionCommand;

const commandHandler = async (args: DiscardCommandHandler) => {
const { id: problemId, path } = args;
const key = `${path}@@${problemId}`;

const editor = vscode.window.activeTextEditor;
if (!editor) {
vscode.window.showErrorMessage(CONSTANTS.editorNotSelectorError);
let isDecorationsApplied = false;
const analyzeState = new Analyze(context);
const problems = analyzeState.get()?.value;

if (!problems) {
_debug?.appendLine('Metabob: Problems is undefined in Discard Suggestion');
vscode.window.showErrorMessage(CONSTANTS.discardCommandErrorMessage);
return;
}

if (!Utils.isValidDocument(editor.document)) {
_debug?.appendLine(CONSTANTS.editorSelectedIsInvalid);

return;
}
const currentQuestion = new CurrentQuestion(context);
const extensionEventEmitter = getExtensionEventEmitter();
const { id: problemId, path } = args;
const key = `${path}@@${problemId}`;

const session = new Session(context).get()?.value;
if (!session) {
_debug?.appendLine('Metabob: Session is undefined in Discard Suggestion');

vscode.window.showErrorMessage(CONSTANTS.discardCommandErrorMessage);
return;
}

const analyzeState = new Analyze(context);
const currentQuestion = new CurrentQuestion(context);

const problems = analyzeState.get()?.value;
if (!problems) {
_debug?.appendLine('Metabob: Problems is undefined in Discard Suggestion');

// verifying that in-fact user viewing problem.path file.
const documentMetaData = Utils.getFileNameFromCurrentEditor();
if (!documentMetaData) {
vscode.window.showErrorMessage(CONSTANTS.editorNotSelectorError);
return;
}

const filename: string | undefined = documentMetaData.fileName;
const isUserOnProblemFile: boolean = filename === path;

const copyProblems = { ...problems };

const payload: FeedbackSuggestionPayload = {
Expand All @@ -53,36 +53,47 @@ export function activateDiscardCommand(context: vscode.ExtensionContext): void {
endorsed: false,
};

try {
await feedbackService.discardSuggestion(payload, session);
} catch (err: any) {
_debug?.appendLine(err.message);
// Updating the state with discarded problem values.
copyProblems[key].isDiscarded = true;
copyProblems[key].isEndorsed = false;
copyProblems[key].isViewed = true;

// Filtering the problem that are not not supported by vscode. Line range should be in range [0, lineNumber].
const results: Problem[] | undefined = Utils.getCurrentEditorProblems(copyProblems, path);
if (!results) {
vscode.window.showErrorMessage(CONSTANTS.discardCommandErrorMessage);
return;
}

copyProblems[key].isDiscarded = true;
if (isUserOnProblemFile) {
isDecorationsApplied = Utils.decorateCurrentEditorWithHighlights(
results,
documentMetaData.editor,
);
}

try {
analyzeState.set(copyProblems).then(() => {
const results: AnalyseMetaData[] = [];
extensionEventEmitter.fire({
type: 'onDiscardSuggestionClicked:Success',
data: {},
});

for (const [, value] of Object.entries(copyProblems)) {
if (!value.isDiscarded) {
results.push(value);
}
}
getExtensionEventEmitter().fire({
type: 'Analysis_Completed',
data: { shouldResetRecomendation: true, shouldMoveToAnalyzePage: true, ...copyProblems },
});

const { decorations } = GenerateDecorations(results, editor);
editor.setDecorations(decorationType, []);
editor.setDecorations(decorationType, decorations);
currentQuestion.clear();
extensionEventEmitter.fire({
type: 'CURRENT_FILE',
data: { ...documentMetaData.editor.document },
});

return;
});
} catch (error: any) {
_debug.appendLine(error);
await Promise.allSettled([
analyzeState.set(copyProblems),
feedbackService.discardSuggestion(payload, session),
feedbackService.readSuggestion(payload, session),
]);

return;
}
currentQuestion.clear();
};

context.subscriptions.push(vscode.commands.registerCommand(command, commandHandler));
Expand Down
25 changes: 23 additions & 2 deletions ext-src/commands/EndorseSuggestion.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,8 @@
import * as vscode from 'vscode';
import CONSTANTS from '../constants';
import { feedbackService, FeedbackSuggestionPayload } from '../services';
import { Session } from '../state';
import { Analyze, Session } from '../state';
import { getExtensionEventEmitter } from '../events';

export type EndorseCommandHandler = { id: string; path: string };

Expand All @@ -12,17 +13,37 @@ export function activateEndorseCommand(
const command = CONSTANTS.endorseSuggestionCommand;

const commandHandler = async (args: EndorseCommandHandler) => {
const { id: problemId } = args;
const { id: problemId, path } = args;
const key = `${path}@@${problemId}`;

const extensionEventEmitter = getExtensionEventEmitter();

const analyzeState = new Analyze(context);
const analyzeStateValue = analyzeState.get()?.value;
if (!analyzeStateValue) return;

const sessionToken = new Session(context).get()?.value;
if (!sessionToken) return;

const copyProblems = { ...analyzeStateValue };

copyProblems[key].isDiscarded = false;
copyProblems[key].isEndorsed = true;
copyProblems[key].isViewed = true;

const payload: FeedbackSuggestionPayload = {
problemId,
discarded: false,
endorsed: true,
};
try {
await feedbackService.endorseSuggestion(payload, sessionToken);
await feedbackService.readSuggestion(payload, sessionToken);
await analyzeState.set(copyProblems);
extensionEventEmitter.fire({
type: 'Analysis_Completed',
data: { shouldResetRecomendation: false, shouldMoveToAnalyzePage: false, ...copyProblems },
});
} catch {
_debug?.appendLine(`Metabob: Error Endorsing Problem With ${args.id}`);
vscode.window.showErrorMessage(CONSTANTS.endorseCommandErrorMessage);
Expand Down
2 changes: 1 addition & 1 deletion ext-src/commands/FixSuggestion.ts
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,7 @@ export function activateFixSuggestionCommand(context: vscode.ExtensionContext):
},
});
} catch (error) {
debugChannel.appendLine(`Metabob: Error while `);
debugChannel.appendLine(`Metabob: Error while fixing suggestion ${JSON.stringify(error)}`);
}

vscode.commands.executeCommand('recommendation-panel-webview.focus');
Expand Down
22 changes: 11 additions & 11 deletions ext-src/commands/FocusRecommendation.ts
Original file line number Diff line number Diff line change
@@ -1,29 +1,29 @@
import * as vscode from 'vscode';
import { CurrentQuestion } from '../state/CurrentQuestion';
import { Problem } from '../types';
import _debug from '../debug';
import { getExtensionEventEmitter } from '../events';
import { Analyze } from '../state';

type FocusCommandHandler = { path: string; id: string; vuln: Problem; jobId: string };
export function activateFocusRecommendCommand(context: vscode.ExtensionContext): void {
const command = 'metabob.focusRecommend';

const commandHandler = async (args: FocusCommandHandler) => {
const { id, vuln, path } = args;
const key = `${path}@@${id}`;
_debug?.appendLine(`Current Detection Set for ${path} with Problem ${id} `);

const currentQuestionState = new CurrentQuestion(context);
const currentQuestion = currentQuestionState.get()?.value;
if (!currentQuestion) return;
const analyzeState = new Analyze(context);
const analyzeStateValue = analyzeState.get()?.value;
if (!analyzeStateValue) return;

currentQuestionState.set({
path,
id,
vuln,
isFix: false,
isReset: true,
});
const copyProblems = { ...analyzeStateValue };

copyProblems[key].isDiscarded = false;
copyProblems[key].isEndorsed = false;
copyProblems[key].isViewed = true;

await analyzeState.set({ ...copyProblems })
getExtensionEventEmitter().fire({
type: 'FIX_SUGGESTION',
data: {
Expand Down
1 change: 1 addition & 0 deletions ext-src/constants.ts
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@ const CONSTANTS = {
analyzeCommandQueueMessage: 'Metabob: Document is Queued',
analyzeCommandErrorMessage: 'Metabob: Error Analyzing the Document',
analyzeCommandTimeoutMessage: 'Metabob: Looks like the server is overloaded, please try again later',
applyRecommendationEror: 'Metabob: Could not apply recommendation to file',

// Error Constants
editorNotSelectorError: 'Metabob: kindly select an editor to perform this command',
Expand Down
Loading

0 comments on commit 798c3bd

Please sign in to comment.