Skip to content
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

Move analyzer to separate project #355

Merged
merged 1 commit into from
Jun 5, 2024
Merged
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
15 changes: 15 additions & 0 deletions Carter.sln
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,8 @@ Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Carter.ResponseNegotiators.
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Carter.ResponseNegotiators.Newtonsoft.Tests", "test\Carter.ResponseNegotiators.Newtonsoft.Tests\Carter.ResponseNegotiators.Newtonsoft.Tests.csproj", "{47DD3AA8-F072-41E3-AF7F-119DBBD8D14A}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Carter.Analyzers", "src\Carter.Analyzers\Carter.Analyzers.csproj", "{C15C71C0-73CE-41DA-8EEE-C66318BF3A6C}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
Expand Down Expand Up @@ -150,6 +152,18 @@ Global
{47DD3AA8-F072-41E3-AF7F-119DBBD8D14A}.Release|x64.Build.0 = Release|Any CPU
{47DD3AA8-F072-41E3-AF7F-119DBBD8D14A}.Release|x86.ActiveCfg = Release|Any CPU
{47DD3AA8-F072-41E3-AF7F-119DBBD8D14A}.Release|x86.Build.0 = Release|Any CPU
{C15C71C0-73CE-41DA-8EEE-C66318BF3A6C}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{C15C71C0-73CE-41DA-8EEE-C66318BF3A6C}.Debug|Any CPU.Build.0 = Debug|Any CPU
{C15C71C0-73CE-41DA-8EEE-C66318BF3A6C}.Debug|x64.ActiveCfg = Debug|Any CPU
{C15C71C0-73CE-41DA-8EEE-C66318BF3A6C}.Debug|x64.Build.0 = Debug|Any CPU
{C15C71C0-73CE-41DA-8EEE-C66318BF3A6C}.Debug|x86.ActiveCfg = Debug|Any CPU
{C15C71C0-73CE-41DA-8EEE-C66318BF3A6C}.Debug|x86.Build.0 = Debug|Any CPU
{C15C71C0-73CE-41DA-8EEE-C66318BF3A6C}.Release|Any CPU.ActiveCfg = Release|Any CPU
{C15C71C0-73CE-41DA-8EEE-C66318BF3A6C}.Release|Any CPU.Build.0 = Release|Any CPU
{C15C71C0-73CE-41DA-8EEE-C66318BF3A6C}.Release|x64.ActiveCfg = Release|Any CPU
{C15C71C0-73CE-41DA-8EEE-C66318BF3A6C}.Release|x64.Build.0 = Release|Any CPU
{C15C71C0-73CE-41DA-8EEE-C66318BF3A6C}.Release|x86.ActiveCfg = Release|Any CPU
{C15C71C0-73CE-41DA-8EEE-C66318BF3A6C}.Release|x86.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
Expand All @@ -164,6 +178,7 @@ Global
{E5D99119-96EB-4C01-9EC2-A06FC3EEC182} = {35DE35A0-758D-4FDD-BDA3-67F04F65677D}
{D30E87B0-39AE-41FE-8BA3-E5F9FBFFDD64} = {5D056A8A-821C-4C3C-A281-4FA7F8CE251B}
{47DD3AA8-F072-41E3-AF7F-119DBBD8D14A} = {DCB5B9A0-F06D-4BDF-917D-A459C790C718}
{C15C71C0-73CE-41DA-8EEE-C66318BF3A6C} = {5D056A8A-821C-4C3C-A281-4FA7F8CE251B}
EndGlobalSection
GlobalSection(ExtensibilityGlobals) = postSolution
SolutionGuid = {9096DE78-6327-48BA-AE0E-336F769681A7}
Expand Down
19 changes: 19 additions & 0 deletions src/Carter.Analyzers/Carter.Analyzers.csproj
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
<Project Sdk="Microsoft.NET.Sdk">

<PropertyGroup>
<TargetFramework>netstandard2.0</TargetFramework>
<Nullable>enable</Nullable>
<ImplicitUsings>enable</ImplicitUsings>
<LangVersion>12</LangVersion>
<EnforceExtendedAnalyzerRules>true</EnforceExtendedAnalyzerRules>
<NoWarn>RS2008</NoWarn>
</PropertyGroup>

<ItemGroup>
<PackageReference Include="Microsoft.CodeAnalysis.CSharp" Version="4.7.0" />
</ItemGroup>

