diff --git a/Extension/src/LanguageServer/client.ts b/Extension/src/LanguageServer/client.ts index 5481bdd8b..b370188f7 100644 --- a/Extension/src/LanguageServer/client.ts +++ b/Extension/src/LanguageServer/client.ts @@ -53,7 +53,7 @@ import * as configs from './configurations'; import { CopilotCompletionContextFeatures, CopilotCompletionContextProvider } from './copilotCompletionContextProvider'; import { CustomConfigurationProvider1, getCustomConfigProviders, isSameProviderExtensionId } from './customProviders'; import { DataBinding } from './dataBinding'; -import { cachedEditorConfigSettings, getEditorConfigSettings } from './editorConfig'; +import { cachedEditorConfigSettings, EditorConfigWatcher, getEditorConfigSettings } from './editorConfig'; import { CppSourceStr, clients, configPrefix, initializeIntervalTimer, isWritingCrashCallStack, updateLanguageConfigurations, usesCrashHandler, watchForCrashes } from './extension'; import { IncludeCleanupPreferences, getIncludeCleanupPreferences } from './includeCleanupEditorConfig'; import { InactiveRegion, InactiveRegionStore, getInactiveRegionStartLines } from './inactiveRegions'; @@ -882,6 +882,7 @@ export class DefaultClient implements Client { private semanticTokensProviderDisposable: vscode.Disposable | undefined; private innerConfiguration?: configs.CppProperties; private rootPathFileWatcher?: vscode.FileSystemWatcher; + private editorConfigWatcher?: EditorConfigWatcher; private rootFolder?: vscode.WorkspaceFolder; private rootRealPath: string; private workspaceStoragePath: string; @@ -1947,6 +1948,11 @@ export class DefaultClient implements Client { } private prepareVisibleEditorInfo(editors: readonly vscode.TextEditor[]): { [uri: string]: VisibleEditorInfo } { + this.editorConfigWatcher ??= new EditorConfigWatcher(() => this.refreshEditorConfigSettings()); + if (this.editorConfigWatcher.update(editors.filter(editor => editor.document.uri.scheme === 'file') + .map(editor => editor.document.uri.fsPath))) { + cachedEditorConfigLookups.clear(); + } const visibileEditorInfo: { [uri: string]: VisibleEditorInfo } = {}; editors.forEach(editor => { // Use a map, to account for multiple editors for the same file. @@ -1975,6 +1981,10 @@ export class DefaultClient implements Client { // Handles changes to visible files/ranges, changes to current selection/position, // and changes to the active text editor. Should only be called on the primary client. public async onDidChangeVisibleTextEditors(editors: readonly vscode.TextEditor[]): Promise { + const defaultClient: Client = clients.getDefaultClient(); + if (this !== defaultClient) { + return defaultClient.onDidChangeVisibleTextEditors(editors); + } const params: DidChangeVisibleTextEditorsParams = { visibleEditorInfo: this.prepareVisibleEditorInfo(editors) }; @@ -2719,10 +2729,11 @@ export class DefaultClient implements Client { private refreshEditorConfigSettings(): void { cachedEditorConfigSettings.clear(); cachedEditorConfigLookups.clear(); - this.updateActiveDocumentTextOptions(); + const defaultClient: Client = clients.getDefaultClient(); + defaultClient.updateActiveDocumentTextOptions(); const cppEditors: vscode.TextEditor[] = vscode.window.visibleTextEditors.filter(editor => util.isCpp(editor.document)); - void this.onDidChangeVisibleTextEditors(cppEditors).catch(logAndReturn.undefined); + void defaultClient.onDidChangeVisibleTextEditors(cppEditors).catch(logAndReturn.undefined); } /** @@ -3215,7 +3226,7 @@ export class DefaultClient implements Client { void SessionState.buildAndDebugIsSourceFile.set(util.isCppOrCFile(editor.document.uri, editor.document.languageId)); void SessionState.buildAndDebugIsFolderOpen.set(util.isFolderOpen(editor.document.uri)); // If using vcFormat, check for a ".editorconfig" file, and apply those text options to the active document. - const settings: CppSettings = new CppSettings(this.RootUri); + const settings: CppSettings = new CppSettings(editor.document.uri); if (settings.useVcFormat(editor.document)) { const editorConfigSettings: any = getEditorConfigSettings(editor.document.uri.fsPath); if (editorConfigSettings.indent_style === "tab") { @@ -4358,6 +4369,7 @@ export class DefaultClient implements Client { } public dispose(): void { + this.editorConfigWatcher?.dispose(); this.inactiveRegionsDecorations.forEach(currentSet => currentSet.decoration.dispose()); this.inactiveRegionsDecorations.clear(); this.pendingTagParsingCalls.forEach(pendingCall => { diff --git a/Extension/src/LanguageServer/clientCollection.ts b/Extension/src/LanguageServer/clientCollection.ts index 390afc2ff..57b7d7955 100644 --- a/Extension/src/LanguageServer/clientCollection.ts +++ b/Extension/src/LanguageServer/clientCollection.ts @@ -7,6 +7,7 @@ import * as vscode from 'vscode'; import * as util from '../common'; import * as telemetry from '../telemetry'; +import { logAndReturn } from '../Utility/Async/returns'; import * as cpptools from './client'; import { getCustomConfigProviders } from './customProviders'; import { TimeTelemetryCollector } from './timeTelemetryCollector'; @@ -63,7 +64,8 @@ export class ClientCollection { this.defaultClient = this.activeClient; this.languageClients.set(key, this.activeClient); - this.disposables.push(vscode.workspace.onDidChangeWorkspaceFolders(e => this.onDidChangeWorkspaceFolders(e))); + this.disposables.push(vscode.workspace.onDidChangeWorkspaceFolders(e => + this.onDidChangeWorkspaceFolders(e).catch(logAndReturn.undefined))); } public async didChangeActiveEditor(editor?: vscode.TextEditor): Promise { @@ -144,6 +146,9 @@ export class ClientCollection { this.activeClient.activate(); await this.activeClient.didChangeActiveEditor(vscode.window.activeTextEditor); } + + await this.defaultClient.onDidChangeVisibleTextEditors( + vscode.window.visibleTextEditors.filter(editor => util.isCpp(editor.document))); } private async onDidChangeWorkspaceFolders(e?: vscode.WorkspaceFoldersChangeEvent): Promise { @@ -205,6 +210,9 @@ export class ClientCollection { this.activeClient.activate(); } } + + await this.defaultClient.onDidChangeVisibleTextEditors( + vscode.window.visibleTextEditors.filter(editor => util.isCpp(editor.document))); } } diff --git a/Extension/src/LanguageServer/editorConfig.ts b/Extension/src/LanguageServer/editorConfig.ts index 4cccd367f..ff6275f5e 100644 --- a/Extension/src/LanguageServer/editorConfig.ts +++ b/Extension/src/LanguageServer/editorConfig.ts @@ -7,10 +7,23 @@ import * as fs from 'fs'; import { Minimatch } from 'minimatch'; import * as path from 'path'; +import * as vscode from 'vscode'; import * as util from '../common'; import { isWindows } from '../constants'; -export const cachedEditorConfigSettings: Map = new Map(); +type EditorConfigSettings = Record; + +interface EditorConfigSection { + pattern: string; + settings: EditorConfigSettings; +} + +interface ParsedEditorConfig { + global: EditorConfigSettings; + sections: EditorConfigSection[]; +} + +export const cachedEditorConfigSettings: Map = new Map(); export function mapIndentationReferenceToEditorConfig(value: string | undefined): string { if (value !== undefined) { @@ -85,10 +98,10 @@ export function matchesSection(pathPrefix: string, filePath: string, section: st return matcher.match(filePath); } -function parseEditorConfigContent(content: string): Record { +function parseEditorConfigContent(content: string): ParsedEditorConfig { const lines = content.split(/\r?\n/); - const config: Record = {}; - let currentSection: string | null = '*'; // Use '*' for sectionless (global) settings. + const config: ParsedEditorConfig = { global: {}, sections: [] }; + let currentSettings: EditorConfigSettings = config.global; lines.forEach(line => { line = line.trim(); @@ -99,32 +112,25 @@ function parseEditorConfigContent(content: string): Record { } if (line.startsWith('[') && line.endsWith(']')) { - // New section (e.g., [*.js]) - currentSection = line.slice(1, -1).trim(); - config[currentSection] = config[currentSection] || {}; + currentSettings = {}; + config.sections.push({ pattern: line.slice(1, -1).trim(), settings: currentSettings }); } else { // Key-value pair (e.g., indent_style = space). const [key, ...values] = line.split('='); if (key && values.length > 0) { - const trimmedKey = key.trim(); - let value: any = values.join('=').trim(); + const trimmedKey = key.trim().toLowerCase(); + let value: string | number | boolean = values.join('=').trim(); // Convert boolean-like and numeric values. - if (value === 'true') { + if (value.toLowerCase() === 'true') { value = true; - } else if (value === 'false') { + } else if (value.toLowerCase() === 'false') { value = false; } else if (!isNaN(Number(value))) { value = Number(value); } - if (currentSection) { - // Ensure the current section is initialized. - if (!config[currentSection]) { - config[currentSection] = {}; - } - config[currentSection][trimmedKey] = value; - } + currentSettings[trimmedKey] = value; } } }); @@ -132,9 +138,8 @@ function parseEditorConfigContent(content: string): Record { return config; } -function getEditorConfig(filePath: string): any { - let combinedConfig: any = {}; - let globalConfig: any = {}; +function getEditorConfig(filePath: string): EditorConfigSettings { + let combinedConfig: EditorConfigSettings = {}; let currentDir: string = path.dirname(filePath); const rootDir: string = path.parse(currentDir).root; @@ -147,33 +152,24 @@ function getEditorConfig(filePath: string): any { const editorConfigPath: string = path.join(currentDir, '.editorconfig'); if (util.checkFileExistsSync(editorConfigPath)) { const configFileContent: string = fs.readFileSync(editorConfigPath, 'utf-8'); - const configData = parseEditorConfigContent(configFileContent); - - // Extract global (sectionless) entries. - if (configData['*']) { - globalConfig = { - ...globalConfig, - ...configData['*'] - }; - } + const configData: ParsedEditorConfig = parseEditorConfigContent(configFileContent); + const currentConfig: EditorConfigSettings = { ...configData.global }; let currentDirForwardSlashes: string = currentDir; if (isWindows) { currentDirForwardSlashes = currentDir.replace(/\\/g, '/'); } - // Match sections and combine configurations. - Object.keys(configData).forEach((section: string) => { - if (section !== '*' && matchesSection(currentDirForwardSlashes, filePath, section)) { - combinedConfig = { - ...configData[section], - ...combinedConfig - }; + for (const section of configData.sections) { + if (matchesSection(currentDirForwardSlashes, filePath, section.pattern)) { + Object.assign(currentConfig, section.settings); } - }); + } + combinedConfig = { ...currentConfig, ...combinedConfig }; // Check if the current .editorconfig is the root. - if (configData['*']?.root) { + if (configData.global.root === true) { + combinedConfig.root = true; break; // Stop searching after processing the root = true file. } } @@ -183,20 +179,78 @@ function getEditorConfig(filePath: string): any { currentDir = path.dirname(currentDir); } - // Merge global config with section-based config. - return { - ...globalConfig, - ...combinedConfig - }; + for (const [key, value] of Object.entries(combinedConfig)) { + if (typeof value === 'string' && value.toLowerCase() === 'unset') { + delete combinedConfig[key]; + } + } + return combinedConfig; } // Look up the appropriate .editorconfig settings for the specified file. // This is intentionally not async to avoid races due to multiple entrancy. -export function getEditorConfigSettings(fsPath: string): Promise { - let editorConfigSettings: any = cachedEditorConfigSettings.get(fsPath); +export function getEditorConfigSettings(fsPath: string): EditorConfigSettings { + let editorConfigSettings: EditorConfigSettings | undefined = cachedEditorConfigSettings.get(fsPath); if (!editorConfigSettings) { editorConfigSettings = getEditorConfig(fsPath); cachedEditorConfigSettings.set(fsPath, editorConfigSettings); } return editorConfigSettings; } + +export class EditorConfigWatcher implements vscode.Disposable { + private readonly watchers: Map = new Map(); + + constructor(private readonly onChanged: () => void) { } + + public update(filePaths: readonly string[]): boolean { + const directories: Set = new Set(); + for (const filePath of filePaths) { + let directory: string = path.dirname(filePath); + for (;;) { + if (!vscode.workspace.getWorkspaceFolder(vscode.Uri.file(directory))) { + directories.add(directory); + } + const parent: string = path.dirname(directory); + if (parent === directory) { + break; + } + directory = parent; + } + } + + for (const [directory, watcher] of this.watchers) { + if (!directories.has(directory)) { + watcher.dispose(); + this.watchers.delete(directory); + } + } + + let addedWatchers: boolean = false; + for (const directory of directories) { + if (this.watchers.has(directory)) { + continue; + } + const watcher: vscode.FileSystemWatcher = vscode.workspace.createFileSystemWatcher( + new vscode.RelativePattern(vscode.Uri.file(directory), '.editorconfig')); + const onChanged = () => { + cachedEditorConfigSettings.clear(); + this.onChanged(); + }; + watcher.onDidCreate(onChanged); + watcher.onDidChange(onChanged); + watcher.onDidDelete(onChanged); + this.watchers.set(directory, watcher); + addedWatchers = true; + } + if (addedWatchers) { + cachedEditorConfigSettings.clear(); + } + return addedWatchers; + } + + public dispose(): void { + this.watchers.forEach(watcher => watcher.dispose()); + this.watchers.clear(); + } +} diff --git a/Extension/src/LanguageServer/includeCleanupEditorConfig.ts b/Extension/src/LanguageServer/includeCleanupEditorConfig.ts index 60c7fb17c..1742d48af 100644 --- a/Extension/src/LanguageServer/includeCleanupEditorConfig.ts +++ b/Extension/src/LanguageServer/includeCleanupEditorConfig.ts @@ -8,6 +8,7 @@ export interface IncludeCleanupPreferences { excludedFiles: string; replacementFiles: string; requiredFiles: string; + removeUnusedErrorTagType: string; } function normalizeSettingKeys(settings: any): Record { @@ -28,6 +29,7 @@ export function getIncludeCleanupPreferences(settings: any): IncludeCleanupPrefe alternateFiles: getStringSetting(normalizedSettings, 'cpp_include_cleanup_alternate_files'), excludedFiles: getStringSetting(normalizedSettings, 'cpp_include_cleanup_excluded_files'), replacementFiles: getStringSetting(normalizedSettings, 'cpp_include_cleanup_replacement_files'), - requiredFiles: getStringSetting(normalizedSettings, 'cpp_include_cleanup_required_files') + requiredFiles: getStringSetting(normalizedSettings, 'cpp_include_cleanup_required_files'), + removeUnusedErrorTagType: getStringSetting(normalizedSettings, 'cpp_include_cleanup_remove_unused_error_tag_type').toLowerCase() || 'none' }; } diff --git a/Extension/src/LanguageServer/protocolFilter.ts b/Extension/src/LanguageServer/protocolFilter.ts index d97481297..f5bc72bc3 100644 --- a/Extension/src/LanguageServer/protocolFilter.ts +++ b/Extension/src/LanguageServer/protocolFilter.ts @@ -92,7 +92,7 @@ export function createProtocolFilter(): Middleware { client.takeOwnership(document); void sendMessage(document); const cppEditors: vscode.TextEditor[] = vscode.window.visibleTextEditors.filter(e => util.isCpp(e.document)); - void client.onDidChangeVisibleTextEditors(cppEditors).catch(logAndReturn.undefined); + void clients.getDefaultClient().onDidChangeVisibleTextEditors(cppEditors).catch(logAndReturn.undefined); } } }, diff --git a/Extension/src/nativeStrings.json b/Extension/src/nativeStrings.json index df651a089..5312102ef 100644 --- a/Extension/src/nativeStrings.json +++ b/Extension/src/nativeStrings.json @@ -817,5 +817,13 @@ "error_config_arg_requires_path": { "text": "{0} requires a path.", "hint": "Error shown when a configuration argument is not followed by a path. {0} is the command-line option name. {Locked=\"{0}\"}" + }, + "include_is_not_used": { + "text": "Include is not used", + "hint": "Diagnostic on a C or C++ include directive whose header is unused." + }, + "include_is_duplicated": { + "text": "Include is duplicated", + "hint": "Diagnostic on a C or C++ include directive that repeats an earlier include of the same header." } } diff --git a/Extension/test/scenarios/MultirootDeadlockTest/tests/editorConfig.test.ts b/Extension/test/scenarios/MultirootDeadlockTest/tests/editorConfig.test.ts new file mode 100644 index 000000000..93dc39723 --- /dev/null +++ b/Extension/test/scenarios/MultirootDeadlockTest/tests/editorConfig.test.ts @@ -0,0 +1,194 @@ +/* -------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All Rights Reserved. + * See 'LICENSE' in the project root for license information. + * ------------------------------------------------------------------------------------------ */ + +import * as assert from 'assert'; +import { mkdtemp, readFile, rm, writeFile } from 'fs/promises'; +import { suite } from 'mocha'; +import * as path from 'path'; +import * as sinon from 'sinon'; +import * as vscode from 'vscode'; +import { EditorConfigWatcher } from '../../../../src/LanguageServer/editorConfig'; +import * as extension from '../../../../src/LanguageServer/extension'; +import { createProtocolFilter } from '../../../../src/LanguageServer/protocolFilter'; +import { timeout } from '../../../../src/Utility/Async/timeout'; +import * as testHelpers from '../../../common/testHelpers'; + +suite("EditorConfig in a multi-root workspace", () => { + let firstFolder: vscode.WorkspaceFolder; + let secondFolder: vscode.WorkspaceFolder; + const directories: string[] = []; + const documents: vscode.TextDocument[] = []; + + suiteSetup(async () => { + await testHelpers.activateCppExtension(); + firstFolder = vscode.workspace.workspaceFolders?.[0] ?? assert.fail("First workspace folder is unavailable"); + secondFolder = vscode.workspace.workspaceFolders?.[1] ?? assert.fail("Second workspace folder is unavailable"); + }); + + teardown(async () => { + await closeDocuments(); + await extension.clients.getDefaultClient().onDidChangeVisibleTextEditors([]); + for (const directory of directories.splice(0)) { + await rm(directory, { recursive: true, force: true, maxRetries: 5 }); + } + }); + + async function closeDocuments(): Promise { + for (const document of documents.splice(0)) { + if (!document.isClosed) { + await vscode.window.showTextDocument(document, { preview: false }); + await vscode.commands.executeCommand("workbench.action.revertAndCloseActiveEditor"); + } + } + } + + async function createDocument(folder: vscode.WorkspaceFolder, endOfLine?: 'crlf'): Promise { + const directory = await mkdtemp(path.join(folder.uri.fsPath, 'editorconfig-review-')); + directories.push(directory); + await writeFile(path.join(directory, '.editorconfig'), + 'root = true\n[*.cpp]\nindent_style = tab\nindent_size = 3\n' + + (endOfLine ? `end_of_line = ${endOfLine}\n` : '')); + const source = path.join(directory, 'sample.cpp'); + await writeFile(source, 'int value;\n'); + const document = await vscode.workspace.openTextDocument(source); + documents.push(document); + return document; + } + + test("uses the active document's formatting mode even when called on another client", async () => { + const firstConfiguration = vscode.workspace.getConfiguration("C_Cpp", firstFolder.uri); + const secondConfiguration = vscode.workspace.getConfiguration("C_Cpp", secondFolder.uri); + const firstOriginal = firstConfiguration.inspect("formatting")?.workspaceFolderValue; + const secondOriginal = secondConfiguration.inspect("formatting")?.workspaceFolderValue; + const settingsFiles = [firstFolder, secondFolder].map(folder => path.join(folder.uri.fsPath, '.vscode/settings.json')); + const settingsContents = await Promise.all(settingsFiles.map(async file => { + try { + return await readFile(file); + } catch (error) { + if (error instanceof Error && 'code' in error && error.code === 'ENOENT') { + return undefined; + } + throw error; + } + })); + try { + await firstConfiguration.update("formatting", "clangFormat", vscode.ConfigurationTarget.WorkspaceFolder); + await secondConfiguration.update("formatting", "vcFormat", vscode.ConfigurationTarget.WorkspaceFolder); + const firstDocument = await createDocument(firstFolder, 'crlf'); + const secondDocument = await createDocument(secondFolder); + const firstOwner = extension.clients.getClientFor(firstDocument.uri); + const secondOwner = extension.clients.getClientFor(secondDocument.uri); + assert.notStrictEqual(firstOwner, secondOwner); + const editor = await vscode.window.showTextDocument(firstDocument, { preview: false }); + editor.options = { insertSpaces: true, tabSize: 4, indentSize: 4 }; + secondOwner.updateActiveDocumentTextOptions(); + assert.strictEqual(editor.options.insertSpaces, true); + assert.strictEqual(editor.options.tabSize, 4); + assert.strictEqual(firstDocument.eol, vscode.EndOfLine.LF); + + const secondEditor = await vscode.window.showTextDocument(secondDocument, { preview: false }); + secondEditor.options = { insertSpaces: true, tabSize: 4, indentSize: 4 }; + firstOwner.updateActiveDocumentTextOptions(); + assert.strictEqual(secondEditor.options.insertSpaces, false); + assert.strictEqual(secondEditor.options.tabSize, 3); + } finally { + await closeDocuments(); + await firstConfiguration.update("formatting", firstOriginal, vscode.ConfigurationTarget.WorkspaceFolder); + await secondConfiguration.update("formatting", secondOriginal, vscode.ConfigurationTarget.WorkspaceFolder); + for (let index = 0; index < settingsFiles.length; ++index) { + const content = settingsContents[index]; + if (content === undefined) { + await rm(settingsFiles[index], { force: true }); + } else { + await writeFile(settingsFiles[index], content); + } + } + } + }); + + test("uses one watcher owner for secondary didOpen and later visibility changes", async () => { + await extension.clients.getDefaultClient().onDidChangeVisibleTextEditors([]); + const document = await createDocument(secondFolder); + const editor = await vscode.window.showTextDocument(document, { preview: false }); + const owner = extension.clients.getClientFor(document.uri); + const defaultClient = extension.clients.getDefaultClient(); + assert.notStrictEqual(owner, defaultClient); + await defaultClient.onDidChangeVisibleTextEditors([]); + const sandbox = sinon.createSandbox(); + const updates = sandbox.spy(EditorConfigWatcher.prototype, "update"); + const creations = sandbox.spy(vscode.workspace, "createFileSystemWatcher"); + const trackedDocument = owner.TrackedDocuments.get(document.uri.toString()); + try { + sandbox.stub(owner, "takeOwnership"); + owner.TrackedDocuments.delete(document.uri.toString()); + const filter = createProtocolFilter(); + assert.ok(filter.didOpen); + await filter.didOpen(document, async () => { }); + await defaultClient.onDidChangeVisibleTextEditors([editor]); + assert.ok(updates.called); + assert.strictEqual(new Set(updates.thisValues).size, 1); + const disposals = creations.getCalls() + .filter(call => call.args[0] instanceof vscode.RelativePattern && call.args[0].pattern === '.editorconfig') + .map(call => sandbox.spy(call.returnValue, "dispose")); + assert.ok(disposals.length > 0); + await defaultClient.onDidChangeVisibleTextEditors([]); + for (const disposal of disposals) { + sinon.assert.calledOnce(disposal); + } + } finally { + if (trackedDocument) { + owner.TrackedDocuments.set(document.uri.toString(), trackedDocument); + } + sandbox.restore(); + } + }); + + test("restores ancestor watches when a visible document's workspace folder is removed", async () => { + const document = await createDocument(secondFolder); + const editor = await vscode.window.showTextDocument(document, { preview: false }); + await extension.clients.getDefaultClient().onDidChangeVisibleTextEditors([editor]); + const workspaceFile = vscode.workspace.workspaceFile ?? assert.fail("Workspace file is unavailable"); + const workspaceContents = await readFile(workspaceFile.fsPath); + const sandbox = sinon.createSandbox(); + const creations = sandbox.spy(vscode.workspace, "createFileSystemWatcher"); + + async function changeFolder(remove: boolean): Promise { + let subscription: vscode.Disposable | undefined; + const changed = new Promise(resolve => { + subscription = vscode.workspace.onDidChangeWorkspaceFolders(event => { + if ((remove ? event.removed : event.added).some(folder => folder.uri.toString() === secondFolder.uri.toString())) { + resolve(); + } + }); + }); + try { + assert.ok(vscode.workspace.updateWorkspaceFolders(secondFolder.index, remove ? 1 : 0, + ...remove ? [] : [{ uri: secondFolder.uri }]), "Workspace folder update should be accepted"); + await timeout(10000, changed); + } finally { + subscription?.dispose(); + } + } + + try { + await changeFolder(true); + assert.ok(vscode.window.visibleTextEditors.some(visible => visible.document === document), + "The document should remain visible after its workspace folder is removed"); + assert.ok(creations.getCalls().some(call => { + const pattern = call.args[0]; + return pattern instanceof vscode.RelativePattern && pattern.pattern === '.editorconfig' + && pattern.baseUri.fsPath === path.dirname(document.uri.fsPath); + }), "The visible document's newly external EditorConfig should be watched"); + } finally { + await closeDocuments(); + sandbox.restore(); + if (!vscode.workspace.getWorkspaceFolder(document.uri)) { + await changeFolder(false); + } + await writeFile(workspaceFile.fsPath, workspaceContents); + } + }); + +}); diff --git a/Extension/test/unit/clientCollection.test.ts b/Extension/test/unit/clientCollection.test.ts new file mode 100644 index 000000000..99b409427 --- /dev/null +++ b/Extension/test/unit/clientCollection.test.ts @@ -0,0 +1,60 @@ +/* -------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All Rights Reserved. + * See 'LICENSE' in the project root for license information. + * ------------------------------------------------------------------------------------------ */ + +import { it } from 'mocha'; +import { strictEqual } from 'node:assert'; +import * as sinon from 'sinon'; +import proxyquire = require('proxyquire'); + +it('replays visible C++ editors to the replacement default client after recreation', async () => { + class StubClient { + public readonly RootFolder = undefined; + public readonly TrackedDocuments = new Map(); + public readonly deactivate = sinon.spy(); + public readonly dispose = sinon.spy(); + public readonly onDidChangeVisibleTextEditors = sinon.stub().resolves(); + } + + const cppEditor = { document: { languageId: 'cpp' } }; + const textEditor = { document: { languageId: 'plaintext' } }; + const visibleEditors = [cppEditor, textEditor]; + const createdClients: StubClient[] = []; + const subscription = { dispose: sinon.spy() }; + const { ClientCollection }: typeof import('../../src/LanguageServer/clientCollection') = proxyquire.noCallThru()( + '../../src/LanguageServer/clientCollection', { + vscode: { + window: { visibleTextEditors: visibleEditors }, + workspace: { onDidChangeWorkspaceFolders: () => subscription } + }, + '../common': { isCpp: (document: { languageId: string }) => document.languageId === 'cpp' }, + '../telemetry': {}, + '../Utility/Async/returns': { logAndReturn: { undefined: (error: unknown) => { throw error; } } }, + './client': { + createClient: () => { + const client = new StubClient(); + createdClients.push(client); + return client; + }, + DefaultClient: { stopLanguageClient: () => Promise.resolve() } + }, + './customProviders': { getCustomConfigProviders: () => [] }, + './timeTelemetryCollector': { TimeTelemetryCollector: class { } } + }); + const collection = new ClientCollection(); + try { + const oldClient = collection.getDefaultClient(); + await collection.recreateClients(); + strictEqual(createdClients.length, 2, 'The default client should be replaced once'); + strictEqual(collection.getDefaultClient(), createdClients[1], 'The replacement should become the default client'); + sinon.assert.calledOnce(createdClients[0].dispose); + sinon.assert.notCalled(createdClients[0].onDidChangeVisibleTextEditors); + sinon.assert.calledOnceWithExactly(createdClients[1].onDidChangeVisibleTextEditors, [cppEditor]); + strictEqual(visibleEditors.length, 2, 'Recreation should not change editor visibility'); + strictEqual(oldClient, createdClients[0], 'Only the isolated original client should be disposed'); + } finally { + await collection.dispose(); + } + sinon.assert.calledOnce(subscription.dispose); +}); diff --git a/Extension/test/unit/editorConfig.test.ts b/Extension/test/unit/editorConfig.test.ts new file mode 100644 index 000000000..5a859002f --- /dev/null +++ b/Extension/test/unit/editorConfig.test.ts @@ -0,0 +1,249 @@ +/* -------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All Rights Reserved. + * See 'LICENSE' in the project root for license information. + * ------------------------------------------------------------------------------------------ */ + +import { afterEach, beforeEach, describe, it } from 'mocha'; +import { deepStrictEqual, ok, strictEqual } from 'node:assert'; +import { existsSync, mkdirSync, mkdtempSync, rmSync, unlinkSync, writeFileSync } from 'node:fs'; +import { tmpdir } from 'node:os'; +import { join, sep } from 'node:path'; +import proxyquire = require('proxyquire'); +import { getIncludeCleanupPreferences } from '../../src/LanguageServer/includeCleanupEditorConfig'; + +type WatcherEvent = 'create' | 'change' | 'delete'; + +class TestWatcher { + public disposed = false; + private readonly listeners: Record void)[]> = { create: [], change: [], delete: [] }; + + constructor(public readonly directory: string) { } + + public onDidCreate(listener: () => void): void { this.listeners.create.push(listener); } + public onDidChange(listener: () => void): void { this.listeners.change.push(listener); } + public onDidDelete(listener: () => void): void { this.listeners.delete.push(listener); } + public fire(event: WatcherEvent): void { this.listeners[event].forEach(listener => listener()); } + public dispose(): void { + this.disposed = true; + this.listeners.create = []; + this.listeners.change = []; + this.listeners.delete = []; + } +} + +let workspaceDirectory: string | undefined; +const watchers: TestWatcher[] = []; +const vscode = { + Uri: { file: (fsPath: string) => ({ fsPath }) }, + RelativePattern: class { + constructor(public readonly baseUri: { fsPath: string }, public readonly pattern: string) { } + }, + workspace: { + getWorkspaceFolder: (uri: { fsPath: string }) => + workspaceDirectory && (uri.fsPath === workspaceDirectory || uri.fsPath.startsWith(workspaceDirectory + sep)) + ? { uri: { fsPath: workspaceDirectory } } : undefined, + createFileSystemWatcher: (pattern: { baseUri: { fsPath: string }; pattern: string }) => { + strictEqual(pattern.pattern, '.editorconfig'); + const watcher = new TestWatcher(pattern.baseUri.fsPath); + watchers.push(watcher); + return watcher; + } + } +}; + +const editorConfig: typeof import('../../src/LanguageServer/editorConfig') = proxyquire.noCallThru()( + '../../src/LanguageServer/editorConfig', { + vscode, + '../common': { checkFileExistsSync: existsSync } + }); + +describe('EditorConfig resolution and refresh', () => { + let directory: string; + + beforeEach(() => { + directory = mkdtempSync(join(tmpdir(), 'cpptools-editorconfig-')); + workspaceDirectory = undefined; + watchers.length = 0; + editorConfig.cachedEditorConfigSettings.clear(); + writeConfig('', 'root = true\n'); + }); + + afterEach(() => { + watchers.forEach(watcher => watcher.dispose()); + editorConfig.cachedEditorConfigSettings.clear(); + rmSync(directory, { recursive: true, force: true }); + }); + + function writeConfig(relativeDirectory: string, content: string): void { + const configDirectory = join(directory, relativeDirectory); + mkdirSync(configDirectory, { recursive: true }); + writeFileSync(join(configDirectory, '.editorconfig'), content); + } + + function getLevel(relativeFile = 'nested/sample.cpp'): string { + const settings = editorConfig.getEditorConfigSettings(join(directory, relativeFile)); + return getIncludeCleanupPreferences(settings).removeUnusedErrorTagType; + } + + function fire(directory: string, event: WatcherEvent): void { + const watcher = watchers.find(watcher => watcher.directory === directory && !watcher.disposed); + ok(watcher, `No active EditorConfig watcher for ${directory}`); + watcher.fire(event); + } + + it('lets a closer wildcard section disable an inherited warning', () => { + writeConfig('', 'root = true\n[*]\ncpp_include_cleanup_remove_unused_error_tag_type = warning\n'); + writeConfig('nested', '[*]\ncpp_include_cleanup_remove_unused_error_tag_type = none\n'); + strictEqual(getLevel(), 'none'); + }); + + it('uses the last matching section instead of the first', () => { + writeConfig('', 'root = true\n[*.cpp]\ncpp_include_cleanup_remove_unused_error_tag_type = warning\n' + + '[sample.cpp]\ncpp_include_cleanup_remove_unused_error_tag_type = error\n'); + strictEqual(getLevel(), 'error'); + }); + + it('preserves the ordering of repeated wildcard sections', () => { + writeConfig('', 'root = true\n[*]\ncpp_include_cleanup_remove_unused_error_tag_type = warning\n' + + '[*.cpp]\ncpp_include_cleanup_remove_unused_error_tag_type = error\n' + + '[*]\ncpp_include_cleanup_remove_unused_error_tag_type = none\n'); + strictEqual(getLevel(), 'none'); + }); + + it('lets a later wildcard section override a specific section', () => { + writeConfig('', 'root = true\n[*.cpp]\ncpp_include_cleanup_remove_unused_error_tag_type = error\n' + + '[*]\ncpp_include_cleanup_remove_unused_error_tag_type = none\n'); + strictEqual(getLevel(), 'none'); + }); + + it('lets a closer section unset the inherited diagnostic level', () => { + writeConfig('', 'root = true\n[*]\ncpp_include_cleanup_remove_unused_error_tag_type = warning\n'); + writeConfig('nested', '[*.cpp]\ncpp_include_cleanup_remove_unused_error_tag_type = unset\n'); + strictEqual(getLevel(), 'none'); + }); + + it('removes winning unset values for formatting and Include Cleanup', () => { + writeConfig('', 'root = true\n[*.cpp]\nend_of_line = lf\nindent_size = 4\n' + + 'cpp_include_cleanup_remove_unused_error_tag_type = warning\n' + + '[sample.cpp]\nend_of_line = unset\nindent_size = UnSeT\ncpp_include_cleanup_remove_unused_error_tag_type = unset\n'); + const settings = editorConfig.getEditorConfigSettings(join(directory, 'sample.cpp')); + strictEqual(Object.hasOwn(settings, 'end_of_line'), false); + strictEqual(Object.hasOwn(settings, 'indent_size'), false); + strictEqual(Object.hasOwn(settings, 'cpp_include_cleanup_remove_unused_error_tag_type'), false); + strictEqual(getIncludeCleanupPreferences(settings).removeUnusedErrorTagType, 'none'); + }); + + it('does not restore ancestor values after a closer config unsets them', () => { + writeConfig('', 'root = true\n[*]\nend_of_line = crlf\nindent_style = tab\nindent_size = 8\n'); + writeConfig('nested', '[*.cpp]\nend_of_line = unset\nindent_size = unset\n'); + const settings = editorConfig.getEditorConfigSettings(join(directory, 'nested/sample.cpp')); + strictEqual(Object.hasOwn(settings, 'end_of_line'), false); + strictEqual(Object.hasOwn(settings, 'indent_size'), false); + strictEqual(settings.indent_style, 'tab'); + }); + + it('preserves a concrete value that overrides an earlier unset', () => { + writeConfig('', 'root = true\n[*]\nend_of_line = unset\nindent_size = unset\n' + + '[*.cpp]\nend_of_line = lf\nindent_size = 4\n'); + const settings = editorConfig.getEditorConfigSettings(join(directory, 'sample.cpp')); + strictEqual(settings.end_of_line, 'lf'); + strictEqual(settings.indent_size, 4); + }); + + it('preserves formatting inheritance and stops at root true', () => { + writeConfig('', 'root = true\n[*]\nindent_style = tab\nindent_size = 8\n'); + writeConfig('nested', '[*.cpp]\nindent_size = 4\n'); + const inherited = editorConfig.getEditorConfigSettings(join(directory, 'nested/sample.cpp')); + strictEqual(inherited.indent_style, 'tab'); + strictEqual(inherited.indent_size, 4); + writeConfig('nested', 'root = true\n[*.cpp]\nindent_size = 2\n'); + editorConfig.cachedEditorConfigSettings.clear(); + const rooted = editorConfig.getEditorConfigSettings(join(directory, 'nested/sample.cpp')); + strictEqual(rooted.indent_style, undefined); + strictEqual(rooted.indent_size, 2); + strictEqual(rooted.root, true); + }); + + it('matches property names case-insensitively without changing path values', async () => { + writeConfig('', 'ROOT = TRUE\n[*]\nCPP_INCLUDE_CLEANUP_REMOVE_UNUSED_ERROR_TAG_TYPE = warning\n' + + 'cpp_include_cleanup_excluded_files = MixedCase.h\n[*.cpp]\ncpp_include_cleanup_remove_unused_error_tag_type = none\n'); + const settings = editorConfig.getEditorConfigSettings(join(directory, 'sample.cpp')); + strictEqual(getIncludeCleanupPreferences(settings).removeUnusedErrorTagType, 'none'); + strictEqual(getIncludeCleanupPreferences(settings).excludedFiles, 'MixedCase.h'); + strictEqual(settings.root, true); + }); + + it('refreshes cached single-file preferences when an applicable config changes', () => { + writeConfig('', 'root = true\n[*]\ncpp_include_cleanup_remove_unused_error_tag_type = warning\n'); + const file = join(directory, 'sample.cpp'); + let refreshedLevel = ''; + const watcher = new editorConfig.EditorConfigWatcher(() => { + refreshedLevel = getIncludeCleanupPreferences(editorConfig.getEditorConfigSettings(file)).removeUnusedErrorTagType; + }); + watcher.update([file]); + strictEqual(getIncludeCleanupPreferences(editorConfig.getEditorConfigSettings(file)).removeUnusedErrorTagType, 'warning'); + writeConfig('', 'root = true\n[*]\ncpp_include_cleanup_remove_unused_error_tag_type = none\n'); + fire(directory, 'change'); + strictEqual(refreshedLevel, 'none'); + watcher.dispose(); + }); + + it('watches parent configs outside the workspace without duplicating workspace watches', () => { + workspaceDirectory = join(directory, 'workspace'); + mkdirSync(workspaceDirectory); + writeConfig('', 'root = true\n[*]\ncpp_include_cleanup_remove_unused_error_tag_type = warning\n'); + const file = join(workspaceDirectory, 'sample.cpp'); + let refreshed = 0; + const watcher = new editorConfig.EditorConfigWatcher(() => { ++refreshed; }); + watcher.update([file]); + strictEqual(getIncludeCleanupPreferences(editorConfig.getEditorConfigSettings(file)).removeUnusedErrorTagType, 'warning'); + strictEqual(watchers.some(watcher => watcher.directory === workspaceDirectory), false); + writeConfig('', 'root = true\n[*]\ncpp_include_cleanup_remove_unused_error_tag_type = none\n'); + fire(directory, 'change'); + strictEqual(refreshed, 1); + strictEqual(getIncludeCleanupPreferences(editorConfig.getEditorConfigSettings(file)).removeUnusedErrorTagType, 'none'); + watcher.dispose(); + }); + + it('invalidates preferences for newly created and deleted closer configs', () => { + writeConfig('', 'root = true\n[*]\ncpp_include_cleanup_remove_unused_error_tag_type = warning\n'); + mkdirSync(join(directory, 'nested')); + const file = join(directory, 'nested/sample.cpp'); + const watcher = new editorConfig.EditorConfigWatcher(() => { }); + watcher.update([file]); + strictEqual(getIncludeCleanupPreferences(editorConfig.getEditorConfigSettings(file)).removeUnusedErrorTagType, 'warning'); + writeConfig('nested', '[*]\ncpp_include_cleanup_remove_unused_error_tag_type = none\n'); + fire(join(directory, 'nested'), 'create'); + strictEqual(getIncludeCleanupPreferences(editorConfig.getEditorConfigSettings(file)).removeUnusedErrorTagType, 'none'); + unlinkSync(join(directory, 'nested/.editorconfig')); + fire(join(directory, 'nested'), 'delete'); + strictEqual(getIncludeCleanupPreferences(editorConfig.getEditorConfigSettings(file)).removeUnusedErrorTagType, 'warning'); + watcher.dispose(); + }); + + it('deduplicates ancestor watches and releases them when no documents are visible', () => { + const watcher = new editorConfig.EditorConfigWatcher(() => { }); + const files = [join(directory, 'first.cpp'), join(directory, 'second.cpp')]; + strictEqual(watcher.update(files), true); + const initialWatchers = [...watchers]; + strictEqual(watcher.update(files), false); + deepStrictEqual(watchers, initialWatchers); + watcher.update([]); + strictEqual(watchers.every(watcher => watcher.disposed), true); + watcher.dispose(); + }); + + it('re-reads preferences after the file was hidden while its config changed', () => { + writeConfig('', 'root = true\n[*]\ncpp_include_cleanup_remove_unused_error_tag_type = warning\n'); + const file = join(directory, 'sample.cpp'); + const watcher = new editorConfig.EditorConfigWatcher(() => { }); + watcher.update([file]); + strictEqual(getIncludeCleanupPreferences(editorConfig.getEditorConfigSettings(file)).removeUnusedErrorTagType, 'warning'); + watcher.update([]); + writeConfig('', 'root = true\n[*]\ncpp_include_cleanup_remove_unused_error_tag_type = none\n'); + watcher.update([file]); + strictEqual(getIncludeCleanupPreferences(editorConfig.getEditorConfigSettings(file)).removeUnusedErrorTagType, 'none'); + watcher.dispose(); + strictEqual(watchers.every(watcher => watcher.disposed), true); + }); +}); diff --git a/Extension/test/unit/includeCleanupEditorConfig.test.ts b/Extension/test/unit/includeCleanupEditorConfig.test.ts index cf9ccdf74..a1d5aef0e 100644 --- a/Extension/test/unit/includeCleanupEditorConfig.test.ts +++ b/Extension/test/unit/includeCleanupEditorConfig.test.ts @@ -18,7 +18,8 @@ describe('Include Cleanup editorconfig settings', () => { alternateFiles: 'umbrella.h:internal.h', excludedFiles: 'generated.h', replacementFiles: 'stdio.h:cstdio', - requiredFiles: 'atlwin.h:atlbase.h' + requiredFiles: 'atlwin.h:atlbase.h', + removeUnusedErrorTagType: 'none' }); }); @@ -27,12 +28,14 @@ describe('Include Cleanup editorconfig settings', () => { CPP_INCLUDE_CLEANUP_ALTERNATE_FILES: 'umbrella.h:internal.h', Cpp_Include_Cleanup_Excluded_Files: 'generated.h', cpp_INCLUDE_cleanup_REPLACEMENT_files: 'stdio.h:cstdio', - CPP_include_cleanup_required_FILES: 'atlwin.h:atlbase.h' + CPP_include_cleanup_required_FILES: 'atlwin.h:atlbase.h', + CPP_INCLUDE_CLEANUP_REMOVE_UNUSED_ERROR_TAG_TYPE: 'DiMmEd' }), { alternateFiles: 'umbrella.h:internal.h', excludedFiles: 'generated.h', replacementFiles: 'stdio.h:cstdio', - requiredFiles: 'atlwin.h:atlbase.h' + requiredFiles: 'atlwin.h:atlbase.h', + removeUnusedErrorTagType: 'dimmed' }); }); @@ -40,12 +43,38 @@ describe('Include Cleanup editorconfig settings', () => { deepStrictEqual(getIncludeCleanupPreferences({ cpp_include_cleanup_alternate_files: 'unset', cpp_include_cleanup_excluded_files: true, - cpp_include_cleanup_replacement_files: 42 + cpp_include_cleanup_replacement_files: 42, + cpp_include_cleanup_remove_unused_error_tag_type: 'UNSET' }), { alternateFiles: '', excludedFiles: '', replacementFiles: '', - requiredFiles: '' + requiredFiles: '', + removeUnusedErrorTagType: 'none' }); }); + + it('defaults unused-include suggestions to none without EditorConfig settings', () => { + deepStrictEqual(getIncludeCleanupPreferences(undefined), { + alternateFiles: '', + excludedFiles: '', + replacementFiles: '', + requiredFiles: '', + removeUnusedErrorTagType: 'none' + }); + }); + + for (const level of ['none', 'suggestion', 'warning', 'error', 'dimmed']) { + it(`transports the ${level} unused-include diagnostic level`, () => { + deepStrictEqual(getIncludeCleanupPreferences({ + cpp_include_cleanup_remove_unused_error_tag_type: level + }), { + alternateFiles: '', + excludedFiles: '', + replacementFiles: '', + requiredFiles: '', + removeUnusedErrorTagType: level + }); + }); + } });