-
Notifications
You must be signed in to change notification settings - Fork 289
Add analyzer for OSCondition (MSTEST0059) #7015
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
Copilot
wants to merge
14
commits into
main
Choose a base branch
from
copilot/add-oscondition-analyzer
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.
+1,605
−0
Open
Changes from 10 commits
Commits
Show all changes
14 commits
Select commit
Hold shift + click to select a range
d23a3b4
Initial plan
Copilot 679b549
Add analyzer and code fixer for OSCondition attribute
Copilot a5c0841
Add missing using directive for RoslynAnalyzerHelpers namespace
Copilot 155ccc3
Fix pattern matching issue and unify test structure
Copilot 9063a66
Apply suggestions from code review
Evangelink cbd04fa
Add test cases with trivias (comments) for code fix behavior
Copilot 4953348
Apply suggestions from code review
Evangelink 2e80171
Fix codefix and update tests
Evangelink 16472b0
Add OperatingSystem.Is* support and only flag if statements at beginn…
Copilot a251f24
Fix IDE0046: convert if-return-false to return expression
Copilot 35943b5
Add tests for OSCondition with existing attribute and nested assertions
Copilot 4f379ac
Merge branch 'main' into copilot/add-oscondition-analyzer
Evangelink e99ed4d
Fix broken test
Evangelink 12d2628
Fix line ending issue on linux and macos
Evangelink 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
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
167 changes: 167 additions & 0 deletions
167
...Analyzers/MSTest.Analyzers.CodeFixes/UseOSConditionAttributeInsteadOfRuntimeCheckFixer.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,167 @@ | ||
| // Copyright (c) Microsoft Corporation. All rights reserved. | ||
| // Licensed under the MIT license. See LICENSE file in the project root for full 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.CodeAnalysis.Editing; | ||
|
|
||
| using MSTest.Analyzers.Helpers; | ||
|
|
||
| namespace MSTest.Analyzers; | ||
|
|
||
| /// <summary> | ||
| /// Code fixer for <see cref="UseOSConditionAttributeInsteadOfRuntimeCheckAnalyzer"/>. | ||
| /// </summary> | ||
| [ExportCodeFixProvider(LanguageNames.CSharp, Name = nameof(UseOSConditionAttributeInsteadOfRuntimeCheckFixer))] | ||
| [Shared] | ||
| public sealed class UseOSConditionAttributeInsteadOfRuntimeCheckFixer : CodeFixProvider | ||
| { | ||
| /// <inheritdoc /> | ||
| public override ImmutableArray<string> FixableDiagnosticIds { get; } | ||
| = ImmutableArray.Create(DiagnosticIds.UseOSConditionAttributeInsteadOfRuntimeCheckRuleId); | ||
|
|
||
| /// <inheritdoc /> | ||
| public override FixAllProvider GetFixAllProvider() | ||
Evangelink marked this conversation as resolved.
Show resolved
Hide resolved
|
||
| => WellKnownFixAllProviders.BatchFixer; | ||
|
|
||
| /// <inheritdoc /> | ||
| public override async Task RegisterCodeFixesAsync(CodeFixContext context) | ||
Evangelink marked this conversation as resolved.
Show resolved
Hide resolved
|
||
| { | ||
| SyntaxNode root = await context.Document.GetRequiredSyntaxRootAsync(context.CancellationToken).ConfigureAwait(false); | ||
| Diagnostic diagnostic = context.Diagnostics[0]; | ||
|
|
||
| string? isNegatedStr = diagnostic.Properties[UseOSConditionAttributeInsteadOfRuntimeCheckAnalyzer.IsNegatedKey]; | ||
| string? osPlatform = diagnostic.Properties[UseOSConditionAttributeInsteadOfRuntimeCheckAnalyzer.OSPlatformKey]; | ||
|
|
||
| if (isNegatedStr is null || osPlatform is null || !bool.TryParse(isNegatedStr, out bool isNegated)) | ||
| { | ||
| return; | ||
| } | ||
|
|
||
| SyntaxNode diagnosticNode = root.FindNode(diagnostic.Location.SourceSpan, getInnermostNodeForTie: true); | ||
|
|
||
| // Find the containing method | ||
| MethodDeclarationSyntax? methodDeclaration = diagnosticNode.FirstAncestorOrSelf<MethodDeclarationSyntax>(); | ||
| if (methodDeclaration is null) | ||
| { | ||
| return; | ||
| } | ||
|
|
||
| // Find the if statement to remove | ||
| IfStatementSyntax? ifStatement = diagnosticNode.FirstAncestorOrSelf<IfStatementSyntax>(); | ||
Evangelink marked this conversation as resolved.
Show resolved
Hide resolved
|
||
| if (ifStatement is null) | ||
| { | ||
| return; | ||
| } | ||
|
|
||
| context.RegisterCodeFix( | ||
| CodeAction.Create( | ||
| title: CodeFixResources.UseOSConditionAttributeInsteadOfRuntimeCheckFix, | ||
| createChangedDocument: ct => AddOSConditionAttributeAsync(context.Document, methodDeclaration, ifStatement, osPlatform, isNegated, ct), | ||
| equivalenceKey: nameof(UseOSConditionAttributeInsteadOfRuntimeCheckFixer)), | ||
| diagnostic); | ||
| } | ||
|
|
||
| private static async Task<Document> AddOSConditionAttributeAsync( | ||
| Document document, | ||
| MethodDeclarationSyntax methodDeclaration, | ||
| IfStatementSyntax ifStatement, | ||
| string osPlatform, | ||
| bool isNegated, | ||
| CancellationToken cancellationToken) | ||
| { | ||
| DocumentEditor editor = await DocumentEditor.CreateAsync(document, cancellationToken).ConfigureAwait(false); | ||
|
|
||
| // Map OSPlatform to OperatingSystems enum | ||
| string? operatingSystem = MapOSPlatformToOperatingSystem(osPlatform); | ||
| if (operatingSystem is null) | ||
| { | ||
| return document; | ||
| } | ||
|
|
||
| // Determine the condition mode: | ||
| // - If isNegated is false (checking if IS on platform, then early return), we want to EXCLUDE this platform | ||
| // - If isNegated is true (checking if NOT on platform, then early return), we want to INCLUDE this platform only | ||
| // Actually: | ||
| // if (!RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) return; => Include Windows only (default, omit ConditionMode) | ||
| // if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) return; => Exclude Windows | ||
|
|
||
| // Create the attribute | ||
| AttributeSyntax osConditionAttribute; | ||
| if (isNegated) | ||
| { | ||
| // Include mode is the default, so we only need to specify the operating system | ||
| osConditionAttribute = SyntaxFactory.Attribute( | ||
| SyntaxFactory.IdentifierName("OSCondition"), | ||
| SyntaxFactory.AttributeArgumentList( | ||
| SyntaxFactory.SingletonSeparatedList( | ||
| SyntaxFactory.AttributeArgument( | ||
| SyntaxFactory.ParseExpression($"OperatingSystems.{operatingSystem}"))))); | ||
| } | ||
| else | ||
| { | ||
| // Exclude mode must be explicitly specified | ||
| osConditionAttribute = SyntaxFactory.Attribute( | ||
| SyntaxFactory.IdentifierName("OSCondition"), | ||
| SyntaxFactory.AttributeArgumentList( | ||
| SyntaxFactory.SeparatedList(new[] | ||
| { | ||
| SyntaxFactory.AttributeArgument( | ||
| SyntaxFactory.ParseExpression("ConditionMode.Exclude")), | ||
| SyntaxFactory.AttributeArgument( | ||
| SyntaxFactory.ParseExpression($"OperatingSystems.{operatingSystem}")), | ||
| }))); | ||
| } | ||
|
|
||
| // Check if the method already has an OSCondition attribute | ||
| bool hasOSConditionAttribute = methodDeclaration.AttributeLists | ||
| .SelectMany(al => al.Attributes) | ||
| .Any(a => a.Name.ToString() is "OSCondition" or "OSConditionAttribute"); | ||
|
|
||
| // Track the if statement on the original method before making any modifications | ||
| MethodDeclarationSyntax trackedMethod = methodDeclaration.TrackNodes(ifStatement); | ||
| IfStatementSyntax? trackedIfStatement = trackedMethod.GetCurrentNode(ifStatement); | ||
|
|
||
| if (trackedIfStatement is null) | ||
| { | ||
| return document; | ||
| } | ||
|
|
||
| // Remove the if statement from the method body | ||
| MethodDeclarationSyntax newMethod = trackedMethod.RemoveNode(trackedIfStatement, SyntaxRemoveOptions.KeepNoTrivia)!; | ||
|
|
||
| if (!hasOSConditionAttribute) | ||
| { | ||
| // Add the attribute to the method | ||
| // Use CarriageReturnLineFeed to match the formatting of attributes added by the editor | ||
| AttributeListSyntax newAttributeList = SyntaxFactory.AttributeList( | ||
| SyntaxFactory.SingletonSeparatedList(osConditionAttribute)) | ||
| .WithTrailingTrivia(SyntaxFactory.CarriageReturnLineFeed); | ||
|
|
||
| newMethod = newMethod.AddAttributeLists(newAttributeList); | ||
| } | ||
|
|
||
| // Replace the entire method declaration with the modified version | ||
| editor.ReplaceNode(methodDeclaration, newMethod); | ||
|
|
||
| return editor.GetChangedDocument(); | ||
| } | ||
|
|
||
| private static string? MapOSPlatformToOperatingSystem(string osPlatform) | ||
| => osPlatform.ToUpperInvariant() switch | ||
| { | ||
| "WINDOWS" => "Windows", | ||
| "LINUX" => "Linux", | ||
| "OSX" => "OSX", | ||
| "FREEBSD" => "FreeBSD", | ||
| _ => null, | ||
| }; | ||
| } | ||
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
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
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
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
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.