<ItemGroup>
<InternalsVisibleTo Include="Carter.Tests" />
</ItemGroup>
</Project>
Original file line number Diff line number Diff line change
Expand Up @@ -44,28 +44,28 @@ private static void OnTypeAnalysis(SymbolAnalysisContext context, INamedTypeSymb
foreach (var syntaxReference in constructor.DeclaringSyntaxReferences)
{
var node = syntaxReference.GetSyntax();
SyntaxToken identifier;
if (node is ConstructorDeclarationSyntax constructorDeclaration)
SyntaxToken? identifier = node switch
{
identifier = constructorDeclaration.Identifier;
} else if (node is RecordDeclarationSyntax recordDeclaration)
{
identifier = recordDeclaration.Identifier;
}
else
ConstructorDeclarationSyntax constructorDeclaration => constructorDeclaration.Identifier,
RecordDeclarationSyntax recordDeclaration => recordDeclaration.Identifier,
ClassDeclarationSyntax classDeclaration => classDeclaration.Identifier,
StructDeclarationSyntax structDeclaration => structDeclaration.Identifier,
_ => null
};
if (!identifier.HasValue)
{
continue;
}

var diagnostic = Diagnostic.Create(
DiagnosticDescriptors.CarterModuleShouldNotHaveDependencies,
identifier.GetLocation(),
identifier.Text
identifier.Value.GetLocation(),
identifier.Value.Text
);
context.ReportDiagnostic(diagnostic);
}
}
}

