Skip to content

Commit 1861da0

Browse files
authored
Merge pull request #310 from Achal1607/globalVars-refactored
Refactor globalVars into a Separate Class for Improved Encapsulation
2 parents 2141e42 + e7e5ad4 commit 1861da0

24 files changed

+255
-129
lines changed

vscode/src/commands/cache.ts

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -14,16 +14,16 @@
1414
limitations under the License.
1515
*/
1616
import { commands, window } from "vscode";
17-
import { globalVars } from "../extension";
1817
import { builtInCommands, extCommands } from "./commands";
1918
import { ICommand } from "./types";
2019
import { l10n } from "../localiser";
2120
import * as fs from 'fs';
2221
import * as path from 'path';
22+
import { globalState } from "../globalState";
2323

2424
const deleteCache = async () => {
2525
// TODO: Change workspace path to userdir path
26-
const storagePath = globalVars.extensionInfo.getWorkspaceStorage()?.fsPath;
26+
const storagePath = globalState.getExtensionContextInfo().getWorkspaceStorage()?.fsPath;
2727
if (!storagePath) {
2828
window.showErrorMessage(l10n.value("jdk.extension.cache.error_msg.cannotFindWrkSpacePath"));
2929
return;
@@ -38,9 +38,9 @@ const deleteCache = async () => {
3838
if (confirmation === yes) {
3939
const reloadWindowActionLabel = l10n.value("jdk.extension.cache.label.reloadWindow");
4040
try {
41-
await globalVars.clientPromise.stopClient();
42-
globalVars.deactivated = true;
43-
await globalVars.nbProcessManager?.killProcess(false);
41+
await globalState.getClientPromise().stopClient();
42+
globalState.setDeactivated(true);
43+
await globalState.getNbProcessManager()?.killProcess(false);
4444
await fs.promises.rmdir(userDir, { recursive: true });
4545
await window.showInformationMessage(l10n.value("jdk.extension.message.cacheDeleted"), reloadWindowActionLabel);
4646
} catch (err) {

vscode/src/commands/create.ts

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -20,12 +20,12 @@ import { l10n } from "../localiser";
2020
import * as os from 'os';
2121
import * as fs from 'fs';
2222
import { ICommand } from "./types";
23-
import { globalVars } from "../extension";
2423
import { getContextUri, isNbCommandRegistered } from "./utils";
2524
import { isString } from "../utils";
25+
import { globalState } from "../globalState";
2626

2727
const newFromTemplate = async (ctx: any, template: any) => {
28-
const client: LanguageClient = await globalVars.clientPromise.client;
28+
const client: LanguageClient = await globalState.getClientPromise().client;
2929
if (await isNbCommandRegistered(nbCommands.newFromTemplate)) {
3030
const workspaces = workspace.workspaceFolders;
3131

@@ -72,7 +72,7 @@ const newFromTemplate = async (ctx: any, template: any) => {
7272
}
7373

7474
const newProject = async (ctx: any) => {
75-
const client: LanguageClient = await globalVars.clientPromise.client;
75+
const client: LanguageClient = await globalState.getClientPromise().client;
7676
if (await isNbCommandRegistered(nbCommands.newProject)) {
7777
const res = await commands.executeCommand(nbCommands.newProject, getContextUri(ctx)?.toString());
7878
if (isString(res)) {

vscode/src/commands/navigation.ts

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -19,12 +19,12 @@ import { l10n } from "../localiser";
1919
import * as path from 'path';
2020
import { ICommand } from "./types";
2121
import { LanguageClient } from "vscode-languageclient/node";
22-
import { globalVars } from "../extension";
2322
import { LOGGER } from '../logger';
2423
import { getContextUri, isNbCommandRegistered, wrapCommandWithProgress } from "./utils";
24+
import { globalState } from "../globalState";
2525

2626
const goToTest = async (ctx: any) => {
27-
let client: LanguageClient = await globalVars.clientPromise.client;
27+
let client: LanguageClient = await globalState.getClientPromise().client;
2828
if (await isNbCommandRegistered(nbCommands.goToTest)) {
2929
try {
3030
const res: any = await commands.executeCommand(nbCommands.goToTest, getContextUri(ctx)?.toString());

vscode/src/commands/refactor.ts

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -18,9 +18,9 @@ import { ICommand } from "./types";
1818
import { extConstants } from "../constants";
1919
import { builtInCommands, extCommands, nbCommands } from "./commands";
2020
import { l10n } from "../localiser";
21-
import { globalVars } from "../extension";
2221
import { WorkspaceEdit } from 'vscode-languageserver-protocol';
2322
import { SymbolInformation } from 'vscode-languageclient';
23+
import { globalState } from "../globalState";
2424

2525
const goToSuperImplementationHandler = async () => {
2626
if (window.activeTextEditor?.document.languageId !== extConstants.LANGUAGE_ID) {
@@ -48,7 +48,7 @@ const surroundWithHandler = async (items: any) => {
4848
const selected: any = await window.showQuickPick(items, { placeHolder: l10n.value('jdk.extension.command.quickPick.placeholder.surroundWith') });
4949
if (selected) {
5050
if (selected.userData.edit) {
51-
const client = await globalVars.clientPromise.client;
51+
const client = await globalState.getClientPromise().client;
5252
const edit = await client.protocol2CodeConverter.asWorkspaceEdit(selected.userData.edit as WorkspaceEdit);
5353
await workspace.applyEdit(edit);
5454
await commands.executeCommand(builtInCommands.focusActiveEditorGroup);
@@ -60,7 +60,7 @@ const surroundWithHandler = async (items: any) => {
6060
const codeGenerateHandler = async (command: any, data: any) => {
6161
const edit: any = await commands.executeCommand(command, data);
6262
if (edit) {
63-
const client = await globalVars.clientPromise.client;
63+
const client = await globalState.getClientPromise().client;
6464
const wsEdit = await client.protocol2CodeConverter.asWorkspaceEdit(edit as WorkspaceEdit);
6565
await workspace.applyEdit(wsEdit);
6666
await commands.executeCommand(builtInCommands.focusActiveEditorGroup);
@@ -76,7 +76,7 @@ const completeAbstractMethodsHandler = async () => {
7676
}
7777

7878
const workspaceSymbolsHandler = async (query: any) => {
79-
const client = await globalVars.clientPromise.client;
79+
const client = await globalState.getClientPromise().client;
8080
return (await client.sendRequest<SymbolInformation[]>("workspace/symbol", { "query": query })) ?? [];
8181
}
8282

vscode/src/commands/runConfiguration.ts

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -15,13 +15,13 @@
1515
*/
1616

1717
import { extCommands } from "./commands";
18-
import { globalVars } from "../extension";
1918
import { configureRunSettings } from "../views/runConfiguration";
2019
import { ICommand } from "./types";
20+
import { globalState } from "../globalState";
2121

2222

2323
const configureRunSettingsHandler = (...params: any[]) => {
24-
configureRunSettings(globalVars.extensionInfo.getExtensionContext(), params);
24+
configureRunSettings(globalState.getExtensionContextInfo().getExtensionContext(), params);
2525
}
2626

2727

vscode/src/commands/utilCommands.ts

Lines changed: 3 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -13,21 +13,16 @@
1313
See the License for the specific language governing permissions and
1414
limitations under the License.
1515
*/
16-
import { globalVars } from "../extension";
16+
import { globalState } from "../globalState";
1717
import { extCommands } from "./commands";
1818
import { ICommand } from "./types";
1919

2020
const startupConditionHandler = () => {
21-
return globalVars.clientPromise.client;
21+
return globalState.getClientPromise().client;
2222
}
2323

2424
const addEventListenerHandler = async (eventName: any, listener: any) => {
25-
let ls = globalVars.listeners.get(eventName);
26-
if (!ls) {
27-
ls = [];
28-
globalVars.listeners.set(eventName, ls);
29-
}
30-
ls.push(listener);
25+
globalState.addListener(eventName, listener);
3126
}
3227

3328

vscode/src/commands/utils.ts

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -17,9 +17,9 @@ import { commands, OutputChannel, ProgressLocation, Uri, window } from "vscode";
1717
import { nbCommands } from "./commands";
1818
import { ProjectActionParams } from "../lsp/protocol";
1919
import { LanguageClient } from "vscode-languageclient/node";
20-
import { globalVars } from "../extension";
2120
import { l10n } from "../localiser";
2221
import { LOGGER } from "../logger";
22+
import { globalState } from "../globalState";
2323

2424
export const getContextUri = (ctx: any): Uri | undefined => {
2525
if (ctx?.fsPath) {
@@ -78,7 +78,7 @@ export const wrapProjectActionWithProgress = (action: string, configuration: str
7878
export const wrapCommandWithProgress = (lsCommand: string, title: string, log?: OutputChannel, ...args: any[]): Thenable<unknown> => {
7979
return window.withProgress({ location: ProgressLocation.Window }, p => {
8080
return new Promise(async (resolve, reject) => {
81-
let c: LanguageClient = await globalVars.clientPromise.client;
81+
let c: LanguageClient = await globalState.getClientPromise().client;
8282
if (await isNbCommandRegistered(lsCommand)) {
8383
p.report({ message: title });
8484
c.outputChannel.show(true);

vscode/src/configurations/handlers.ts

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -18,10 +18,10 @@ import { ConfigurationTarget, extensions, workspace, WorkspaceConfiguration } fr
1818
import { builtInConfigKeys, configKeys } from "./configuration";
1919
import { extConstants, NODE_WINDOWS_LABEL } from "../constants";
2020
import * as os from 'os';
21-
import { globalVars } from "../extension";
2221
import { LOGGER } from "../logger";
2322
import * as path from 'path';
2423
import * as fs from 'fs';
24+
import { globalState } from "../globalState";
2525

2626
export const getConfiguration = (key: string = extConstants.COMMAND_PREFIX): WorkspaceConfiguration => {
2727
return workspace.getConfiguration(key);
@@ -114,11 +114,12 @@ export const isDarkColorThemeHandler = (): boolean => {
114114
}
115115

116116
export const userdirHandler = (): string => {
117+
const extensionContextInfo = globalState.getExtensionContextInfo();
117118
const userdirScope = process.env['nbcode_userdir'] || getConfigurationValue(configKeys.userdir, "local");
118-
const workspaceStoragePath = globalVars.extensionInfo.getWorkspaceStorage()?.fsPath;
119+
const workspaceStoragePath = extensionContextInfo.getWorkspaceStorage()?.fsPath;
119120
const userdirParentDir = userdirScope === "local" && workspaceStoragePath
120121
? workspaceStoragePath
121-
: globalVars.extensionInfo.getGlobalStorage().fsPath;
122+
: extensionContextInfo.getGlobalStorage().fsPath;
122123

123124
if (!userdirParentDir) {
124125
throw new Error(`Cannot create path for ${userdirScope} directory.`);

vscode/src/configurations/listener.ts

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -15,15 +15,15 @@
1515
*/
1616

1717
import { ConfigurationChangeEvent, ExtensionContext, workspace } from "vscode";
18-
import { globalVars } from "../extension";
1918
import { userConfigsListened } from "./configuration";
2019
import { Disposable } from "vscode-languageclient";
20+
import { globalState } from "../globalState";
2121

2222
const configChangeHandler = (params: ConfigurationChangeEvent) => {
2323
userConfigsListened.forEach((config: string) => {
2424
const doesAffect = params.affectsConfiguration(config);
2525
if (doesAffect) {
26-
globalVars.clientPromise.restartExtension(globalVars.nbProcessManager, true);
26+
globalState.getClientPromise().restartExtension(globalState.getNbProcessManager(), true);
2727
}
2828
});
2929
}

vscode/src/debugger/debugger.ts

Lines changed: 9 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -22,10 +22,10 @@ import { DebugConnector } from '../lsp/protocol';
2222
import { extConstants } from '../constants';
2323
import { l10n } from '../localiser';
2424
import { StreamDebugAdapter } from './streamDebugAdapter';
25-
import { globalVars } from '../extension';
2625
import { extCommands, nbCommands } from '../commands/commands';
2726
import { argumentsNode, environmentVariablesNode, vmOptionsNode, workingDirectoryNode } from '../views/runConfiguration';
2827
import { initializeRunConfiguration } from '../utils';
28+
import { globalState } from '../globalState';
2929

3030
export function registerDebugger(context: ExtensionContext): void {
3131
let debugTrackerFactory = new NetBeansDebugAdapterTrackerFactory();
@@ -50,8 +50,9 @@ class NetBeansDebugAdapterTrackerFactory implements vscode.DebugAdapterTrackerFa
5050
createDebugAdapterTracker(_session: vscode.DebugSession): vscode.ProviderResult<vscode.DebugAdapterTracker> {
5151
return {
5252
onDidSendMessage(message: any): void {
53-
if (globalVars.testAdapter && message.type === 'event' && message.event === 'output') {
54-
globalVars.testAdapter.testOutput(message.body.output);
53+
const testAdapter = globalState.getTestAdapter();
54+
if (testAdapter && message.type === 'event' && message.event === 'output') {
55+
testAdapter.testOutput(message.body.output);
5556
}
5657
}
5758
}
@@ -64,18 +65,18 @@ class NetBeansDebugAdapterDescriptionFactory implements vscode.DebugAdapterDescr
6465
return new Promise<vscode.DebugAdapterDescriptor>((resolve, reject) => {
6566
let cnt = 10;
6667
const fnc = () => {
67-
if (globalVars.debugPort < 0) {
68+
if (globalState.getDebugPort() < 0) {
6869
if (cnt-- > 0) {
6970
setTimeout(fnc, 1000);
7071
} else {
7172
reject(new Error(l10n.value('jdk.extension.debugger.error_msg.debugAdapterNotInitialized')));
7273
}
7374
} else {
7475
// resolve(new vscode.DebugAdapterServer(debugPort));
75-
const socket = net.connect(globalVars.debugPort, "127.0.0.1", () => { });
76+
const socket = net.connect(globalState.getDebugPort(), "127.0.0.1", () => { });
7677
socket.on("connect", () => {
7778
const adapter = new StreamDebugAdapter();
78-
socket.write(globalVars.debugHash ? globalVars.debugHash : "");
79+
socket.write(globalState?.getDebugHash() || "");
7980
adapter.connect(socket, socket);
8081
resolve(new vscode.DebugAdapterInlineImplementation(adapter));
8182
});
@@ -94,7 +95,7 @@ class NetBeansConfigurationInitialProvider implements vscode.DebugConfigurationP
9495
}
9596

9697
async doProvideDebugConfigurations(folder: vscode.WorkspaceFolder | undefined, _token?: vscode.CancellationToken): Promise<vscode.DebugConfiguration[]> {
97-
let c: LanguageClient = await globalVars.clientPromise.client;
98+
let c: LanguageClient = await globalState.getClientPromise().client;
9899
if (!folder) {
99100
return [];
100101
}
@@ -145,7 +146,7 @@ class NetBeansConfigurationDynamicProvider implements vscode.DebugConfigurationP
145146
}
146147

147148
async doProvideDebugConfigurations(folder: vscode.WorkspaceFolder | undefined, context: ExtensionContext, commandValues: Map<string, string>, _token?: vscode.CancellationToken): Promise<vscode.DebugConfiguration[]> {
148-
let c: LanguageClient = await globalVars.clientPromise.client;
149+
let c: LanguageClient = await globalState.getClientPromise().client;
149150
if (!folder) {
150151
return [];
151152
}

vscode/src/extension.ts

Lines changed: 9 additions & 28 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
/*
2-
* Copyright (c) 2023, Oracle and/or its affiliates.
2+
* Copyright (c) 2024, Oracle and/or its affiliates.
33
*
44
* Licensed to the Apache Software Foundation (ASF) under one
55
* or more contributor license agreements. See the NOTICE file
@@ -19,44 +19,25 @@
1919
* under the License.
2020
*/
2121

22-
/* This file has been modified for Oracle Java SE extension */
23-
2422
'use strict';
2523

26-
import { ExtensionContext, TextEditorDecorationType, Uri } from 'vscode';
27-
import { NbTestAdapter } from './views/TestViewController';
28-
import { SetTextEditorDecorationParams } from './lsp/protocol';
24+
import { ExtensionContext } from 'vscode';
2925
import * as launchConfigurations from './launchConfigurations';
3026
import { extConstants } from './constants';
31-
import { ExtensionInfo } from './extensionInfo';
32-
import { ClientPromise } from './lsp/clientPromise';
33-
import { NbProcessManager } from './lsp/nbProcessManager';
3427
import { clientInit } from './lsp/initializer';
3528
import { subscribeCommands } from './commands/register';
3629
import { VSNetBeansAPI } from './lsp/types';
3730
import { registerDebugger } from './debugger/debugger';
3831
import { registerConfigChangeListeners } from './configurations/listener';
3932
import { registerFileProviders } from './lsp/listeners/textDocumentContentProvider';
40-
41-
export namespace globalVars {
42-
export const listeners = new Map<string, string[]>();
43-
export let extensionInfo: ExtensionInfo;
44-
export let clientPromise: ClientPromise;
45-
export let debugPort: number = -1;
46-
export let debugHash: string | undefined;
47-
export let deactivated: boolean = true;
48-
export let nbProcessManager: NbProcessManager | null;
49-
export let testAdapter: NbTestAdapter | undefined;
50-
export let decorations = new Map<string, TextEditorDecorationType>();
51-
export let decorationParamsByUri = new Map<Uri, SetTextEditorDecorationParams>();
52-
}
53-
33+
import { ExtensionContextInfo } from './extensionContextInfo';
34+
import { ClientPromise } from './lsp/clientPromise';
35+
import { globalState } from './globalState';
5436

5537
export function activate(context: ExtensionContext): VSNetBeansAPI {
56-
globalVars.clientPromise = new ClientPromise();
57-
globalVars.extensionInfo = new ExtensionInfo(context);
38+
globalState.initialize(new ExtensionContextInfo(context), new ClientPromise());
39+
globalState.getClientPromise().initialize();
5840

59-
globalVars.clientPromise.initialize();
6041
registerConfigChangeListeners(context);
6142
clientInit();
6243

@@ -78,10 +59,10 @@ export function activate(context: ExtensionContext): VSNetBeansAPI {
7859

7960

8061
export function deactivate(): Thenable<void> {
81-
const process = globalVars.nbProcessManager?.getProcess();
62+
const process = globalState.getNbProcessManager()?.getProcess();
8263
if (process != null) {
8364
process?.kill();
8465
}
85-
return globalVars.clientPromise.stopClient();
66+
return globalState.getClientPromise().stopClient();
8667
}
8768

vscode/src/extensionInfo.ts renamed to vscode/src/extensionContextInfo.ts

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -15,7 +15,7 @@
1515
*/
1616
import { Disposable, ExtensionContext } from "vscode";
1717

18-
export class ExtensionInfo {
18+
export class ExtensionContextInfo {
1919
constructor(private context: ExtensionContext) { }
2020

2121
getGlobalStorage = () => this.context.globalStorageUri;

0 commit comments

Comments
 (0)