Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Tree view #7

Merged
merged 4 commits into from
Feb 23, 2025
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
14 changes: 14 additions & 0 deletions media/common/dep.svg
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
24 changes: 24 additions & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,31 @@
},
"icon": "icon.png",
"contributes": {
"viewsWelcome": [
{
"view": "aderyn-panel-diagnostics-provider",
"contents": "Visit the [Welcome Page](command:aderyn.commands.showOnboardPanel) to get started",
"when": "!aderyn-panel-diagnostics-provider.hasItems"
}
],
"viewsContainers": {
"activitybar": [
{
"id": "aderyn-panel-diagnostics",
"title": "Aderyn Diagnostics",
"icon": "media/common/dep.svg"
}
]
},
"views": {
"aderyn-panel-diagnostics": [
{
"id": "aderyn-panel-diagnostics-provider",
"name": "Aderyn Diagnostics",
"icon": "media/common/dep.svg",
"contextualTitle": "Aderyn Diagnostics"
}
],
"explorer": [
{
"type": "webview",
Expand Down
14 changes: 12 additions & 2 deletions src/extension.ts
Original file line number Diff line number Diff line change
@@ -1,15 +1,24 @@
import * as vscode from 'vscode';
import {
hasRecognizedProjectStructureAtWorkspaceRoot,
isKeyUsed,
isWindowsNotWSL,
Keys,
Logger,
} from './utils';

import {
createOrInitLspClient,
startServing,
stopServingIfOn,
createOrInitOnboardProvider,
createAderynStatusItem,
} from './state';

import { registerEditorCommands } from './commands';
import { registerWebviewPanels } from './webview-providers';
import { isKeyUsed, isWindowsNotWSL, Keys, Logger } from './utils';
import { registerStatusBarItems } from './state/statusbar/index';
import { registerDataProviders } from './panel-providers';

export function activate(context: vscode.ExtensionContext) {
if (isWindowsNotWSL()) {
Expand All @@ -25,13 +34,14 @@ export function activate(context: vscode.ExtensionContext) {
.then(() => registerWebviewPanels(context))
.then(() => registerEditorCommands(context))
.then(() => registerStatusBarItems(context))
.then(() => registerDataProviders(context))
.then(autoStartLspClientIfRequested);
}

async function autoStartLspClientIfRequested() {
const config = vscode.workspace.getConfiguration('aderyn.config');
const userPrefersAutoStart = config.get<boolean>('autoStart');
if (userPrefersAutoStart) {
if (userPrefersAutoStart && hasRecognizedProjectStructureAtWorkspaceRoot()) {
try {
startServing();
} catch (_ex) {
Expand Down
153 changes: 153 additions & 0 deletions src/panel-providers/diagnostics-panel.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,153 @@
import * as vscode from 'vscode';
import * as path from 'path';
import {
ensureWorkspacePreconditionsMetAndReturnProjectURI,
findProjectRoot,
} from '../utils/index';
import {
createAderynReportAndDeserialize,
isAderynAvailableOnPath,
} from '../utils/install/aderyn';
import { Report, IssueInstance, Issue } from '../utils/install/issues';
import { Logger } from '../utils/logger';

class AderynDiagnosticsProvider implements vscode.TreeDataProvider<DiagnosticItem> {
private _onDidChangeTreeData: vscode.EventEmitter<DiagnosticItem | undefined | void> =
new vscode.EventEmitter<DiagnosticItem | undefined | void>();
readonly onDidChangeTreeData: vscode.Event<DiagnosticItem | undefined | void> =
this._onDidChangeTreeData.event;

projectRootUri: string | null = null;

refresh(): void {
this._onDidChangeTreeData.fire();
}

getTreeItem(element: DiagnosticItem): vscode.TreeItem {
return element;
}

async getChildren(element?: DiagnosticItem): Promise<DiagnosticItem[]> {
if (!element) {
return this.prepareResults().then(this.getTopLevelItems);
}
if (element.itemKind == ItemKind.Category) {
return this.getIssueItems(element as CategoryItem);
}
if (element.itemKind == ItemKind.Issue) {
return this.getInstances(element as IssueItem);
}
return Promise.resolve([]);
}

async prepareResults(): Promise<Report | null> {
const logger = new Logger();
const aderynIsOnPath = await isAderynAvailableOnPath(logger);
if (aderynIsOnPath) {
const workspaceRoot =
ensureWorkspacePreconditionsMetAndReturnProjectURI(false);
if (!workspaceRoot) {
return Promise.reject('workspace pre-conditions unmet');
}
this.projectRootUri = findProjectRoot(workspaceRoot);
return await createAderynReportAndDeserialize(this.projectRootUri).catch(
(err) => {
logger.err(err);
vscode.window.showErrorMessage('Error fetching results from aderyn');
return null;
},
);
}
return null;
}

getTopLevelItems(report: Report | null): DiagnosticItem[] {
if (!report) {
return [];
}
const highIssues = report.highIssues.issues;
const lowIssues = report.lowIssues.issues;
return [new CategoryItem('High', highIssues), new CategoryItem('Low', lowIssues)];
}

getIssueItems(category: CategoryItem): DiagnosticItem[] {
return category.issues.map((issue) => new IssueItem(issue));
}

getInstances(issueItem: IssueItem): DiagnosticItem[] {
return issueItem.issue.instances.map(
(instance) => new InstanceItem(instance, this.projectRootUri ?? '.'),
);
}
}

const enum ItemKind {
Category,
Issue,
Instance,
}

export class DiagnosticItem extends vscode.TreeItem {
constructor(
public readonly label: string,
public readonly collapsibleState: vscode.TreeItemCollapsibleState,
public readonly itemKind: ItemKind,
) {
super(label, collapsibleState);
this.tooltip = `${this.label}`;
}
}

class CategoryItem extends DiagnosticItem {
constructor(
public readonly label: string,
public readonly issues: Issue[],
) {
super(
label,
issues.length > 0
? vscode.TreeItemCollapsibleState.Collapsed
: vscode.TreeItemCollapsibleState.Expanded,
ItemKind.Category,
);
this.tooltip = `${this.label} issues`;
}
}

class IssueItem extends DiagnosticItem {
constructor(public readonly issue: Issue) {
super(issue.title, vscode.TreeItemCollapsibleState.Collapsed, ItemKind.Issue);
this.tooltip = issue.description;
}
}

class InstanceItem extends DiagnosticItem {
constructor(
public readonly instance: IssueInstance,
projectRootUri: string,
) {
super(
`${instance.contractPath} Line: ${instance.lineNo} ${instance.srcChar}`,
vscode.TreeItemCollapsibleState.None,
ItemKind.Instance,
);
this.tooltip = instance.contractPath;
this.command = {
title: 'Go to file',
command: 'vscode.open',
arguments: [
vscode.Uri.file(path.join(projectRootUri, instance.contractPath)),
{
selection: new vscode.Range(
instance.lineNo - 1,
0,
instance.lineNo - 1,
1000,
),
},
],
};
}
}

export { AderynDiagnosticsProvider };
4 changes: 4 additions & 0 deletions src/panel-providers/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
import { AderynDiagnosticsProvider } from './diagnostics-panel';
import { registerDataProviders } from './registrations';

export { AderynDiagnosticsProvider, registerDataProviders };
19 changes: 19 additions & 0 deletions src/panel-providers/registrations.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
import * as vscode from 'vscode';

import { PanelProviders } from './variants';
import { AderynDiagnosticsProvider as D } from './diagnostics-panel';

function registerDataProviders(context: vscode.ExtensionContext) {
const diagnosticsDataProvider = new D();
const diagnosticsTreeView = vscode.window.createTreeView(PanelProviders.Diagnostics, {
treeDataProvider: diagnosticsDataProvider,
});
diagnosticsTreeView.onDidChangeVisibility((e) => {
if (e.visible) {
diagnosticsDataProvider.refresh();
}
});
context.subscriptions.push(diagnosticsTreeView);
}

export { registerDataProviders };
5 changes: 5 additions & 0 deletions src/panel-providers/variants.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
const enum PanelProviders {
Diagnostics = 'aderyn-panel-diagnostics-provider',
}

export { PanelProviders };
2 changes: 2 additions & 0 deletions src/utils/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import {
executeCommand,
isWindowsNotWSL,
ensureWorkspacePreconditionsMetAndReturnProjectURI,
hasRecognizedProjectStructureAtWorkspaceRoot,
} from './runtime';
import { ensureAderynIsInstalled } from './install';
import { isKeyUsed, Keys } from './keys';
Expand All @@ -12,6 +13,7 @@ import { readAderynConfigTemplate } from './metadata';

export {
findProjectRoot,
hasRecognizedProjectStructureAtWorkspaceRoot,
ensureWorkspacePreconditionsMetAndReturnProjectURI,
readAderynConfigTemplate,
isWindowsNotWSL,
Expand Down
22 changes: 20 additions & 2 deletions src/utils/install/aderyn.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,10 @@
import { executeCommand } from '../runtime';
import {
ensureWorkspacePreconditionsMetAndReturnProjectURI,
executeCommand,
findProjectRoot,
} from '../runtime';
import { Logger } from '../logger';
import { parseAderynReportFromJsonString, Report } from './issues';

/**
* Checks if the command "aderyn" is available on path in the shell
Expand All @@ -19,4 +24,17 @@ async function isAderynAvailableOnPath(logger: Logger): Promise<boolean> {
});
}

export { isAderynAvailableOnPath };
async function createAderynReportAndDeserialize(projectRootUri: string): Promise<Report> {
const cmd = `aderyn ${projectRootUri} -o report.json --stdout --skip-cloc`;
return executeCommand(cmd)
.then((text) => {
const match = text.match(/STDOUT START([\s\S]*?)STDOUT END/);
if (!match) {
throw new Error('corrupted json');
}
return match[1].trim();
})
.then((reportJson) => parseAderynReportFromJsonString(reportJson));
}

export { isAderynAvailableOnPath, createAderynReportAndDeserialize };
4 changes: 2 additions & 2 deletions src/utils/install/index.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import { Logger } from '../logger';
import { readPackageJson } from '../metadata';
import { hasReliableInternet } from '../runtime';
import { isAderynAvailableOnPath } from './aderyn';
import { isAderynAvailableOnPath, createAderynReportAndDeserialize } from './aderyn';
import {
whichAderyn,
installAderynWithAppropriateCmd,
Expand Down Expand Up @@ -155,4 +155,4 @@ async function ensureAderynIsInstalled(): Promise<void> {
}
}

export { ensureAderynIsInstalled };
export { ensureAderynIsInstalled, createAderynReportAndDeserialize };
Loading