-
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 all 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
272 changes: 272 additions & 0 deletions
272
...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,272 @@ | ||
| // 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); | ||
|
|
||
| string? operatingSystem = MapOSPlatformToOperatingSystem(osPlatform); | ||
| if (operatingSystem is null) | ||
| { | ||
| return document; | ||
| } | ||
|
|
||
| MethodDeclarationSyntax? modifiedMethod = RemoveIfStatementFromMethod(methodDeclaration, ifStatement); | ||
| if (modifiedMethod is null) | ||
| { | ||
| return document; | ||
| } | ||
|
|
||
| AttributeSyntax? existingAttribute = FindExistingOSConditionAttribute(methodDeclaration); | ||
| MethodDeclarationSyntax newMethod = existingAttribute is not null | ||
| ? UpdateMethodWithCombinedAttribute(modifiedMethod, existingAttribute, operatingSystem, isNegated) | ||
| : AddNewAttributeToMethod(modifiedMethod, operatingSystem, isNegated); | ||
|
|
||
| editor.ReplaceNode(methodDeclaration, newMethod); | ||
| return editor.GetChangedDocument(); | ||
| } | ||
|
|
||
| private static MethodDeclarationSyntax? RemoveIfStatementFromMethod( | ||
| MethodDeclarationSyntax methodDeclaration, | ||
| IfStatementSyntax ifStatement) | ||
| { | ||
| MethodDeclarationSyntax trackedMethod = methodDeclaration.TrackNodes(ifStatement); | ||
| IfStatementSyntax? trackedIfStatement = trackedMethod.GetCurrentNode(ifStatement); | ||
|
|
||
| return trackedIfStatement is not null | ||
| ? trackedMethod.RemoveNode(trackedIfStatement, SyntaxRemoveOptions.KeepNoTrivia) | ||
| : null; | ||
| } | ||
|
|
||
| private static AttributeSyntax? FindExistingOSConditionAttribute(MethodDeclarationSyntax methodDeclaration) | ||
| => methodDeclaration.AttributeLists | ||
| .SelectMany(al => al.Attributes) | ||
| .FirstOrDefault(a => a.Name.ToString() is "OSCondition" or "OSConditionAttribute"); | ||
|
|
||
| private static MethodDeclarationSyntax UpdateMethodWithCombinedAttribute( | ||
| MethodDeclarationSyntax method, | ||
| AttributeSyntax existingAttribute, | ||
| string operatingSystem, | ||
| bool isNegated) | ||
| { | ||
| ExistingAttributeInfo attributeInfo = ParseExistingAttribute(existingAttribute); | ||
|
|
||
| // Only combine if the condition modes match | ||
| if (CanCombineAttributes(attributeInfo.IsIncludeMode, isNegated)) | ||
| { | ||
| string combinedOSValue = CombineOSValues(attributeInfo.OSValue, operatingSystem); | ||
| AttributeSyntax newAttribute = CreateCombinedAttribute(combinedOSValue, isNegated); | ||
| return ReplaceExistingAttribute(method, newAttribute); | ||
| } | ||
|
|
||
| // Different condition modes - add as separate attribute | ||
| // (This shouldn't happen in practice since OSCondition doesn't allow multiple attributes) | ||
| return AddNewAttributeToMethod(method, operatingSystem, isNegated); | ||
| } | ||
|
|
||
| private static ExistingAttributeInfo ParseExistingAttribute(AttributeSyntax attribute) | ||
| { | ||
| if (attribute.ArgumentList is null) | ||
| { | ||
| return new ExistingAttributeInfo(IsIncludeMode: true, OSValue: null); | ||
| } | ||
|
|
||
| SeparatedSyntaxList<AttributeArgumentSyntax> args = attribute.ArgumentList.Arguments; | ||
|
|
||
| return args.Count switch | ||
| { | ||
| // [OSCondition(OperatingSystems.Linux)] - Include mode | ||
| 1 => new ExistingAttributeInfo( | ||
| IsIncludeMode: true, | ||
| OSValue: args[0].Expression.ToString()), | ||
|
|
||
| // [OSCondition(ConditionMode.Exclude, OperatingSystems.Windows)] | ||
| 2 => new ExistingAttributeInfo( | ||
| IsIncludeMode: !args[0].Expression.ToString().Contains("Exclude"), | ||
| OSValue: args[1].Expression.ToString()), | ||
|
|
||
| _ => new ExistingAttributeInfo(IsIncludeMode: true, OSValue: null), | ||
| }; | ||
| } | ||
|
|
||
| private static bool CanCombineAttributes(bool existingIsIncludeMode, bool isNegated) | ||
| => (isNegated && existingIsIncludeMode) || (!isNegated && !existingIsIncludeMode); | ||
|
|
||
| private static string CombineOSValues(string? existingOSValue, string newOperatingSystem) | ||
| => existingOSValue is not null | ||
| ? $"{existingOSValue} | OperatingSystems.{newOperatingSystem}" | ||
| : $"OperatingSystems.{newOperatingSystem}"; | ||
|
|
||
| private static AttributeSyntax CreateCombinedAttribute(string osValue, bool isNegated) | ||
| { | ||
| if (isNegated) | ||
| { | ||
| // Include mode (default) | ||
| return SyntaxFactory.Attribute( | ||
| SyntaxFactory.IdentifierName("OSCondition"), | ||
| SyntaxFactory.AttributeArgumentList( | ||
| SyntaxFactory.SingletonSeparatedList( | ||
| SyntaxFactory.AttributeArgument( | ||
| SyntaxFactory.ParseExpression(osValue))))); | ||
| } | ||
|
|
||
| // Exclude mode | ||
| return SyntaxFactory.Attribute( | ||
| SyntaxFactory.IdentifierName("OSCondition"), | ||
| SyntaxFactory.AttributeArgumentList( | ||
| SyntaxFactory.SeparatedList(new[] | ||
| { | ||
| SyntaxFactory.AttributeArgument( | ||
| SyntaxFactory.ParseExpression("ConditionMode.Exclude")), | ||
| SyntaxFactory.AttributeArgument( | ||
| SyntaxFactory.ParseExpression(osValue)), | ||
| }))); | ||
| } | ||
|
|
||
| private static MethodDeclarationSyntax ReplaceExistingAttribute( | ||
| MethodDeclarationSyntax method, | ||
| AttributeSyntax newAttribute) | ||
| { | ||
| AttributeListSyntax? oldAttributeList = method.AttributeLists | ||
| .FirstOrDefault(al => al.Attributes.Any(a => a.Name.ToString() is "OSCondition" or "OSConditionAttribute")); | ||
|
|
||
| if (oldAttributeList is null) | ||
| { | ||
| return method; | ||
| } | ||
|
|
||
| AttributeListSyntax newAttributeList = SyntaxFactory.AttributeList( | ||
| SyntaxFactory.SingletonSeparatedList(newAttribute)) | ||
| .WithTrailingTrivia(oldAttributeList.GetTrailingTrivia()); | ||
|
|
||
| return method.ReplaceNode(oldAttributeList, newAttributeList); | ||
| } | ||
|
|
||
| private static MethodDeclarationSyntax AddNewAttributeToMethod( | ||
| MethodDeclarationSyntax method, | ||
| string operatingSystem, | ||
| bool isNegated) | ||
| { | ||
| AttributeListSyntax newAttributeList = CreateAttributeList(operatingSystem, isNegated); | ||
| return method.AddAttributeLists(newAttributeList); | ||
| } | ||
|
|
||
| private static AttributeListSyntax CreateAttributeList(string operatingSystem, bool isNegated) | ||
| { | ||
| 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}")), | ||
| }))); | ||
| } | ||
|
|
||
| return SyntaxFactory.AttributeList( | ||
| SyntaxFactory.SingletonSeparatedList(osConditionAttribute)); | ||
| } | ||
|
|
||
| private static string? MapOSPlatformToOperatingSystem(string osPlatform) | ||
| => osPlatform.ToUpperInvariant() switch | ||
| { | ||
| "WINDOWS" => "Windows", | ||
| "LINUX" => "Linux", | ||
| "OSX" => "OSX", | ||
| "FREEBSD" => "FreeBSD", | ||
| _ => null, | ||
| }; | ||
|
|
||
| private readonly record struct ExistingAttributeInfo(bool IsIncludeMode, string? OSValue); | ||
| } | ||
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.