Skip to content

Commit

Permalink
Bug fix (#70)
Browse files Browse the repository at this point in the history
* added enum

* bug fix for watcher

* bug fix

* fix

* bug fix

* handled uncaught error

* fixed package.json error

* bug fix

* cleanup

* removed files command

* bug fix

* bug fix

* test case fix

* fixed immediate effect is not applying

---------

Co-authored-by: Nagarjun Sanji <[email protected]>
Co-authored-by: Rajpreet Singh <[email protected]>
  • Loading branch information
3 people authored Oct 9, 2024
1 parent dcada1e commit c374670
Show file tree
Hide file tree
Showing 24 changed files with 322 additions and 432 deletions.
4 changes: 4 additions & 0 deletions .github/workflows/ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -113,6 +113,10 @@ jobs:
name: coverage
path: coverage/
retention-days: 10
if-no-files-found: warn
compression-level: 6
overwrite: false
include-hidden-files: false

cleanup:
runs-on: ubuntu-latest
Expand Down
16 changes: 13 additions & 3 deletions .vscode/settings.json
Original file line number Diff line number Diff line change
Expand Up @@ -26,8 +26,18 @@
"editor.codeActionsOnSave": {
"source.fixAll.eslint": "always"
},
"eslint.validate": ["javascript", "javascriptreact", "typescript", "typescriptreact"],
"eslint.validate": [
"javascript",
"javascriptreact",
"typescript",
"typescriptreact"
],
"editor.formatOnSave": true,
"cSpell.words": ["automations", "CALLGRAPH", "debricked", "uninstallation"],
"cSpell.words": [
"automations",
"CALLGRAPH",
"debricked",
"uninstallation"
],
"editor.defaultFormatter": "esbenp.prettier-vscode"
}
}
4 changes: 2 additions & 2 deletions esbuild.js
Original file line number Diff line number Diff line change
Expand Up @@ -45,8 +45,8 @@ async function main() {
project: "visual-studio-code-extensions",
url: "https://sentry.debricked.com/",
release: {
name: "vs-code-extension@" + process.env.LATEST_TAG,
dist: process.env.LATEST_TAG,
name: `vs-code-extension@${process.env.LATEST_TAG || "0.0.0"}`,
dist: process.env.LATEST_TAG || "0.0.0",
cleanArtifacts: true,
},
}),
Expand Down
16 changes: 2 additions & 14 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@
"hoverProvider": "true"
},
"activationEvents": [
"workspaceContains:package.json"
"workspaceContains:**/package.json"
],
"main": "./dist/extension.js",
"repository": {
Expand Down Expand Up @@ -88,18 +88,6 @@
"category": "debricked",
"icon": "$(debug-start)"
},
{
"command": "debricked.files",
"title": "Analyze files",
"category": "debricked",
"icon": "$(files)"
},
{
"command": "debricked.files.find",
"title": "Find all dependency files in inputted path",
"category": "debricked",
"icon": "$(search)"
},
{
"command": "debricked.auth.login",
"title": "Authenticate debricked user",
Expand Down Expand Up @@ -184,4 +172,4 @@
"mock-fs": "^5.2.0",
"proxyquire": "^2.1.3"
}
}
}
11 changes: 1 addition & 10 deletions src/commands/debrickedCommand.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import * as vscode from "vscode";
import { DebrickedCommands } from "../constants/index";
import { baseCommandService, scanService, fileService, authService } from "../services";
import { baseCommandService, scanService, authService } from "../services";
import { Logger, SentryHelper, errorHandler } from "../helpers";