public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics { get; } = [DiagnosticDescriptors.CarterModuleShouldNotHaveDependencies];
public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics { get; } = ImmutableArray.Create(DiagnosticDescriptors.CarterModuleShouldNotHaveDependencies);
}
11 changes: 4 additions & 7 deletions src/Carter/Carter.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -13,27 +13,24 @@
<AllowedOutputExtensionsInPackageBuildOutputFolder>$(AllowedOutputExtensionsInPackageBuildOutputFolder);.pdb</AllowedOutputExtensionsInPackageBuildOutputFolder>
<MinVerSkip Condition="'$(Configuration)' == 'Debug'">true</MinVerSkip>
<PackageReadmeFile>README.md</PackageReadmeFile>
<EnforceExtendedAnalyzerRules>true</EnforceExtendedAnalyzerRules>
<NoWarn>RS2008</NoWarn>
</PropertyGroup>
<ItemGroup>
<None Include="..\..\media\carterlogo.png" Pack="true" PackagePath="\" />
<None Include="..\..\README.md" Pack="true" PackagePath="\"/>
<None Include="$(OutputPath)\$(AssemblyName).dll" Pack="true" PackagePath="analyzers/dotnet/cs" Visible="false" />
<None Include="$(OutputPath)\Carter.Analyzers.dll" Pack="true" PackagePath="analyzers/dotnet/cs" Visible="false" />
</ItemGroup>
<ItemGroup>
<FrameworkReference Include="Microsoft.AspNetCore.App" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\Carter.Analyzers\Carter.Analyzers.csproj" OutputItemType="Analyzer" />
</ItemGroup>
<ItemGroup>
<PackageReference Include="FluentValidation" Version="11.8.0" />
<PackageReference Include="Microsoft.CodeAnalysis.CSharp" Version="4.7.0" PrivateAssets="compile" />
<PackageReference Include="Microsoft.Extensions.DependencyModel" Version="8.0.0" />
<PackageReference Include="Microsoft.SourceLink.GitHub" Version="1.1.1" PrivateAssets="all" />
<PackageReference Include="MinVer" Version="2.5.0">
<PrivateAssets>all</PrivateAssets>
</PackageReference>
</ItemGroup>
<ItemGroup>
<InternalsVisibleTo Include="$(AssemblyName).Tests" />
</ItemGroup>
</Project>
2 changes: 0 additions & 2 deletions src/Carter/DependencyContextAssemblyCatalog.cs
Original file line number Diff line number Diff line change
Expand Up @@ -89,9 +89,7 @@ private static Assembly SafeLoadAssembly(AssemblyName assemblyName)
{
try
{
#pragma warning disable RS1035
return Assembly.Load(assemblyName);
#pragma warning restore RS1035
}
catch (Exception)
{
Expand Down
2 changes: 2 additions & 0 deletions src/Carter/ICarterModule.cs
Original file line number Diff line number Diff line change
Expand Up @@ -54,7 +54,9 @@ protected CarterModule() : this(string.Empty)
/// Initializes a new instance of <see cref="CarterModule"/>
/// </summary>
/// <param name="basePath">A base path to group routes in your <see cref="CarterModule"/></param>
#pragma warning disable CARTER1
protected CarterModule(string basePath)
#pragma warning restore CARTER1
{
this.basePath = basePath;
}
Expand Down
2 changes: 0 additions & 2 deletions src/Carter/ModelBinding/BindExtensions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -88,14 +88,12 @@ public static async Task BindAndSaveFile(this HttpRequest request, string saveLo

private static async Task SaveFileInternal(IFormFile file, string saveLocation, string fileName = "")
{
#pragma warning disable RS1035
if (!Directory.Exists(saveLocation))
Directory.CreateDirectory(saveLocation);

fileName = !string.IsNullOrWhiteSpace(fileName) ? fileName : file.FileName;

using (var fileToSave = File.Create(Path.Combine(saveLocation, fileName)))
await file.CopyToAsync(fileToSave);
#pragma warning restore RS1035
}
}
25 changes: 25 additions & 0 deletions test/Carter.Tests/Analyzers/CSharpPreviewAnalyzerTest.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
namespace Carter.Tests.Analyzers;

using System.IO;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.CSharp.Testing;
using Microsoft.CodeAnalysis.Diagnostics;
using Microsoft.CodeAnalysis.Testing;
using Microsoft.CodeAnalysis.Testing.Verifiers;

public sealed class CSharpPreviewAnalyzerTest<TAnalyzer> : CSharpAnalyzerTest<TAnalyzer, XUnitVerifier>
where TAnalyzer : DiagnosticAnalyzer, new()
{
public CSharpPreviewAnalyzerTest(string code)
{
var carterPackage = new PackageIdentity("Carter", "8.1.0");
var aspNetPackage = new PackageIdentity("Microsoft.AspNetCore.App.Ref", "8.0.0");
var bclPackage = new PackageIdentity("Microsoft.NETCore.App.Ref", "8.0.0");
ReferenceAssemblies = new ReferenceAssemblies("net8.0", bclPackage, Path.Combine("ref", "net8.0")).AddPackages([carterPackage, aspNetPackage]);
TestCode = code;

}
protected override ParseOptions CreateParseOptions()
=> new CSharpParseOptions(LanguageVersion.Preview, DocumentationMode.Diagnose);
}
Original file line number Diff line number Diff line change
@@ -1,9 +1,7 @@
namespace Carter.Tests.Analyzers;

using System.IO;
using System.Threading.Tasks;
using Carter.Analyzers;
using Microsoft.CodeAnalysis.CSharp.Testing;
using Microsoft.CodeAnalysis.Testing;
using Microsoft.CodeAnalysis.Testing.Verifiers;
using Xunit;
Expand Down Expand Up @@ -33,7 +31,7 @@ public void AddRoutes(IEndpointRouteBuilder app) {}
.WithLocation(0)
.WithArguments("MyCarterModule");

return this.VerifyAsync(code, diagnosticResult);
return VerifyAsync(code, diagnosticResult);
}

[Theory]
Expand All @@ -55,7 +53,7 @@ public void AddRoutes(IEndpointRouteBuilder app) {}
.WithLocation(0)
.WithArguments("MyCarterModule");

return this.VerifyAsync(code, diagnosticResult);
return VerifyAsync(code, diagnosticResult);
}

[Theory]
Expand All @@ -81,7 +79,7 @@ public void AddRoutes(IEndpointRouteBuilder app) {}
.WithLocation(0)
.WithArguments("MyCarterModule");

return this.VerifyAsync(code, diagnosticResult);
return VerifyAsync(code, diagnosticResult);
}

[Theory]
Expand All @@ -103,7 +101,7 @@ public void AddRoutes(IEndpointRouteBuilder app) {}
.WithLocation(0)
.WithArguments("MyCarterModule");

return this.VerifyAsync(code, diagnosticResult);
return VerifyAsync(code, diagnosticResult);
}

[Theory]
Expand All @@ -129,7 +127,7 @@ public void AddRoutes(IEndpointRouteBuilder app) {}
.WithLocation(0)
.WithArguments("MyCarterModule");

return this.VerifyAsync(code, diagnosticResult);
return VerifyAsync(code, diagnosticResult);
}

[Theory]
Expand All @@ -151,7 +149,7 @@ public void AddRoutes(IEndpointRouteBuilder app) {}
.WithLocation(0)
.WithArguments("MyCarterModule");

