Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -1917,6 +1917,12 @@
"category": "CSharp",
"enablement": "isWorkspaceTrusted"
},
{
"command": "csharp.syncNamespaces",
"title": "%command.csharp.syncNamespaces%",
"category": "CSharp",
"enablement": "isWorkspaceTrusted"
},
{
"command": "csharp.showDecompilationTerms",
"title": "%command.csharp.showDecompilationTerms%",
Expand Down
1 change: 1 addition & 0 deletions package.nls.json
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@
"command.csharp.listRemoteDockerProcess": "List processes on Docker connection",
"command.csharp.attachToProcess": "Attach to a .NET 5+ or .NET Core process",
"command.csharp.reportIssue": "Report an issue",
"command.csharp.syncNamespaces": "Sync namespaces",
"command.csharp.showDecompilationTerms": "Show the decompiler terms agreement",
"command.csharp.recordLanguageServerTrace": "Record a performance trace of the C# Language Server",
"command.extension.showRazorCSharpWindow": "Show Razor CSharp",
Expand Down
7 changes: 7 additions & 0 deletions src/lsptoolshost/commands.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ import {
} from './projectContext/projectContextCommands';
import TelemetryReporter from '@vscode/extension-telemetry';
import { TelemetryEventNames } from '../shared/telemetryEventNames';
import { syncNamespaces } from './refactoring/namespaceSync';

export function registerCommands(
context: vscode.ExtensionContext,
Expand Down Expand Up @@ -83,4 +84,10 @@ function registerExtensionCommands(
context.subscriptions.push(
vscode.commands.registerCommand('csharp.showOutputWindow', async () => outputChannel.show())
);
context.subscriptions.push(
vscode.commands.registerCommand('csharp.syncNamespaces', async () => {
reporter.sendTelemetryEvent(TelemetryEventNames.NamespaceSyncCommand);
await syncNamespaces(outputChannel);
})
);
}
118 changes: 118 additions & 0 deletions src/lsptoolshost/refactoring/csprojAnalyzer.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,118 @@
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/

import * as vscode from 'vscode';
import * as path from 'path';

/**
* Common directories to exclude when scanning for project files.
*/
const EXCLUDED_DIRECTORIES = [
'bin',
'obj',
'.git',
'.svn',
'.hg',
'node_modules',
'packages',
'.vs',
'.vscode',
'TestResults',
'artifacts',
'.idea',
'dist',
'out',
'build',
];

/**
* Recursively finds all .csproj files in the given directory.
* Excludes common build artifacts, version control directories, and dependencies.
*/
export async function getCsprojFiles(uri: vscode.Uri): Promise<vscode.Uri[]> {
const results: vscode.Uri[] = [];

try {
const entries = await vscode.workspace.fs.readDirectory(uri);

for (const [name, type] of entries) {
// Skip build artifacts, version control, dependencies, and common irrelevant directories
if (EXCLUDED_DIRECTORIES.includes(name) || name.startsWith('.')) {
continue;
}

const fullPath = vscode.Uri.joinPath(uri, name);

if (type === vscode.FileType.Directory) {
results.push(...(await getCsprojFiles(fullPath)));
} else if (name.endsWith('.csproj')) {
results.push(fullPath);
}
}
} catch (_err) {
// Ignore permission errors or invalid directories
}

return results;
}

/**
* Recursively finds all .cs files in the given directory.
* Excludes common build output directories and other irrelevant directories.
*/
export async function getCsFiles(uri: vscode.Uri): Promise<vscode.Uri[]> {
const results: vscode.Uri[] = [];

try {
const entries = await vscode.workspace.fs.readDirectory(uri);

for (const [name, type] of entries) {
// Skip build output directories, version control, dependencies, and common artifacts
if (EXCLUDED_DIRECTORIES.includes(name) || name.startsWith('.')) {
continue;
}

const fullPath = vscode.Uri.joinPath(uri, name);

if (type === vscode.FileType.Directory) {
results.push(...(await getCsFiles(fullPath)));
} else if (name.endsWith('.cs')) {
results.push(fullPath);
}
}
} catch (_err) {
// Ignore permission errors or invalid directories
}

return results;
}

/**
* Extracts the root namespace from a .csproj file.
* Falls back to the project file name if RootNamespace is not specified.
*/
export async function getRootNamespace(csprojUri: vscode.Uri): Promise<string> {
try {
const content = await vscode.workspace.fs.readFile(csprojUri);
const text = Buffer.from(content).toString('utf8');

const match = text.match(/<RootNamespace>(.*?)<\/RootNamespace>/);
if (match) {
const trimmed = match[1].trim();
// If RootNamespace is empty, fall back to project filename
if (trimmed.length === 0) {
return path.basename(csprojUri.fsPath, '.csproj');
}
return trimmed;
}

// Fall back to project file name without extension
const fileName = path.basename(csprojUri.fsPath, '.csproj');
return fileName;
} catch (_err) {
// If we can't read the file, use the filename as fallback
return path.basename(csprojUri.fsPath, '.csproj');
}
Comment on lines +92 to +117
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'm pretty sure we already have this data on the language server side of things, we really don't need to be doing a regex like this. Grabbing it from MSBuild directly would also mean folks who customize it in with some shared logic would get the right thing.

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

More generally, this entire feature is already implemented in the language server, or at least the code for it is. We shouldn't be reinventing that.

}
93 changes: 93 additions & 0 deletions src/lsptoolshost/refactoring/namespaceCalculator.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,93 @@
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/

import * as vscode from 'vscode';
import * as path from 'path';

/**
* Calculates the expected namespace for a C# file based on its location
* relative to the project root.
*/
export function calculateNamespace(rootNamespace: string, csprojUri: vscode.Uri, fileUri: vscode.Uri): string {
const csprojPath = csprojUri.path;
const filePath = fileUri.path;

const csprojDir = path.posix.dirname(csprojPath);
const fileDir = path.posix.dirname(filePath);
const relativePath = path.posix.relative(csprojDir, fileDir);

if (!relativePath || relativePath === '.') {
return rootNamespace;
}

const suffix = relativePath
.split('/')
.map((segment: string) => sanitizeFolderName(segment))
.filter((segment: string) => segment.length > 0)
.join('.');

return suffix ? `${rootNamespace}.${suffix}` : rootNamespace;
}

/**
* Sanitizes a folder name to be used as part of a namespace.
* Removes or replaces characters that are invalid in C# namespaces.
* - Replaces whitespace, hyphens, and dots with underscores
* - Prefixes segments starting with digits with underscore
* - Removes any remaining invalid characters
*/
function sanitizeFolderName(name: string): string {
// Normalize whitespace, hyphens, and dots to underscores
// Dots are replaced to avoid creating unintended namespace segments
let sanitized = name
.replace(/[\s.-]/g, '_')
.replace(/[^\w]/g, '')
.trim();

// C# namespace identifiers cannot start with a digit; prefix with '_' if they do
if (/^[0-9]/.test(sanitized)) {
sanitized = `_${sanitized}`;
}

return sanitized;
}

/**
* Extracts the current namespace from C# file content.
* Supports both traditional block namespaces and file-scoped namespaces.
* Returns null if no namespace declaration is found.
*/
export function extractCurrentNamespace(
content: string
): { namespace: string; isFileScoped: boolean; match: RegExpMatchArray } | null {
// Remove multi-line comments to avoid matching namespaces inside /* */ blocks
const contentWithoutMultiLineComments = content.replace(/\/\*[\s\S]*?\*\//g, '');

// Try file-scoped namespace first (namespace Foo.Bar;)
const fileScopedRegex = /^(\s*)namespace\s+([\w.]+)\s*;/m;
let match = contentWithoutMultiLineComments.match(fileScopedRegex);

if (match) {
return {
namespace: match[2],
isFileScoped: true,
match: match,
};
}

// Try traditional block namespace (namespace Foo.Bar { ... })
const blockNamespaceRegex = /^(\s*)namespace\s+([\w.]+)/m;
match = contentWithoutMultiLineComments.match(blockNamespaceRegex);

if (match) {
return {
namespace: match[2],
isFileScoped: false,
match: match,
};
}

return null;
}
Loading
Loading