-
Notifications
You must be signed in to change notification settings - Fork 740
Add namespace synchronization feature #8913
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
chandelima
wants to merge
4
commits into
dotnet:main
Choose a base branch
from
chandelima:namespace-sync
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
+921
−2
Open
Changes from all commits
Commits
Show all changes
4 commits
Select commit
Hold shift + click to select a range
ae5b886
Add namespace synchronization feature
chandelima c6ee012
Fix code quality issues from GitHub Copilot review
chandelima c5ce558
Fix cross-platform path handling for namespace calculation
chandelima c3d413f
Refactor namespace calculation and improve URI handling for cross-pla…
chandelima File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Some comments aren't visible on the classic Files Changed page.
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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'); | ||
| } | ||
| } | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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; | ||
| } |
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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.