-
Notifications
You must be signed in to change notification settings - Fork 1.2k
Add CA1877: Collapse nested Path.Combine/Path.Join calls #51456
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
Merged
Merged
Changes from all commits
Commits
Show all changes
2 commits
Select commit
Hold shift + click to select a range
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
There are no files selected for viewing
107 changes: 107 additions & 0 deletions
107
...ers/Microsoft.NetCore.Analyzers/Performance/CSharpCollapseMultiplePathOperations.Fixer.cs
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,107 @@ | ||
| // Copyright (c) Microsoft. All Rights Reserved. Licensed under the MIT license. See License.txt in the project root for license information. | ||
|
|
||
| using System.Collections.Immutable; | ||
| using System.Composition; | ||
| using Analyzer.Utilities; | ||
| using Microsoft.CodeAnalysis; | ||
| using Microsoft.CodeAnalysis.CodeActions; | ||
| using Microsoft.CodeAnalysis.CodeFixes; | ||
| using Microsoft.CodeAnalysis.CSharp; | ||
| using Microsoft.CodeAnalysis.CSharp.Syntax; | ||
| using Microsoft.NetCore.Analyzers; | ||
| using Microsoft.NetCore.Analyzers.Performance; | ||
|
|
||
| namespace Microsoft.NetCore.CSharp.Analyzers.Performance | ||
| { | ||
| [ExportCodeFixProvider(LanguageNames.CSharp), Shared] | ||
| public sealed class CSharpCollapseMultiplePathOperationsFixer : CodeFixProvider | ||
| { | ||
| public override ImmutableArray<string> FixableDiagnosticIds { get; } = ImmutableArray.Create(CollapseMultiplePathOperationsAnalyzer.RuleId); | ||
|
|
||
| public override FixAllProvider GetFixAllProvider() | ||
| => WellKnownFixAllProviders.BatchFixer; | ||
|
|
||
| public sealed override async Task RegisterCodeFixesAsync(CodeFixContext context) | ||
| { | ||
| var document = context.Document; | ||
| var diagnostic = context.Diagnostics[0]; | ||
| var root = await document.GetRequiredSyntaxRootAsync(context.CancellationToken).ConfigureAwait(false); | ||
| var node = root.FindNode(context.Span, getInnermostNodeForTie: true); | ||
|
|
||
| if (node is not InvocationExpressionSyntax invocation || | ||
| await document.GetSemanticModelAsync(context.CancellationToken).ConfigureAwait(false) is not { } semanticModel || | ||
| semanticModel.Compilation.GetTypeByMetadataName(WellKnownTypeNames.SystemIOPath) is not { } pathType) | ||
| { | ||
| return; | ||
| } | ||
|
|
||
| // Get the method name from diagnostic properties | ||
| if (!diagnostic.Properties.TryGetValue(CollapseMultiplePathOperationsAnalyzer.MethodNameKey, out var methodName)) | ||
| { | ||
| methodName = "Path"; | ||
| } | ||
|
|
||
| context.RegisterCodeFix( | ||
| CodeAction.Create( | ||
| string.Format(MicrosoftNetCoreAnalyzersResources.CollapseMultiplePathOperationsCodeFixTitle, methodName), | ||
| createChangedDocument: cancellationToken => CollapsePathOperationAsync(document, root, invocation, pathType, semanticModel, cancellationToken), | ||
| equivalenceKey: nameof(MicrosoftNetCoreAnalyzersResources.CollapseMultiplePathOperationsCodeFixTitle)), | ||
| diagnostic); | ||
| } | ||
|
|
||
| private static Task<Document> CollapsePathOperationAsync(Document document, SyntaxNode root, InvocationExpressionSyntax invocation, INamedTypeSymbol pathType, SemanticModel semanticModel, CancellationToken cancellationToken) | ||
| { | ||
| // Collect all arguments by recursively unwrapping nested Path.Combine/Join calls | ||
| var allArguments = CollectAllArguments(invocation, pathType, semanticModel); | ||
|
|
||
| // Create new argument list with all collected arguments | ||
| var newArgumentList = SyntaxFactory.ArgumentList( | ||
| SyntaxFactory.SeparatedList(allArguments)); | ||
|
|
||
| // Create the new invocation with all arguments | ||
| var newInvocation = invocation.WithArgumentList(newArgumentList) | ||
| .WithTriviaFrom(invocation); | ||
|
|
||
| var newRoot = root.ReplaceNode(invocation, newInvocation); | ||
|
|
||
| return Task.FromResult(document.WithSyntaxRoot(newRoot)); | ||
| } | ||
|
|
||
| private static ArgumentSyntax[] CollectAllArguments(InvocationExpressionSyntax invocation, INamedTypeSymbol pathType, SemanticModel semanticModel) | ||
| { | ||
| var arguments = ImmutableArray.CreateBuilder<ArgumentSyntax>(); | ||
|
|
||
| foreach (var argument in invocation.ArgumentList.Arguments) | ||
| { | ||
| if (argument.Expression is InvocationExpressionSyntax nestedInvocation && | ||
| IsPathCombineOrJoin(nestedInvocation, pathType, semanticModel, out var methodName) && | ||
| IsPathCombineOrJoin(invocation, pathType, semanticModel, out var outerMethodName) && | ||
| methodName == outerMethodName) | ||
| { | ||
| // Recursively collect arguments from nested invocation | ||
| arguments.AddRange(CollectAllArguments(nestedInvocation, pathType, semanticModel)); | ||
| } | ||
| else | ||
| { | ||
| arguments.Add(argument); | ||
| } | ||
| } | ||
|
|
||
| return arguments.ToArray(); | ||
| } | ||
|
|
||
| private static bool IsPathCombineOrJoin(InvocationExpressionSyntax invocation, INamedTypeSymbol pathType, SemanticModel semanticModel, out string methodName) | ||
| { | ||
| if (semanticModel.GetSymbolInfo(invocation).Symbol is IMethodSymbol methodSymbol && | ||
| SymbolEqualityComparer.Default.Equals(methodSymbol.ContainingType, pathType) && | ||
| methodSymbol.Name is "Combine" or "Join") | ||
| { | ||
| methodName = methodSymbol.Name; | ||
| return true; | ||
| } | ||
|
|
||
| methodName = string.Empty; | ||
| return false; | ||
| } | ||
| } | ||
| } | ||
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
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.
Uh oh!
There was an error while loading. Please reload this page.