-
Notifications
You must be signed in to change notification settings - Fork 198
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
Add an analyzer to detect when a duplicate razor file is provided #11498
base: main
Are you sure you want to change the base?
Changes from all commits
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,51 @@ | ||
// Licensed to the .NET Foundation under one or more agreements. | ||
// The .NET Foundation licenses this file to you under the MIT license. | ||
|
||
using System; | ||
using System.Collections.Generic; | ||
using System.Collections.Immutable; | ||
using Microsoft.CodeAnalysis; | ||
using Microsoft.CodeAnalysis.Diagnostics; | ||
using Microsoft.CodeAnalysis.Text; | ||
using Microsoft.NET.Sdk.Razor.SourceGenerators; | ||
|
||
namespace Microsoft.AspNetCore.Razor.SourceGenerators; | ||
|
||
#pragma warning disable RS1041 // Compiler extensions should be implemented in assemblies targeting netstandard2.0 | ||
[DiagnosticAnalyzer(LanguageNames.CSharp)] | ||
#pragma warning restore RS1041 // Compiler extensions should be implemented in assemblies targeting netstandard2.0 | ||
public class DuplicateRazorFileIncludedAnalyzer : DiagnosticAnalyzer | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Sealed? |
||
{ | ||
private static readonly ImmutableArray<DiagnosticDescriptor> s_supportedDiagnostics = ImmutableArray.Create(RazorDiagnostics.DuplicateRazorFileIncludedDescriptor); | ||
|
||
public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics => s_supportedDiagnostics; | ||
|
||
public override void Initialize(AnalysisContext context) | ||
{ | ||
context.ConfigureGeneratedCodeAnalysis(GeneratedCodeAnalysisFlags.None); | ||
context.EnableConcurrentExecution(); | ||
context.RegisterCompilationStartAction(static compStartAction => | ||
{ | ||
var includedFiles = new HashSet<string>(StringComparer.Ordinal); | ||
|
||
compStartAction.RegisterAdditionalFileAction(additionalFilesContext => | ||
{ | ||
var additionalFile = additionalFilesContext.AdditionalFile; | ||
|
||
if (additionalFile.Path.EndsWith(".cshtml", StringComparison.Ordinal) || | ||
additionalFile.Path.EndsWith(".razor", StringComparison.Ordinal)) | ||
{ | ||
if (!includedFiles.Add(additionalFile.Path)) | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Can it happen that the paths are equivalent but not normalized at this point? For example:
This check would not catch such duplicates. |
||
{ | ||
var diagnostic = Diagnostic.Create( | ||
RazorDiagnostics.DuplicateRazorFileIncludedDescriptor, | ||
Location.Create(additionalFile.Path, new TextSpan(0, 0), new LinePositionSpan(LinePosition.Zero, LinePosition.Zero)), | ||
additionalFile.Path); | ||
|
||
additionalFilesContext.ReportDiagnostic(diagnostic); | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more.
The source generator will still run and report errors though, right? Wouldn't it be better if this was part of the SG pipeline then? What's the advantage of a separate analyzer anyway? There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. There is a general feeling that we should be moving towards analyzers producing diagnostics over generators as they play better in the incremental space. There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Perhaps the source generator could also detect this situation and bail early to avoid producing superfluous diagnostics. There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more.
Thinking about this recommendation in general, it's hard to imagine all the diagnostics that are produced by the razor SG now would instead be produced by some analyzer, that sounds like a lot of duplicate (and hence error-prone) logic. |
||
} | ||
} | ||
}); | ||
}); | ||
} | ||
} |
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,17 +1,17 @@ | ||
<?xml version="1.0" encoding="utf-8"?> | ||
<root> | ||
<!-- | ||
Microsoft ResX Schema | ||
<!-- | ||
Microsoft ResX Schema | ||
|
||
Version 2.0 | ||
The primary goals of this format is to allow a simple XML format | ||
that is mostly human readable. The generation and parsing of the | ||
various data types are done through the TypeConverter classes | ||
|
||
The primary goals of this format is to allow a simple XML format | ||
that is mostly human readable. The generation and parsing of the | ||
various data types are done through the TypeConverter classes | ||
associated with the data types. | ||
|
||
Example: | ||
|
||
... ado.net/XML headers & schema ... | ||
<resheader name="resmimetype">text/microsoft-resx</resheader> | ||
<resheader name="version">2.0</resheader> | ||
|
@@ -26,36 +26,36 @@ | |
<value>[base64 mime encoded string representing a byte array form of the .NET Framework object]</value> | ||
<comment>This is a comment</comment> | ||
</data> | ||
There are any number of "resheader" rows that contain simple | ||
|
||
There are any number of "resheader" rows that contain simple | ||
name/value pairs. | ||
Each data row contains a name, and value. The row also contains a | ||
type or mimetype. Type corresponds to a .NET class that support | ||
text/value conversion through the TypeConverter architecture. | ||
Classes that don't support this are serialized and stored with the | ||
|
||
Each data row contains a name, and value. The row also contains a | ||
type or mimetype. Type corresponds to a .NET class that support | ||
text/value conversion through the TypeConverter architecture. | ||
Classes that don't support this are serialized and stored with the | ||
mimetype set. | ||
The mimetype is used for serialized objects, and tells the | ||
ResXResourceReader how to depersist the object. This is currently not | ||
|
||
The mimetype is used for serialized objects, and tells the | ||
ResXResourceReader how to depersist the object. This is currently not | ||
extensible. For a given mimetype the value must be set accordingly: | ||
Note - application/x-microsoft.net.object.binary.base64 is the format | ||
that the ResXResourceWriter will generate, however the reader can | ||
|
||
Note - application/x-microsoft.net.object.binary.base64 is the format | ||
that the ResXResourceWriter will generate, however the reader can | ||
read any of the formats listed below. | ||
|
||
mimetype: application/x-microsoft.net.object.binary.base64 | ||
value : The object must be serialized with | ||
value : The object must be serialized with | ||
: System.Runtime.Serialization.Formatters.Binary.BinaryFormatter | ||
: and then encoded with base64 encoding. | ||
|
||
mimetype: application/x-microsoft.net.object.soap.base64 | ||
value : The object must be serialized with | ||
value : The object must be serialized with | ||
: System.Runtime.Serialization.Formatters.Soap.SoapFormatter | ||
: and then encoded with base64 encoding. | ||
|
||
mimetype: application/x-microsoft.net.object.bytearray.base64 | ||
value : The object must be serialized into a byte array | ||
value : The object must be serialized into a byte array | ||
: using a System.ComponentModel.TypeConverter | ||
: and then encoded with base64 encoding. | ||
--> | ||
|
@@ -177,4 +177,10 @@ | |
<data name="MetadataReferenceNotProvidedMessage" xml:space="preserve"> | ||
<value>Expected a valid MetadataReference, but found none.</value> | ||
</data> | ||
</root> | ||
<data name="DuplicateRazorFileIncludedTitle" xml:space="preserve"> | ||
<value>Razor file was included twice</value> | ||
</data> | ||
<data name="DuplicateRazorFileIncludedMessage" xml:space="preserve"> | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Nit: Should this be more specific and say "was included as an additional file" rather than just "in the build"? Including it in the build twice isn't actually a problem if the items have different item types, eg EmbeddedResource and AdditionalFiles, right? Also "more than once" rather than "twice" because it could actually be three times 😛 |
||
<value>File '{0}' was included in the build twice. This will cause generator build issues.</value> | ||
</data> | ||
</root> |
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,118 @@ | ||
// Licensed to the .NET Foundation under one or more agreements. | ||
// The .NET Foundation licenses this file to you under the MIT license. | ||
|
||
using System.Threading.Tasks; | ||
using Microsoft.AspNetCore.Razor.SourceGenerators; | ||
using Microsoft.CodeAnalysis; | ||
using Microsoft.CodeAnalysis.CSharp.Testing; | ||
using Microsoft.CodeAnalysis.Testing; | ||
using Xunit; | ||
|
||
namespace Microsoft.NET.Sdk.Razor.SourceGenerators.Tests; | ||
|
||
public class DuplicateRazorFileIncludedAnalyzerTest | ||
{ | ||
[Theory] | ||
[InlineData("Duplicate.cshtml")] | ||
[InlineData("Duplicate.razor")] | ||
public async Task Analyzer_ReportsDiagnostic_WhenDuplicateRazorFileIsIncluded(string fileName) | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Consider adding a test for the razor source generator as well to see what the errors would be. I actually cannot reproduce any issues there. I've created a project which passes duplicate AdditionalFiles to Csc but don't see any errors from the razor source generator. What is needed to hit an error? |
||
{ | ||
// Arrange | ||
var test = new CSharpAnalyzerTest<DuplicateRazorFileIncludedAnalyzer, DefaultVerifier> | ||
{ | ||
TestState = | ||
{ | ||
Sources = | ||
{ | ||
// Need a non-empty source file to make the test helper happy | ||
("Test.cs", "public class Test {}"), | ||
}, | ||
AdditionalFiles = | ||
{ | ||
(fileName, "<h1>Duplicate</h1>"), | ||
(fileName, "<h1>Duplicate</h1>"), | ||
}, | ||
}, | ||
ExpectedDiagnostics = | ||
{ | ||
new DiagnosticResult(RazorDiagnostics.DuplicateRazorFileIncludedDescriptor.Id, DiagnosticSeverity.Error) | ||
.WithLocation(fileName, 1, 1) | ||
.WithMessageFormat(RazorDiagnostics.DuplicateRazorFileIncludedDescriptor.MessageFormat.ToString()) | ||
.WithArguments(fileName), | ||
}, | ||
}; | ||
|
||
// Act & Assert | ||
await test.RunAsync(); | ||
} | ||
|
||
[Theory] | ||
[InlineData("Duplicate.cshtml", "duplicate.cshtml")] | ||
[InlineData("Duplicate.razor", "duplicate.razor")] | ||
public async Task Analyzer_NoDiagnostic_WhenDuplicateRazorFileIsIncluded_DifferentCase(string fileName1, string fileName2) | ||
{ | ||
// Arrange | ||
var test = new CSharpAnalyzerTest<DuplicateRazorFileIncludedAnalyzer, DefaultVerifier> | ||
{ | ||
TestState = | ||
{ | ||
Sources = | ||
{ | ||
// Need a non-empty source file to make the test helper happy | ||
("Test.cs", "public class Test {}"), | ||
}, | ||
AdditionalFiles = | ||
{ | ||
(fileName1, "<h1>Duplicate</h1>"), | ||
(fileName2, "<h1>Duplicate</h1>"), | ||
}, | ||
}, | ||
ExpectedDiagnostics = | ||
{ | ||
}, | ||
}; | ||
|
||
// Act & Assert | ||
await test.RunAsync(); | ||
} | ||
|
||
[Theory] | ||
[InlineData("Duplicate.cshtml")] | ||
[InlineData("Duplicate.razor")] | ||
public async Task Analyzer_ReportsDiagnostic_WhenThreeDuplicateRazorFilesAreIncluded(string fileName) | ||
{ | ||
// Arrange | ||
var test = new CSharpAnalyzerTest<DuplicateRazorFileIncludedAnalyzer, DefaultVerifier> | ||
{ | ||
TestState = | ||
{ | ||
Sources = | ||
{ | ||
// Need a non-empty source file to make the test helper happy | ||
("Test.cs", "public class Test {}"), | ||
}, | ||
AdditionalFiles = | ||
{ | ||
(fileName, "<h1>Duplicate</h1>"), | ||
(fileName, "<h1>Duplicate</h1>"), | ||
(fileName, "<h1>Duplicate</h1>"), | ||
}, | ||
}, | ||
ExpectedDiagnostics = | ||
{ | ||
new DiagnosticResult(RazorDiagnostics.DuplicateRazorFileIncludedDescriptor.Id, DiagnosticSeverity.Error) | ||
.WithLocation(fileName, 1, 1) | ||
.WithMessageFormat(RazorDiagnostics.DuplicateRazorFileIncludedDescriptor.MessageFormat.ToString()) | ||
.WithArguments(fileName), | ||
new DiagnosticResult(RazorDiagnostics.DuplicateRazorFileIncludedDescriptor.Id, DiagnosticSeverity.Error) | ||
.WithLocation(fileName, 1, 1) | ||
.WithMessageFormat(RazorDiagnostics.DuplicateRazorFileIncludedDescriptor.MessageFormat.ToString()) | ||
.WithArguments(fileName), | ||
}, | ||
}; | ||
|
||
// Act & Assert | ||
await test.RunAsync(); | ||
} | ||
} | ||
|
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.
Note that these specific verifiers are deprecated. See https://github.com/dotnet/roslyn-sdk/tree/main/src/Microsoft.CodeAnalysis.Testing#obsolete-packages.