export class DebrickedCommand {
Expand All @@ -9,7 +9,6 @@ export class DebrickedCommand {
Logger.logInfo("Started registering commands");

const baseSubCommands = DebrickedCommands.BASE_COMMAND.sub_commands;
const fileSubCommands = DebrickedCommands.FILES.sub_commands;
const authSubCommands = DebrickedCommands.AUTH.sub_commands;

// Register base command
Expand Down Expand Up @@ -37,14 +36,6 @@ export class DebrickedCommand {

// Register scan command
this.registerCommand(context, DebrickedCommands.SCAN.command, scanService.scan);

// Register files command
this.registerCommand(context, DebrickedCommands.FILES.command, fileService.filesService);

// Register file sub-commands
if (fileSubCommands) {
this.registerCommand(context, fileSubCommands[0].command, fileService.findFilesService);
}
} catch (error) {
errorHandler.handleError(error);
} finally {
Expand Down
9 changes: 2 additions & 7 deletions src/constants/debricked_cli.ts
Original file line number Diff line number Diff line change
Expand Up @@ -119,7 +119,7 @@ export class DebrickedCommands {
label: "JSON",
flag: "-j",
description:
'Print files in JSON format\nFormat:\n[\n{\n"manifestFile": "package.json",\n"lockFiles": [\n"yarn.lock"\n]\n}]',
'Print files in JSON format - Format:[{"manifestFile": "package.json","lockFiles": ["yarn.lock"]}]',
},
{
label: "Lockfile",
Expand Down Expand Up @@ -308,12 +308,7 @@ export class DebrickedCommands {
};

static getAllCommands(): DebrickedCommandNode[] {
return [
DebrickedCommands.BASE_COMMAND,
DebrickedCommands.SCAN,
DebrickedCommands.FILES,
DebrickedCommands.AUTH,
];
return [DebrickedCommands.BASE_COMMAND, DebrickedCommands.SCAN, DebrickedCommands.AUTH];
}

static getCommand(commandName: string): DebrickedCommandNode | undefined {
Expand Down
4 changes: 4 additions & 0 deletions src/constants/enums.ts
Original file line number Diff line number Diff line change
Expand Up @@ -25,3 +25,7 @@ export enum TokenType {
ACCESS = "access",
BEARER = "bearer",
}

export enum SupportedFilesToScan {
PACKAGE_JSON = "package.json",
}
3 changes: 2 additions & 1 deletion src/constants/index.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { DebrickedCommands } from "./debricked_cli";
import { Messages } from "./messages";
import { MessageStatus, Environment, TokenType } from "./enums";
import { MessageStatus, Environment, TokenType, SupportedFilesToScan } from "./enums";
import { Organization } from "./organization";
import { SecondService } from "./secondService";
import { Regex } from "./regex";
Expand All @@ -19,4 +19,5 @@ export {
Environment,
TokenType,
Icons,
SupportedFilesToScan,
};
4 changes: 2 additions & 2 deletions src/constants/organization.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,12 +2,12 @@ import * as path from "path";
import * as vscode from "vscode";
import * as os from "os";
import * as fs from "fs";
import { Environment } from "./enums";
import { Environment, SupportedFilesToScan } from "./enums";

export class Organization {
static readonly debrickedRootDir = path.join(__dirname, "../");
static readonly packageJson = JSON.parse(
fs.readFileSync(path.join(Organization.debrickedRootDir, "package.json")).toString(),
fs.readFileSync(path.join(Organization.debrickedRootDir, SupportedFilesToScan.PACKAGE_JSON)).toString(),
);

static readonly name = Organization.packageJson.displayName;
Expand Down
21 changes: 12 additions & 9 deletions src/extension.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ import { debrickedCommand } from "./commands";
import { DebrickedCommandsTreeDataProvider, providers } from "./providers";
import { Environment, MessageStatus, Organization } from "./constants/index";
import { baseCommandService } from "./services";
import { watchers } from "watcher";
import { ReportWatcher, watchers, WorkSpaceWatcher } from "watcher";

export async function activate(context: vscode.ExtensionContext) {
await indexHelper.setupDebricked(context);
Expand Down Expand Up @@ -60,24 +60,27 @@ export async function activate(context: vscode.ExtensionContext) {
await baseCommandService.login(false);
}
}

// Add file watcher for all files found from 'debricked files find'
await watchers.registerWatcher(context);
await providers.registerDependencyPolicyProvider(context); // after adding watcher and scanning we should add the policy provider

progress.report({ message: "Debricked extension is ready to use", increment: 100 - progressCount });
await new Promise((resolve) => setTimeout(resolve, 1000)); // added for showing the last progress info
progress.report({ message: "Extension is ready to use", increment: (progressCount += 20) });
} catch (error: any) {
errorHandler.handleError(error);
} finally {
Logger.logMessageByStatus(MessageStatus.INFO, "activation has finished.");
}
},
);
// Add file watcher for all manifest files
await watchers.registerWatcher(context);
providers.registerDependencyPolicyProvider(context); // after adding watcher and scanning we should add the policy provider
}

// This method is called when your extension is deactivated
export async function deactivate() {
export async function deactivate(context: vscode.ExtensionContext) {
const workSpaceWatcher = new WorkSpaceWatcher(context);
await workSpaceWatcher.dispose();

const reportWatcher = new ReportWatcher();
await reportWatcher.stop();

SentryHelper.setTransactionName(`Deactivate ${Organization.name}`);
Logger.logMessageByStatus(MessageStatus.INFO, "Deactivate Debricked VS Code Extension");
SentryHelper.close();
Expand Down
10 changes: 5 additions & 5 deletions src/helpers/commonHelper.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { MessageStatus, Organization } from "../constants/index";
import { MessageStatus, Organization, SupportedFilesToScan } from "../constants/index";
import * as crypto from "crypto";
import { Logger } from "./loggerHelper";
import { ShowInputBoxHelper } from "./showInputBoxHelper";
Expand Down Expand Up @@ -68,9 +68,7 @@ export class Common {
}

public async isCurrentDocManifestFile(document: vscode.TextDocument) {
const selectedRepoName = this.globalStore.getRepository();
const manifestFiles = await this.globalStore.getGlobalStateInstance()?.getGlobalData(selectedRepoName)
.filesToScan;
const manifestFiles = Object.values(SupportedFilesToScan);
let currentManifestFile = path.basename(document.fileName);
currentManifestFile = currentManifestFile.endsWith(".git")
? currentManifestFile.slice(0, -4)
Expand Down Expand Up @@ -114,7 +112,9 @@ export class Common {
* @returns A promise that resolves to true if the repository is supported (contains a package.json file), false otherwise.
*/
public async isCurrentRepoSupported(showMsg = true): Promise<boolean> {
const uri = (await vscode.workspace.findFiles("**/package.json", "**/node_modules/**", 1)).length;
const uri = (
await vscode.workspace.findFiles(`**/${SupportedFilesToScan.PACKAGE_JSON}`, "**/node_modules/**", 1)
).length;
if (!uri) {
if (showMsg) {
this.statusBarMessageHelper.showInformationMessage("No files found to scan.");
Expand Down
9 changes: 9 additions & 0 deletions src/helpers/globalStore.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ export class GlobalStore {
private commitId!: number;
private packages!: Map<string, Package>;
private vulnerableData!: Map<string, DependencyVulnerability[]>;
private isScanningInProgress = false;

public static getInstance(): GlobalStore {
if (!GlobalStore.instance) {
Expand Down Expand Up @@ -95,4 +96,12 @@ export class GlobalStore {
public getVulnerableData(): Map<string, DependencyVulnerability[]> {
return this.vulnerableData;
}

public getScanningProgress() {
return this.isScanningInProgress;
}

public setScanningProgress(isScanningInProgress: boolean) {
this.isScanningInProgress = isScanningInProgress;
}
}
98 changes: 51 additions & 47 deletions src/providers/dependencyPolicyProvider.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import { Package } from "types";
import { commonHelper, globalStore } from "../helpers";
import { commonHelper, errorHandler, globalStore } from "../helpers";
import * as vscode from "vscode";
import { PolicyTriggerEvents, SecondService } from "../constants";
import { PolicyTriggerEvents, SecondService, SupportedFilesToScan } from "../constants";

export class DependencyPolicyProvider implements vscode.CodeActionProvider {
constructor(private diagnosticCollection: vscode.DiagnosticCollection) {}
Expand All @@ -11,62 +11,66 @@ export class DependencyPolicyProvider implements vscode.CodeActionProvider {
}

async checkPolicyViolation(document: vscode.TextDocument) {
// Check if the current file is a manifest file
const { isManifestFile, currentManifestFile } = await commonHelper.isCurrentDocManifestFile(document);
try {
// Check if the current file is a manifest file
const { isManifestFile, currentManifestFile } = await commonHelper.isCurrentDocManifestFile(document);

if (!isManifestFile) {
return;
}
if (!isManifestFile) {
return;
}

if (currentManifestFile === "package.json") {
const diagnostics: vscode.Diagnostic[] = [];
const content = document.getText();
const packages: Map<string, Package> = globalStore.getPackages();
if (currentManifestFile === SupportedFilesToScan.PACKAGE_JSON) {
const diagnostics: vscode.Diagnostic[] = [];
const content = document.getText();
const packages: Map<string, Package> = globalStore.getPackages();

if (packages && packages.size > 0) {
const manifestData = JSON.parse(content) || {};
const allDependencies = {
...manifestData.dependencies,
...manifestData.devDependencies,
};
if (content && packages && packages.size > 0) {
const manifestData = JSON.parse(content) || {};
const allDependencies = {
...manifestData.dependencies,
...manifestData.devDependencies,
};

for (const [packageName, packageData] of packages) {
if (packageName in allDependencies) {
const range = this.findDependencyRange(document, packageName);
if (range) {
let diagnostic: vscode.Diagnostic | undefined;
packageData.policyRules?.forEach((rule) => {
if (rule.ruleActions?.includes(PolicyTriggerEvents.FAIL_PIPELINE)) {
diagnostic = new vscode.Diagnostic(
range,
`Dependency ${packageName} failed the pipeline`,
vscode.DiagnosticSeverity.Error,
);
} else if (rule.ruleActions?.includes(PolicyTriggerEvents.WARN_PIPELINE)) {
diagnostic = new vscode.Diagnostic(
range,
`Dependency ${packageName} triggered a pipeline warning`,
vscode.DiagnosticSeverity.Warning,
);
}
});
for (const [packageName, packageData] of packages) {
if (packageName in allDependencies) {
const range = this.findDependencyRange(document, packageName);
if (range) {
let diagnostic: vscode.Diagnostic | undefined;
packageData.policyRules?.forEach((rule) => {
if (rule.ruleActions?.includes(PolicyTriggerEvents.FAIL_PIPELINE)) {
diagnostic = new vscode.Diagnostic(
range,
`Dependency ${packageName} failed the pipeline`,
vscode.DiagnosticSeverity.Error,
);
} else if (rule.ruleActions?.includes(PolicyTriggerEvents.WARN_PIPELINE)) {
diagnostic = new vscode.Diagnostic(
range,
`Dependency ${packageName} triggered a pipeline warning`,
vscode.DiagnosticSeverity.Warning,
);
}
});

if (diagnostic) {
diagnostic.code = {
value: packageData.cve ?? "Unknown reason",
target: vscode.Uri.parse(packageData.cveLink ?? SecondService.debrickedBaseUrl),
};
diagnostics.push(diagnostic);
if (diagnostic) {
diagnostic.code = {
value: packageData.cve ?? "Unknown reason",
target: vscode.Uri.parse(packageData.cveLink ?? SecondService.debrickedBaseUrl),
};
diagnostics.push(diagnostic);
}
}
}
}
}
}

const uri = document.uri;
if (!uri.path.endsWith(".git")) {
this.diagnosticCollection.set(uri, diagnostics);
const uri = document.uri;
if (!uri.path.endsWith(".git")) {
this.diagnosticCollection.set(uri, diagnostics);
}
}
} catch (error) {
errorHandler.handleError(error);
}
}

Expand Down
Loading

0 comments on commit c374670

Please sign in to comment.