Skip to content

Commit

Permalink
refactor: split activate() from handlers
Browse files Browse the repository at this point in the history
  • Loading branch information
yiqing-zhao committed Jun 19, 2024
1 parent 7447d82 commit c4bd30e
Show file tree
Hide file tree
Showing 5 changed files with 298 additions and 256 deletions.
3 changes: 2 additions & 1 deletion packages/vscode-extension/src/extension.ts
Original file line number Diff line number Diff line change
Expand Up @@ -75,6 +75,7 @@ import {
workspaceUri,
} from "./globalVariables";
import * as handlers from "./handlers";
import { activate as activateHandlers } from "./handlers/activate";
import { checkCopilotAccessHandler } from "./handlers/checkCopilotAccess";
import { checkCopilotCallback } from "./handlers/checkCopilotCallback";
import { checkSideloadingCallback } from "./handlers/checkSideloading";
Expand Down Expand Up @@ -146,7 +147,7 @@ export async function activate(context: vscode.ExtensionContext) {
}

// Call activate function of toolkit core.
handlers.activate();
activateHandlers();

// Init VSC context key
await initializeContextKey(context, isTeamsFxProject);
Expand Down
148 changes: 1 addition & 147 deletions packages/vscode-extension/src/handlers.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,13 +17,10 @@ import * as vscode from "vscode";
import {
AppPackageFolderName,
BuildFolderName,
ConfigFolderName,
CoreCallbackEvent,
CreateProjectResult,
Func,
FxError,
Inputs,
M365TokenProvider,
ManifestTemplateFileName,
ManifestUtil,
OptionItem,
Expand All @@ -49,7 +46,6 @@ import {
DepsManager,
DepsType,
FeatureFlags,
FxCore,
Hub,
InvalidProjectError,
JSONSyntaxError,
Expand All @@ -61,7 +57,6 @@ import {
featureFlagManager,
generateScaffoldingSummary,
getHashedEnv,
getProjectMetadata,
globalStateGet,
globalStateUpdate,
isUserCancelError,
Expand All @@ -73,9 +68,8 @@ import {
teamsDevPortalClient,
} from "@microsoft/teamsfx-core";
import { ExtensionContext, QuickPickItem, Uri, commands, env, window, workspace } from "vscode";
import commandController from "./commandController";
import azureAccountManager from "./commonlib/azureLogin";
import { signedIn, signedOut } from "./commonlib/common/constant";
import { signedIn } from "./commonlib/common/constant";
import VsCodeLogInstance from "./commonlib/log";
import M365TokenInstance from "./commonlib/m365Login";
import {
Expand All @@ -95,7 +89,6 @@ import { openHubWebClient } from "./debug/launch";
import { selectAndDebug } from "./debug/runIconHandler";
import { isLoginFailureError, showError, wrapError } from "./error/common";
import { ExtensionErrors, ExtensionSource } from "./error/error";
import * as exp from "./exp/index";
import { TreatmentVariableValue } from "./exp/treatmentVariables";
import {
context,
Expand All @@ -104,9 +97,6 @@ import {
isOfficeAddInProject,
isSPFxProject,
isTeamsFxProject,
setCommandIsRunning,
setCore,
setTools,
tools,
workspaceUri,
} from "./globalVariables";
Expand Down Expand Up @@ -149,112 +139,6 @@ import {
} from "./utils/telemetryUtils";
import { openFolder, openOfficeDevFolder } from "./utils/workspaceUtils";

export function activate(): Result<Void, FxError> {
const result: Result<Void, FxError> = ok(Void);
const validProject = isValidProject(workspaceUri?.fsPath);
if (validProject) {
const fixedProjectSettings = getProjectMetadata(workspaceUri?.fsPath);
ExtTelemetry.addSharedProperty(
TelemetryProperty.ProjectId,
fixedProjectSettings?.projectId as string
);
ExtTelemetry.sendTelemetryEvent(TelemetryEvent.OpenTeamsApp, {});
void azureAccountManager.setStatusChangeMap(
"successfully-sign-in-azure",
(status, token, accountInfo) => {
if (status === signedIn) {
void window.showInformationMessage(localize("teamstoolkit.handlers.azureSignIn"));
} else if (status === signedOut) {
void window.showInformationMessage(localize("teamstoolkit.handlers.azureSignOut"));
}
return Promise.resolve();
},
false
);
}
try {
const m365Login: M365TokenProvider = M365TokenInstance;
const m365NotificationCallback = (
status: string,
token: string | undefined,
accountInfo: Record<string, unknown> | undefined
) => {
if (status === signedIn) {
void window.showInformationMessage(localize("teamstoolkit.handlers.m365SignIn"));
} else if (status === signedOut) {
void window.showInformationMessage(localize("teamstoolkit.handlers.m365SignOut"));
}
return Promise.resolve();
};

void M365TokenInstance.setStatusChangeMap(
"successfully-sign-in-m365",
{ scopes: AppStudioScopes },
m365NotificationCallback,
false
);
setTools({
logProvider: VsCodeLogInstance,
tokenProvider: {
azureAccountProvider: azureAccountManager,
m365TokenProvider: m365Login,
},
telemetryReporter: ExtTelemetry.reporter,
ui: VS_CODE_UI,
expServiceProvider: exp.getExpService(),
});
setCore(new FxCore(tools));
core.on(CoreCallbackEvent.lock, async (command: string) => {
setCommandIsRunning(true);
await commandController.lockedByOperation(command);
});
core.on(CoreCallbackEvent.unlock, async (command: string) => {
setCommandIsRunning(false);
await commandController.unlockedByOperation(command);
});
const workspacePath = workspaceUri?.fsPath;
if (workspacePath) {
addFileSystemWatcher(workspacePath);
}

if (workspacePath) {
// refresh env tree when env config files added or deleted.
workspace.onDidCreateFiles(async (event) => {
await refreshEnvTreeOnFileChanged(workspacePath, event.files);
});

workspace.onDidDeleteFiles(async (event) => {
await refreshEnvTreeOnFileChanged(workspacePath, event.files);
});

workspace.onDidRenameFiles(async (event) => {
const files = [];
for (const f of event.files) {
files.push(f.newUri);
files.push(f.oldUri);
}

await refreshEnvTreeOnFileChanged(workspacePath, files);
});

workspace.onDidSaveTextDocument(async (event) => {
await refreshEnvTreeOnFileContentChanged(workspacePath, event.uri.fsPath);
});
}
} catch (e) {
const FxError: FxError = {
name: (e as Error).name,
source: ExtensionSource,
message: (e as Error).message,
stack: (e as Error).stack,
timestamp: new Date(),
};
void showError(FxError);
return err(FxError);
}
return result;
}

// only used for telemetry
export async function getSettingsVersion(): Promise<string | undefined> {
if (core) {
Expand All @@ -277,22 +161,6 @@ export async function getSettingsVersion(): Promise<string | undefined> {
return undefined;
}

async function refreshEnvTreeOnFileChanged(workspacePath: string, files: readonly Uri[]) {
let needRefresh = false;
for (const file of files) {
// check if file is env config
const res = await core.isEnvFile(workspacePath, file.fsPath);
if (res.isOk() && res.value) {
needRefresh = true;
break;
}
}

if (needRefresh) {
await envTreeProviderInstance.reloadEnvironments();
}
}

export function addFileSystemWatcher(workspacePath: string) {
if (isValidProject(workspaceUri?.fsPath)) {
const packageLockFileWatcher = vscode.workspace.createFileSystemWatcher("**/package-lock.json");
Expand Down Expand Up @@ -337,20 +205,6 @@ export async function sendSDKVersionTelemetry(filePath: string) {
});
}

async function refreshEnvTreeOnFileContentChanged(workspacePath: string, filePath: string) {
const projectSettingsPath = path.resolve(
workspacePath,
`.${ConfigFolderName}`,
"configs",
"projectSettings.json"
);

// check if file is project config
if (path.normalize(filePath) === path.normalize(projectSettingsPath)) {
await envTreeProviderInstance.reloadEnvironments();
}
}

export async function createNewProjectHandler(...args: any[]): Promise<Result<any, FxError>> {
ExtTelemetry.sendTelemetryEvent(TelemetryEvent.CreateProjectStart, getTriggerFromProperty(args));
let inputs: Inputs | undefined;
Expand Down
Loading

0 comments on commit c4bd30e

Please sign in to comment.