Skip to content

Commit

Permalink
13 integrate command files (#33)
Browse files Browse the repository at this point in the history
* added userID to global store

* bug fix

---------

Co-authored-by: Nagarjun Sanji <[email protected]>
  • Loading branch information
nagarjunsanji and Nagarjun Sanji authored Aug 5, 2024
1 parent fc8ed1f commit bec5e4c
Show file tree
Hide file tree
Showing 8 changed files with 58 additions and 53 deletions.
12 changes: 12 additions & 0 deletions src/helpers/commandHelper.ts
Original file line number Diff line number Diff line change
Expand Up @@ -88,4 +88,16 @@ export class Command {
throw error;
}
}

public execute(command: string): Promise<string> {
return new Promise((resolve, reject) => {
exec(command, (error, stdout, stderr) => {
if (error) {
reject(new Error(`Execution error: ${stderr}`));
} else {
resolve(stdout.trim());
}
});
});
}
}
24 changes: 12 additions & 12 deletions src/helpers/commonHelper.ts
Original file line number Diff line number Diff line change
@@ -1,14 +1,14 @@
import { MessageStatus, Organization } from "../constants/index";
import * as crypto from "crypto";
import { Logger } from "./loggerHelper";
import { GlobalState } from "./globalState";
import { ShowInputBoxHelper } from "./showInputBoxHelper";
import { GlobalStore } from "./globalStore";

