Skip to content

Commit a961988

Browse files
authored
feat: ability to auto-update the language definitions on settings change (#53)
* feat: enable the language definitions to be auto-updated on settings change - Added new `updateLanguageDefinitions` function in Configuration class to update the language definitions. - Refactored the `onDidChangeConfiguration` event in the `activate` function of the extension to auto-update the language definitions and reconfigure the comment blocks when a user changes the settings. It uses the new `updateLanguageDefinitions` function to update the definitions before reconfiguring the comment blocks. - Removed the old `reloadRequiredSettings` array and the `showReloadMessage` function. * perf: cache default configs to reduce redundant repeated disk reads. - Added new Configuration class properties: - `defaultMultiLineConfig` to store the default multi-line configuration object. - `languagesToSkip` to store the languages to skip object. - Refactored `getLanguagesToSkip` method to get the languages from the new `languagesToSkip` class property instead of repeatedly reading the `skip-languages.jsonc` file from disk on every loop iteration of the `findAllLanguageConfigFilePaths` method. - Refactored `setLanguageConfiguration` method to get the default config from the new `defaultMultiLineConfig` class property instead of repeatedly reading the `default-multi-line-config.json` file from disk on every loop iteration of the `configureCommentBlocks` method. - Added a once-per-activation disk read of the `default-multi-line-config.json` and `skip-languages.jsonc` files in the Configuration `constructor` method, and add their contents to the respective new properties. This caches the JSON objects in memory ready for later use, enhancing performance by not reading them from disk on every loop iteration. * perf: only write language definitions to file in development mode. Writing to the auto generated language definition files is not very useful in production and are only helpful in development. In production, they are only ever read from disk to log their data for debugging. So for performance, they should only be written when in development/testing mode, and the updated definitions should only be cached in memory in production mode. - Removed the `writeCommentLanguageDefinitionsToJsonFile` method calls from the `constructor` and `updateLanguageDefinitions` methods. - Refactored `writeCommentLanguageDefinitionsToJsonFile` method: - Changed the visibility of the method from `private` to `public`, so it can be called from outside of the class. - Extracted the call to the `convertMapToReversedObject` utils function into a new method: `getSingleLineLanguageDefinitions`. This method returns the formatted and reversed single-line definitions object ready for logging or writing to JSON file. - Extracted the `Object.fromEntries` call into a new method: `getMultiLineLanguageDefinitions`. This method returns the formatted multi-line definitions object ready for logging or writing to JSON file. - Changed the `writeJsonFile` method calls to get the data from the 2 new methods instead of the old removed variables. - Changed the logging of the language definitions in `logDebugInfo` method to get the data from the new `getMultiLineLanguageDefinitions` and `getSingleLineLanguageDefinitions` methods, instead of reading directly from disk. - Added a conditional in the `activate` function to only run the `writeCommentLanguageDefinitionsToJsonFile` Configuration method when the context of the extension is not running in production (ie. it's running in development or testing mode). The same conditional is added into the configuration change event so when the definitions auto update they are written to the files in development/testing mode. * chore(tsconfig): enable auto type acquisition This helps vscode to show intellisense on native JS functions. * fix: auto-update definitions on change of the multi-line comments override. While adding a multi-line override in the `overrideDefaultLanguageMultiLineComments` setting auto-updated the language definitions correctly and used the override style, removing the override didn't work and it was still in place internally in vscode, and the extension's auto-complete no-longer worked. This happened because the override was inadvertently changing the multi-line style in the cached internal language config whilst also changing it on the shallow-copy for the immediate setting into vscode. So without ever changing it back as it was never supposed to be changed, the override was still apart of the extension's cached language configs making it permanent and breaking functionality. - Fixed by deep-cloning the `internalLangConfig` using JavaScript's `structuredClone` function in `setLanguageConfiguration` method so mutations (like comment overrides) never write back into the cached `languageConfigs` Map, which prevents pollution during definition auto-updates. - Added deep-cloning of the comments object in the cached `defaultMultiLineConfig` using `structuredClone` to prevent shared references and accidental mutations down the line during the fallback assignment. - Update comment override assignment to construct a new block comment tuple while preserving the ending, instead of mutating the existing array in place.
1 parent 3b58c94 commit a961988

3 files changed

Lines changed: 107 additions & 55 deletions

File tree

src/configuration.ts

Lines changed: 73 additions & 29 deletions
Original file line numberDiff line numberDiff line change
@@ -76,17 +76,32 @@ export class Configuration {
7676
*/
7777
private readonly multiLineLangDefinitionFilePath: string = `${this.autoGeneratedDir}/multi-line-languages.json`;
7878

79+
/**
80+
* The default multi-line configuration.
81+
*/
82+
private readonly defaultMultiLineConfig: vscode.LanguageConfiguration;
83+
84+
/**
85+
* The languages to skip, like plaintext, that don't have comment syntax.
86+
*/
87+
private readonly languagesToSkip: JsonObject;
88+
7989
/***********
8090
* Methods *
8191
***********/
8292

8393
public constructor() {
94+
const configPath = `${__dirname}/../../config`;
95+
// Read the default multi-line config from the JSON file and cache it for later use.
96+
this.defaultMultiLineConfig = utils.readJsonFile(`${configPath}/default-multi-line-config.json`) as vscode.LanguageConfiguration;
97+
// Read the languages to skip from the JSON file and cache it for later use.
98+
this.languagesToSkip = utils.readJsonFile(`${configPath}/skip-languages.jsonc`);
99+
84100
this.findAllLanguageConfigFilePaths();
85101
this.setLanguageConfigDefinitions();
86102

87103
this.setMultiLineCommentLanguageDefinitions();
88104
this.setSingleLineCommentLanguageDefinitions();
89-
this.writeCommentLanguageDefinitionsToJsonFile();
90105

91106
this.logDebugInfo();
92107
}
@@ -300,8 +315,7 @@ export class Configuration {
300315
* @returns {JsonArray}
301316
*/
302317
private getLanguagesToSkip(): JsonArray {
303-
const json = utils.readJsonFile(`${__dirname}/../../config/skip-languages.jsonc`);
304-
return json.languages as JsonArray;
318+
return this.languagesToSkip.languages as JsonArray;
305319
}
306320

307321
/**
@@ -662,24 +676,53 @@ export class Configuration {
662676
this.singleLineBlocksMap.set("customSupportedLanguages", new Map([...tempMap].sort()));
663677
}
664678

679+
/**
680+
* Get the single-line language definitions object
681+
* formatted and reversed by comment style for
682+
* logging and development debug file output.
683+
*
684+
* @returns {SingleLineLanguageDefinitions}
685+
*/
686+
public getSingleLineLanguageDefinitions(): SingleLineLanguageDefinitions {
687+
return utils.convertMapToReversedObject<SingleLineLanguageDefinitions>(this.singleLineBlocksMap);
688+
}
689+
690+
/**
691+
* Get the multi-line language definitions object
692+
* formatted for logging and development debug file output.
693+
*
694+
* @returns {MultiLineLanguageDefinitions}
695+
*/
696+
public getMultiLineLanguageDefinitions(): MultiLineLanguageDefinitions {
697+
return Object.fromEntries(this.multiLineBlocksMap) as unknown as MultiLineLanguageDefinitions;
698+
}
699+
665700
/**
666701
* Write Comment Language Definitions to the respective JSON file:
667702
* either multi-line-languages.json, or single-line-languages.json.
668703
*/
669-
private writeCommentLanguageDefinitionsToJsonFile() {
704+
public writeCommentLanguageDefinitionsToJsonFile() {
670705
// Ensure the auto-generated directory exists.
671706
utils.ensureDirExists(this.autoGeneratedDir);
672707

673-
// Convert the singleLineBlocksMap to an object.
674-
const singleLineData = utils.convertMapToReversedObject<SingleLineLanguageDefinitions>(this.singleLineBlocksMap);
675-
676-
const multiLineData = Object.fromEntries(this.multiLineBlocksMap) as unknown as MultiLineLanguageDefinitions;
677-
678708
// Write into the single-line-languages.json file.
679-
utils.writeJsonFile(this.singleLineLangDefinitionFilePath, singleLineData);
709+
utils.writeJsonFile(this.singleLineLangDefinitionFilePath, this.getSingleLineLanguageDefinitions());
680710

681711
// Write into the multi-line-languages.json file.
682-
utils.writeJsonFile(this.multiLineLangDefinitionFilePath, multiLineData);
712+
utils.writeJsonFile(this.multiLineLangDefinitionFilePath, this.getMultiLineLanguageDefinitions());
713+
}
714+
715+
/**
716+
* Update language definitions.
717+
*/
718+
public updateLanguageDefinitions() {
719+
// Remove all elements from the current Map, so we can update
720+
// the definitions with an empty Map.
721+
this.singleLineBlocksMap.clear();
722+
this.multiLineBlocksMap.clear();
723+
// Update the definitions.
724+
this.setSingleLineCommentLanguageDefinitions();
725+
this.setMultiLineCommentLanguageDefinitions();
683726
}
684727

685728
/**
@@ -693,7 +736,7 @@ export class Configuration {
693736
*
694737
* This method performs the following tasks:
695738
* - Retrieves the internal language configuration for the specified language ID.
696-
* - Reads the default multi-line configuration from a JSON file.
739+
* - Uses the cached default multi-line configuration.
697740
* - Merges the default multi-line configuration with the internal language configuration if
698741
* multiLine is `true`.
699742
* - Sets the appropriate comment styles and onEnter rules.
@@ -705,14 +748,17 @@ export class Configuration {
705748
* with rogue characters being inserted on new lines.
706749
*/
707750
private setLanguageConfiguration(langId: LanguageId, multiLine?: boolean, singleLineStyle?: SingleLineCommentStyle): vscode.Disposable {
708-
const internalLangConfig: vscode.LanguageConfiguration = this.getLanguageConfig(langId);
709-
const defaultMultiLineConfig = utils.readJsonFile(`${__dirname}/../../config/default-multi-line-config.json`) as vscode.LanguageConfiguration;
751+
const internalLangConfig: vscode.LanguageConfiguration | undefined = this.getLanguageConfig(langId);
710752

711-
let langConfig = {...internalLangConfig};
753+
// Deep-clone the internalLangConfig so modifications never write back
754+
// into the cached `languageConfigs` Map by accident.
755+
let langConfig: vscode.LanguageConfiguration = internalLangConfig
756+
? structuredClone(internalLangConfig)
757+
: {};
712758

713759
if (multiLine) {
714760
langConfig.autoClosingPairs = utils.mergeArraysBy<vscode.AutoClosingPair>(
715-
defaultMultiLineConfig.autoClosingPairs,
761+
this.defaultMultiLineConfig.autoClosingPairs,
716762
internalLangConfig?.autoClosingPairs,
717763
"open"
718764
);
@@ -725,13 +771,17 @@ export class Configuration {
725771
);
726772

727773
// Only assign the default config comments if it doesn't already exist.
728-
// (nullish assignment operator ??=)
729-
langConfig.comments ??= defaultMultiLineConfig.comments;
774+
// Clone the comments to avoid modifying the original object down the line.
775+
langConfig.comments ??= structuredClone(this.defaultMultiLineConfig.comments);
730776

731777
// If the default multi-line comments has been overridden for the langId,
732-
// add the overridden multi-line comments to the langConfig.
733-
if (this.isLangIdMultiLineCommentOverridden(langId)) {
734-
langConfig.comments.blockComment[0] = this.getOverriddenMultiLineComment(langId);
778+
// AND the langConfig has a comments key with a blockComment key, then
779+
// update the opening comment style while preserving the ending.
780+
if (this.isLangIdMultiLineCommentOverridden(langId) && langConfig.comments?.blockComment) {
781+
langConfig.comments.blockComment = [
782+
this.getOverriddenMultiLineComment(langId),
783+
langConfig.comments.blockComment[1]
784+
];
735785
}
736786

737787
/**
@@ -1017,16 +1067,10 @@ export class Configuration {
10171067
logger.debug("The language configs found are:", this.languageConfigs);
10181068

10191069
// Multi-line language definitions.
1020-
logger.debug(
1021-
"The supported languages for multi-line blocks:",
1022-
utils.readJsonFile<MultiLineLanguageDefinitions>(this.multiLineLangDefinitionFilePath)
1023-
);
1070+
logger.debug("The supported languages for multi-line blocks:", this.getMultiLineLanguageDefinitions());
10241071

10251072
// Single-line language definitions.
1026-
logger.debug(
1027-
"The supported languages for single-line blocks:",
1028-
utils.readJsonFile<SingleLineLanguageDefinitions>(this.singleLineLangDefinitionFilePath)
1029-
);
1073+
logger.debug("The supported languages for single-line blocks:", this.getSingleLineLanguageDefinitions());
10301074
}
10311075

10321076
/**

src/extension.ts

Lines changed: 31 additions & 26 deletions
Original file line numberDiff line numberDiff line change
@@ -32,6 +32,11 @@ export function activate(context: vscode.ExtensionContext) {
3232
const extensionName = extensionData.get("namespace");
3333
const extensionDisplayName = extensionData.get("displayName");
3434

35+
// In development mode, write language definitions to JSON files for debugging/reference.
36+
if (context.extensionMode !== vscode.ExtensionMode.Production) {
37+
configuration.writeCommentLanguageDefinitionsToJsonFile();
38+
}
39+
3540
// Store disposables for cleanup
3641
const disposables: vscode.Disposable[] = [];
3742
let commentBlocksDisposables: vscode.Disposable[] = [];
@@ -75,21 +80,39 @@ export function activate(context: vscode.ExtensionContext) {
7580
logger.setLogLevel(logLevel);
7681
}
7782

78-
// Settings that require an extension host reload when changed.
79-
const reloadRequiredSettings = [
80-
"disabledLanguages",
81-
"overrideDefaultLanguageMultiLineComments",
83+
/**
84+
* Automatically update (without extension host reload) language definitions and
85+
* reconfigure the comment blocks when any of the following settings are changed.
86+
*/
87+
const languageSettings = [
8288
"multiLineStyleBlocks",
8389
"slashStyleBlocks",
8490
"hashStyleBlocks",
8591
"semicolonStyleBlocks",
92+
"disabledLanguages",
93+
"overrideDefaultLanguageMultiLineComments",
8694
];
8795

88-
// Settings that require extension host reload
89-
for (const setting of reloadRequiredSettings) {
96+
for (const setting of languageSettings) {
9097
if (event.affectsConfiguration(`${extensionName}.${setting}`)) {
91-
showReloadMessage(extensionName, setting);
92-
break; // Only show one reload message at a time
98+
logger.info(`Configuration setting ${extensionName}.${setting} has changed.`);
99+
// Dispose of old comment block configurations to prevent memory leaks
100+
commentBlocksDisposables.forEach((disposable) => disposable.dispose());
101+
commentBlocksDisposables = [];
102+
103+
configuration.updateLanguageDefinitions();
104+
105+
// In development mode, write updated language definitions to JSON files.
106+
if (context.extensionMode !== vscode.ExtensionMode.Production) {
107+
configuration.writeCommentLanguageDefinitionsToJsonFile();
108+
}
109+
110+
commentBlocksDisposables = configuration.configureCommentBlocks();
111+
disposables.push(...commentBlocksDisposables);
112+
113+
logger.info("Comment block configurations have been updated.");
114+
115+
break; // Only update once per change
93116
}
94117
}
95118
});
@@ -132,21 +155,3 @@ export function activate(context: vscode.ExtensionContext) {
132155
export function deactivate() {
133156
logger.disposeLogger();
134157
}
135-
136-
/**
137-
* Shows a message prompting the user to reload the extension host.
138-
* @param extensionName The namespace of the extension
139-
* @param settingName The name of the setting that was changed
140-
*/
141-
function showReloadMessage(extensionName: string, settingName: string): void {
142-
vscode.window
143-
.showInformationMessage(
144-
`The ${extensionName}.${settingName} setting has been changed. Please reload the Extension Host to take effect.`,
145-
"Reload"
146-
)
147-
.then((selection) => {
148-
if (selection === "Reload") {
149-
vscode.commands.executeCommand("workbench.action.restartExtensionHost");
150-
}
151-
});
152-
}

tsconfig.json

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -8,5 +8,8 @@
88
"rootDir": ".",
99
"typeRoots": ["./node_modules/@types"]
1010
},
11+
"typeAcquisition": {
12+
"enable": true,
13+
},
1114
"exclude": ["node_modules", ".vscode-test"]
1215
}

0 commit comments

Comments
 (0)