return this.VerifyAsync(code, diagnosticResult);
return VerifyAsync(code, diagnosticResult);
}

[Theory]
Expand All @@ -173,7 +171,7 @@ public void AddRoutes(IEndpointRouteBuilder app) {}
}
""";

return this.VerifyAsync(code);
return VerifyAsync(code);
}

[Theory]
Expand All @@ -195,7 +193,7 @@ public void AddRoutes(IEndpointRouteBuilder app) {}
}
""";

return this.VerifyAsync(code);
return VerifyAsync(code);
}

[Theory]
Expand All @@ -217,7 +215,7 @@ public void AddRoutes(IEndpointRouteBuilder app) {}
}
""";

return this.VerifyAsync(code);
return VerifyAsync(code);
}

[Theory]
Expand All @@ -243,7 +241,7 @@ public void AddRoutes(IEndpointRouteBuilder app) {}
}
""";

return this.VerifyAsync(code);
return VerifyAsync(code);
}

[Theory]
Expand All @@ -262,7 +260,7 @@ internal MyCarterModule(string s, int i) {}
}
""";

return this.VerifyAsync(code);
return VerifyAsync(code);
}

[Theory]
Expand All @@ -278,7 +276,7 @@ public Task RecordNonCarterModuleWithConstructorDependencies_NoDiagnostic(string
}
""";

return this.VerifyAsync(code);
return VerifyAsync(code);
}

[Theory]
Expand All @@ -301,22 +299,54 @@ public MySubCarterModule(string s) {}
}
""";

return this.VerifyAsync(code);
return VerifyAsync(code);
}

private Task VerifyAsync(string code, DiagnosticResult? diagnosticResult = null)
[Theory]
[InlineData("class")]
[InlineData("struct")]
public Task EmptyPrimaryConstructor_NoDiagnostic(string type)
{
var carterPackage = new PackageIdentity("Carter", "8.1.0");
var aspNetPackage = new PackageIdentity("Microsoft.AspNetCore.App.Ref", "8.0.0");
var bclPackage = new PackageIdentity("Microsoft.NETCore.App.Ref", "8.0.0");
var referenceAssemblies = new ReferenceAssemblies("net8.0", bclPackage, Path.Combine("ref", "net8.0"))
.AddPackages([carterPackage, aspNetPackage]);
AnalyzerTest<XUnitVerifier> test = new CSharpAnalyzerTest<CarterModuleShouldNotHaveDependenciesAnalyzer, XUnitVerifier>
{
TestCode = code,
ReferenceAssemblies = referenceAssemblies
};
var code = $$"""
using Carter;
using Microsoft.AspNetCore.Routing;

{{type}} MyCarterModule() : ICarterModule
{
public void AddRoutes(IEndpointRouteBuilder app) {}
}
""";

return VerifyAsync(code);
}

[Theory]
[InlineData("class", "string s")]
[InlineData("struct", "string s")]
[InlineData("class", "string s, int i")]
[InlineData("struct", "string s, int i")]
public Task PrimaryConstructor_Diagnostic(string type, string parameters)
{
var code = $$"""
using Carter;
using Microsoft.AspNetCore.Routing;

{{type}} {|#0:MyCarterModule|}({{parameters}}) : ICarterModule
{
public void AddRoutes(IEndpointRouteBuilder app) {}
}
""";

var diagnosticResult = new DiagnosticResult(DiagnosticDescriptors.CarterModuleShouldNotHaveDependencies)
.WithLocation(0)
.WithArguments("MyCarterModule");

return VerifyAsync(code, diagnosticResult);
}

private static Task VerifyAsync(string code, DiagnosticResult? diagnosticResult = null)
{
AnalyzerTest<XUnitVerifier> test = new CSharpPreviewAnalyzerTest<CarterModuleShouldNotHaveDependenciesAnalyzer>(code);
if (diagnosticResult.HasValue)
{
test.ExpectedDiagnostics.Add(diagnosticResult.Value);
Expand Down
1 change: 1 addition & 0 deletions test/Carter.Tests/Carter.Tests.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\..\src\Carter\Carter.csproj" />
<ProjectReference Include="..\..\src\Carter.Analyzers\Carter.Analyzers.csproj" />
</ItemGroup>
<ItemGroup>
<PackageReference Include="MartinCostello.Logging.XUnit" Version="0.1.0" />
Expand Down
Loading