export class Common {
constructor(
private logger: typeof Logger,
private showInputBoxHelper: ShowInputBoxHelper,
private globalState: typeof GlobalState,
private globalStore: GlobalStore,
) {}

/**
Expand All @@ -34,19 +34,19 @@ export class Common {
*/
public async checkUserId(): Promise<void> {
try {
const userId = await this.globalState
.getInstance()
.getGlobalData(Organization.debrickedDataKey, "", Organization.userId);
const globalState = this.globalStore.getGlobalStateInstance();
let userId = await globalState?.getGlobalData(Organization.debrickedDataKey, "", Organization.userId);
if (!userId) {
const userHashCode = this.generateHashCode(new Date().toDateString());
const debrickedData: any = await this.globalState
.getInstance()
.getGlobalData(Organization.debrickedDataKey, {});
debrickedData[Organization.userId] = userHashCode;
await this.globalState.getInstance().setGlobalData(Organization.debrickedDataKey, debrickedData);
userId = this.generateHashCode(new Date().toDateString());
const debrickedData: any = await globalState?.getGlobalData(Organization.debrickedDataKey, {});
debrickedData[Organization.userId] = userId;
await globalState?.setGlobalData(Organization.debrickedDataKey, debrickedData);

this.logger.logMessageByStatus(MessageStatus.INFO, `New user_id generated: ${userHashCode}`);
this.logger.logMessageByStatus(MessageStatus.INFO, `New user_id generated: ${userId}`);
} else {
this.logger.logMessageByStatus(MessageStatus.INFO, `Existing user_id: ${userId}`);
}
this.globalStore.setUserId(userId);
} catch (error: any) {
throw error;
}
Expand Down
6 changes: 1 addition & 5 deletions src/helpers/debrickedDataHelper.ts
Original file line number Diff line number Diff line change
@@ -1,23 +1,19 @@
import { MessageStatus } from "../constants/index";
import path from "path";
import * as fs from "fs";
import { Logger } from "./loggerHelper";

export class DebrickedDataHelper {
constructor(private logger: typeof Logger) {}
constructor() {}

public createFile(filePath: string): void {
const dirPath = path.dirname(filePath);
if (!fs.existsSync(dirPath)) {
fs.mkdirSync(dirPath, { recursive: true });
this.logger.logMessageByStatus(MessageStatus.INFO, `New file created : ${filePath}`);
}
}

public createDir(dirPath: string): void {
if (!fs.existsSync(dirPath)) {
fs.mkdirSync(dirPath, { recursive: true });
this.logger.logMessageByStatus(MessageStatus.INFO, `New Directory created : ${dirPath}`);
}
}
}
16 changes: 16 additions & 0 deletions src/helpers/globalStore.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ import { GlobalState } from "./globalState";

export class GlobalStore {
private static instance: GlobalStore;
private userId: string | undefined;
private sequenceID: string | undefined;
private globalStateInstance: GlobalState | undefined;

Expand Down Expand Up @@ -43,4 +44,19 @@ export class GlobalStore {
public getGlobalStateInstance(): GlobalState | undefined {
return this.globalStateInstance;
}

/**
* Set a new userId.
*/
public setUserId(userId: string): void {
this.userId = userId;
}

/**
* Get the current userId.
* @returns The current userId.
*/
public getUserId(): string | undefined {
return this.userId;
}
}
15 changes: 6 additions & 9 deletions src/helpers/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -30,17 +30,14 @@ class IndexHelper {
*/
public async setupDebricked(context: vscode.ExtensionContext): Promise<void> {
try {
// Set up global error handlers
errorHandler.setupGlobalErrorHandlers();
GlobalState.initialize(context);

await this.commonHelper.checkUserId();
this.debrickedDataHelper.createDir(Organization.reportsFolderPath);
this.debrickedDataHelper.createDir(context.logUri.fsPath);

Logger.initialize(context);

errorHandler.setupGlobalErrorHandlers();
globalStore.setGlobalStateInstance(GlobalState.getInstance());

await this.commonHelper.checkUserId();
} catch (error: any) {
throw error;
}
Expand All @@ -49,18 +46,18 @@ class IndexHelper {

const statusBarMessageHelper = new StatusBarMessageHelper();
const showInputBoxHelper = new ShowInputBoxHelper();
const debrickedDataHelper = new DebrickedDataHelper(Logger);
const debrickedDataHelper = new DebrickedDataHelper();
const globalStore = GlobalStore.getInstance();

const authHelper = new AuthHelper(showInputBoxHelper, statusBarMessageHelper, Logger, GlobalState);
const errorHandler = new ErrorHandler(statusBarMessageHelper, Logger);
const commandHelper = new Command(authHelper, Logger);
const commonHelper = new Common(Logger, showInputBoxHelper, GlobalState);
const commonHelper = new Common(Logger, showInputBoxHelper, globalStore);
const gitHelper = new GitHelper(commandHelper, Logger, showInputBoxHelper, GlobalState);
const terminal = new Terminal(authHelper, Logger);
const apiClient = new ApiClient(authHelper, errorHandler, Logger);
const apiHelper = new ApiHelper(apiClient, Logger);
const installHelper = new InstallHelper(Logger, statusBarMessageHelper);
const installHelper = new InstallHelper(Logger, statusBarMessageHelper, commandHelper);
const fileHelper = new FileHelper(debrickedDataHelper, Logger);
const indexHelper = new IndexHelper(debrickedDataHelper, commonHelper);
const showQuickPickHelper = new ShowQuickPickHelper();
Expand Down
19 changes: 4 additions & 15 deletions src/helpers/installHelper.ts
Original file line number Diff line number Diff line change
@@ -1,10 +1,10 @@
import * as path from "path";
import * as os from "os";
import { exec } from "child_process";
import { Messages, MessageStatus, Organization } from "../constants/index";
import * as vscode from "vscode";
import { StatusBarMessageHelper } from "./statusBarMessageHelper";
import { Logger } from "./loggerHelper";
import { Command } from "./commandHelper";

export class InstallHelper {
private platform: string;
Expand All @@ -13,13 +13,14 @@ export class InstallHelper {
constructor(
private logger: typeof Logger,
private statusBarMessageHelper: StatusBarMessageHelper,
private commandHelper: Command,
) {
this.platform = os.platform();
this.logger.logMessageByStatus(MessageStatus.INFO, `Debricked running on: ${this.platform}`);
this.scriptDir = path.join(__dirname, "..", Organization.debrickedInstaller);
}

private getScriptPath(): { install: string; command: string } {
this.logger.logInfo(`Debricked running on: ${this.platform}`);
switch (this.platform) {
case Organization.osWin32:
return {
Expand All @@ -38,18 +39,6 @@ export class InstallHelper {
}
}

private executeCommand(command: string): Promise<string> {
return new Promise((resolve, reject) => {
exec(command, (error, stdout, stderr) => {
if (error) {
reject(new Error(`Execution error: ${stderr}`));
} else {
resolve(stdout.trim());
}
});
});
}

public async runInstallScript() {
await vscode.window.withProgress(
{
Expand All @@ -66,7 +55,7 @@ export class InstallHelper {
this.logger.logMessageByStatus(MessageStatus.INFO, `Starting installation...`);
const installCommand =
this.platform === Organization.osWin32 ? `"${install}"` : `${command} "${install}"`;
const installOutput = await this.executeCommand(installCommand);
const installOutput = await this.commandHelper.execute(installCommand);
this.logger.logMessageByStatus(MessageStatus.INFO, `${installOutput}`);
this.logger.logMessageByStatus(MessageStatus.INFO, `${Messages.INSTALLATION_SUCCESS}`);
this.statusBarMessageHelper.showInformationMessage("CLI installed successfully");
Expand Down
17 changes: 6 additions & 11 deletions src/helpers/loggerHelper.ts
Original file line number Diff line number Diff line change
@@ -1,17 +1,16 @@
import * as fs from "fs";
import * as path from "path";
import { Organization, MessageStatus } from "../constants/index";
import { GlobalState } from "./globalState";
import * as vscode from "vscode";
import { GlobalStore } from "./globalStore";

export class Logger {
private static logDirPath = path.join(Organization.debrickedInstalledDir, Organization.debrickedFolder);
private static logFilePath: string;

public static initialize(context: vscode.ExtensionContext) {
public static async initialize(context: vscode.ExtensionContext) {
const logDir = context.logUri.fsPath;
Logger.logFilePath = path.join(logDir, Organization.logFile);
Logger.logFilePath = await path.join(logDir, Organization.logFile);
}

public static async openLogFile() {
Expand All @@ -20,23 +19,19 @@ export class Logger {
await vscode.window.showTextDocument(document);
}

public static setLogFile(fileName: string) {
Logger.logFilePath = path.join(Logger.logDirPath, fileName);
public static async setLogFile(fileName: string) {
Logger.logFilePath = await path.join(Logger.logDirPath, fileName);
}

private static async writeLog(message: string) {
const timestamp = new Date().toISOString();
const userId = await GlobalState.getInstance().getGlobalData(
Organization.debrickedDataKey,
"",
Organization.userId,
);
const userId = GlobalStore.getInstance().getUserId();
const sequenceId = GlobalStore.getInstance().getSequenceID()
? `[seq_id:${GlobalStore.getInstance().getSequenceID()}]`
: "";

const logEntry = `[${timestamp}] [user_id:${userId}] ${sequenceId} ${message}\n`;
fs.appendFileSync(Logger.logFilePath, logEntry, "utf-8");
await fs.appendFileSync(Logger.logFilePath, logEntry, "utf-8");
}

public static async logMessage(message: string) {
Expand Down
2 changes: 1 addition & 1 deletion src/services/baseCommandService.ts
Original file line number Diff line number Diff line change
Expand Up @@ -138,7 +138,7 @@ export class BaseCommandService {
}
}

static async login(updateCredentials: boolean = false) {
static async login(updateCredentials: boolean = true) {
try {
Logger.logInfo("Register login");
globalStore.setSequenceID(commonHelper.generateHashCode());
Expand Down

0 comments on commit bec5e4c

Please sign in to comment.