-
Notifications
You must be signed in to change notification settings - Fork 754
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
Metadata reports generator (Issue #3999) #5531
Open
IbrahimMNada
wants to merge
28
commits into
dotnet:main
Choose a base branch
from
IbrahimMNada:MetadataReportsGenerator
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.
Open
Changes from all commits
Commits
Show all changes
28 commits
Select commit
Hold shift + click to select a range
78e08b5
adding MetadataReportsGenerator
IbrahimMNada 51d6362
fix format
IbrahimMNada 37bf450
fix refs
IbrahimMNada 9f3cb7d
revert dotnet version
IbrahimMNada d448547
remove unneeded using spaces
IbrahimMNada 235aa18
remove un needed usings
IbrahimMNada 54b2eae
manual testing
IbrahimMNada 4581b20
adding test project
IbrahimMNada 2eadb5c
fix order for tests
IbrahimMNada 34a9f7e
adding test classes
IbrahimMNada 12f8a24
extra testing class
IbrahimMNada fff7be2
adding test methods
IbrahimMNada a9bf590
methods
IbrahimMNada 6709e78
adding testng methods
IbrahimMNada b72031d
adding tests
IbrahimMNada e315855
finshing tests
IbrahimMNada 0e63552
remove duplication
IbrahimMNada ff82288
multi blanlines removed
IbrahimMNada bfbab5b
fixing format
IbrahimMNada 7a6abb6
add comments
IbrahimMNada 197bdb9
adding comment for methods
IbrahimMNada b08ad67
remove multi lines
IbrahimMNada da8a021
run tests & adding comments
IbrahimMNada 61d7767
adding comments
IbrahimMNada 5c5f2e3
remove blanks
IbrahimMNada 8384771
Merge branch 'main' into MetadataReportsGenerator
IbrahimMNada 8bfcefa
Merge branch 'main' into MetadataReportsGenerator
IbrahimMNada cbca87e
Merge branch 'main' into MetadataReportsGenerator
IbrahimMNada 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 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
162 changes: 162 additions & 0 deletions
162
src/Generators/Microsoft.Gen.MetadataExtractor/MetadataReportsGenerator.cs
This file contains 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,162 @@ | ||
// Licensed to the .NET Foundation under one or more agreements. | ||
// The .NET Foundation licenses this file to you under the MIT license. | ||
|
||
using System.Globalization; | ||
using System.IO; | ||
using System.Text; | ||
using Microsoft.CodeAnalysis; | ||
using Microsoft.Gen.ComplianceReports; | ||
using Microsoft.Gen.MetricsReports; | ||
using Microsoft.Gen.Shared; | ||
using Microsoft.Shared.DiagnosticIds; | ||
|
||
namespace Microsoft.Gen.MetadataExtractor; | ||
|
||
/// <summary> | ||
/// Generates reports for compliance & metrics annotations. | ||
/// </summary> | ||
[Generator] | ||
public sealed class MetadataReportsGenerator : ISourceGenerator | ||
{ | ||
private const string GenerateMetadataMSBuildProperty = "build_property.GenerateMetadataReport"; | ||
private const string ReportOutputPathMSBuildProperty = "build_property.MetadataReportOutputPath"; | ||
private const string RootNamespace = "build_property.rootnamespace"; | ||
private const string FallbackFileName = "MetadataReport.json"; | ||
private readonly string _fileName; | ||
|
||
/// <summary> | ||
/// Initializes a new instance of the <see cref="MetadataReportsGenerator"/> class. | ||
/// </summary> | ||
public MetadataReportsGenerator() | ||
: this(FallbackFileName) | ||
{ | ||
} | ||
|
||
/// <summary> | ||
/// Initializes a new instance of the <see cref="MetadataReportsGenerator"/> class. | ||
/// </summary> | ||
/// <param name="reportFileName">The report file name.</param> | ||
public MetadataReportsGenerator(string reportFileName) | ||
{ | ||
_fileName = reportFileName; | ||
} | ||
|
||
/// <summary> | ||
/// Initializes the generator. | ||
/// </summary> | ||
/// <param name="context">The generator initialization context.</param> | ||
public void Initialize(GeneratorInitializationContext context) | ||
{ | ||
context.RegisterForSyntaxNotifications(TypeDeclarationSyntaxReceiver.Create); | ||
} | ||
|
||
/// <summary> | ||
/// Generates reports for compliance & metrics annotations. | ||
/// </summary> | ||
/// <param name="context">The generator execution context.</param> | ||
public void Execute(GeneratorExecutionContext context) | ||
{ | ||
context.CancellationToken.ThrowIfCancellationRequested(); | ||
|
||
if (context.SyntaxReceiver is not TypeDeclarationSyntaxReceiver || | ||
((TypeDeclarationSyntaxReceiver)context.SyntaxReceiver).TypeDeclarations.Count == 0 || | ||
!GeneratorUtilities.ShouldGenerateReport(context, GenerateMetadataMSBuildProperty)) | ||
{ | ||
return; | ||
} | ||
|
||
if ((context.SyntaxReceiver is not TypeDeclarationSyntaxReceiver || ((TypeDeclarationSyntaxReceiver)context.SyntaxReceiver).TypeDeclarations.Count == 0)) | ||
{ | ||
// nothing to do yet | ||
return; | ||
} | ||
|
||
var options = context.AnalyzerConfigOptions.GlobalOptions; | ||
var path = GeneratorUtilities.TryRetrieveOptionsValue(options, ReportOutputPathMSBuildProperty, out var reportOutputPath) | ||
? reportOutputPath! | ||
: GeneratorUtilities.GetDefaultReportOutputPath(options); | ||
if (string.IsNullOrWhiteSpace(path)) | ||
{ | ||
// Report diagnostic: | ||
var diagnostic = new DiagnosticDescriptor( | ||
DiagnosticIds.AuditReports.AUDREPGEN000, | ||
"MetricsReports generator couldn't resolve output path for the report. It won't be generated.", | ||
"Both <MetadataReportOutputPath> and <OutputPath> MSBuild properties are not set. The report won't be generated.", | ||
nameof(DiagnosticIds.AuditReports), | ||
DiagnosticSeverity.Info, | ||
isEnabledByDefault: true, | ||
helpLinkUri: string.Format(CultureInfo.InvariantCulture, DiagnosticIds.UrlFormat, DiagnosticIds.AuditReports.AUDREPGEN000)); | ||
|
||
context.ReportDiagnostic(Diagnostic.Create(diagnostic, location: null)); | ||
return; | ||
} | ||
|
||
(string metricReport, string complianceReport) metadataReport = (string.Empty, string.Empty); | ||
metadataReport.metricReport = HandleMetricReportGeneration(context, (TypeDeclarationSyntaxReceiver)context.SyntaxReceiver); | ||
metadataReport.complianceReport = HandleComplianceReportGeneration(context, (TypeDeclarationSyntaxReceiver)context.SyntaxReceiver); | ||
|
||
StringBuilder reportStringBuilder = new StringBuilder() | ||
.Append("{ \"Name\": \"") | ||
.Append(context.Compilation.AssemblyName!) | ||
.Append("\", \"ComplianceReport\": ") | ||
.Append((string.IsNullOrEmpty(metadataReport.complianceReport) ? "{}" : metadataReport.complianceReport)) | ||
.Append(" ,") | ||
.Append(" \"MetricReport\": ") | ||
.Append((string.IsNullOrEmpty(metadataReport.metricReport) ? "[]" : metadataReport.metricReport) + " }"); | ||
|
||
#pragma warning disable RS1035 // Do not use APIs banned for analyzers | ||
File.WriteAllText(Path.Combine(path, _fileName), reportStringBuilder.ToString(), Encoding.UTF8); | ||
#pragma warning restore RS1035 // Do not use APIs banned for analyzers | ||
|
||
} | ||
|
||
/// <summary> | ||
/// used to generate the report for metrics annotations. | ||
/// </summary> | ||
/// <param name="context">The generator execution context.</param> | ||
/// <param name="receiver">The typeDeclaration syntax receiver.</param> | ||
/// <returns>string report as json or String.Empty.</returns> | ||
private static string HandleMetricReportGeneration(GeneratorExecutionContext context, TypeDeclarationSyntaxReceiver receiver) | ||
{ | ||
var meteringParser = new Metrics.Parser(context.Compilation, context.ReportDiagnostic, context.CancellationToken); | ||
var meteringClasses = meteringParser.GetMetricClasses(receiver.TypeDeclarations); | ||
|
||
if (meteringClasses.Count == 0) | ||
{ | ||
return string.Empty; | ||
} | ||
|
||
_ = context.AnalyzerConfigOptions.GlobalOptions.TryGetValue(RootNamespace, out var rootNamespace); | ||
var reportedMetrics = MetricsReportsHelpers.MapToCommonModel(meteringClasses, rootNamespace); | ||
var emitter = new MetricDefinitionEmitter(); | ||
var report = emitter.GenerateReport(reportedMetrics, context.CancellationToken); | ||
return report; | ||
} | ||
|
||
/// <summary> | ||
/// used to generate the report for compliance annotations. | ||
/// </summary> | ||
/// <param name="context">The generator execution context.</param> | ||
/// <param name="receiver">The type declaration syntax receiver.</param> | ||
/// <returns>string report as json or String.Empty.</returns> | ||
private static string HandleComplianceReportGeneration(GeneratorExecutionContext context, TypeDeclarationSyntaxReceiver receiver) | ||
{ | ||
if (!SymbolLoader.TryLoad(context.Compilation, out var symbolHolder)) | ||
{ | ||
return string.Empty; | ||
} | ||
|
||
var parser = new Parser(context.Compilation, symbolHolder!, context.CancellationToken); | ||
var classifiedTypes = parser.GetClassifiedTypes(receiver.TypeDeclarations); | ||
if (classifiedTypes.Count == 0) | ||
{ | ||
// nothing to do | ||
return string.Empty; | ||
} | ||
|
||
var emitter = new Emitter(); | ||
string report = emitter.Emit(classifiedTypes, context.Compilation.AssemblyName!, false); | ||
|
||
return report; | ||
} | ||
} |
57 changes: 57 additions & 0 deletions
57
src/Generators/Microsoft.Gen.MetadataExtractor/Microsoft.Gen.MetadataExtractor.csproj
This file contains 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,57 @@ | ||
<Project Sdk="Microsoft.NET.Sdk"> | ||
<PropertyGroup> | ||
<RootNamespace>Microsoft.Gen.MetadataExtractor</RootNamespace> | ||
<Description>Produces compliance and metrics reports based on data classification annotations in the code.</Description> | ||
<Workstream>Fundamentals</Workstream> | ||
</PropertyGroup> | ||
|
||
<PropertyGroup> | ||
<AnalyzerLanguage>cs</AnalyzerLanguage> | ||
<EnforceExtendedAnalyzerRules>true</EnforceExtendedAnalyzerRules> | ||
<InjectIsExternalInitOnLegacy>true</InjectIsExternalInitOnLegacy> | ||
</PropertyGroup> | ||
|
||
<PropertyGroup> | ||
<Stage>normal</Stage> | ||
<MinCodeCoverage>98</MinCodeCoverage> | ||
<MinMutationScore>85</MinMutationScore> | ||
</PropertyGroup> | ||
|
||
<ItemGroup> | ||
<Compile Include="..\Shared\TypeDeclarationSyntaxReceiver.cs" LinkBase="Shared" /> | ||
<Compile Include="..\Shared\GeneratorUtilities.cs" LinkBase="Shared" /> | ||
<Compile Include="..\Shared\ClassDeclarationSyntaxReceiver.cs" LinkBase="Shared" /> | ||
<Compile Include="..\Shared\EmitterBase.cs" LinkBase="Shared" /> | ||
<Compile Include="..\Shared\ParserUtilities.cs" LinkBase="Shared" /> | ||
<Compile Include="..\Shared\DiagDescriptorsBase.cs" LinkBase="Shared" /> | ||
<Compile Include="..\Shared\StringBuilderPool.cs" LinkBase="Shared" /> | ||
<Compile Include="..\Microsoft.Gen.ComplianceReports\Model\*.cs" LinkBase="Microsoft.Gen.ComplianceReports" /> | ||
<Compile Include="..\Microsoft.Gen.ComplianceReports\*.cs" LinkBase="Microsoft.Gen.ComplianceReports" /> | ||
<Compile Include="..\Microsoft.Gen.Metrics\Exceptions\*.cs" LinkBase="Microsoft.Gen.Metrics" /> | ||
<Compile Include="..\Microsoft.Gen.MetricsReports\*.cs" LinkBase="Microsoft.Gen.MetricsReports" /> | ||
<Compile Include="..\Microsoft.Gen.Metrics\Model\*.cs" LinkBase="Microsoft.Gen.Metrics" /> | ||
<Compile Include="..\Microsoft.Gen.Metrics\*.cs" LinkBase="Microsoft.Gen.Metrics" /> | ||
<Compile Include="..\Microsoft.Gen.Shared\*.cs" LinkBase="Microsoft.Gen.Metrics" /> | ||
<Compile Include="..\Microsoft.Gen.Shared\*.cs" LinkBase="Microsoft.Gen.Metrics" /> | ||
|
||
|
||
|
||
</ItemGroup> | ||
|
||
<ItemGroup> | ||
<AnalyzerReference Include="..\..\Generators\Microsoft.Gen.ComplianceReports\Microsoft.Gen.ComplianceReports.csproj" /> | ||
<AnalyzerReference Include="..\..\Generators\Microsoft.Gen.MetricsReports\Microsoft.Gen.MetricsReports.csproj" /> | ||
</ItemGroup> | ||
|
||
<ItemGroup> | ||
<PackageReference Include="Microsoft.CodeAnalysis.CSharp.Workspaces" PrivateAssets="all" /> | ||
<PackageReference Include="Microsoft.CodeAnalysis" /> | ||
</ItemGroup> | ||
|
||
<ItemGroup> | ||
<ProjectReference Include="..\Microsoft.Gen.Metrics\Microsoft.Gen.Metrics.csproj" /> | ||
</ItemGroup> | ||
<ItemGroup> | ||
<InternalsVisibleToTest Include="Microsoft.Gen.MetadataExtractor.Unit.Tests" /> | ||
</ItemGroup> | ||
</Project> |
This file contains 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
29 changes: 29 additions & 0 deletions
29
src/Generators/Microsoft.Gen.MetricsReports/MetricsReportsHelpers.cs
This file contains 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,29 @@ | ||
// Licensed to the .NET Foundation under one or more agreements. | ||
// The .NET Foundation licenses this file to you under the MIT license. | ||
|
||
using System.Collections.Generic; | ||
using System.Linq; | ||
using Microsoft.Gen.Metrics.Model; | ||
|
||
namespace Microsoft.Gen.MetricsReports; | ||
internal static class MetricsReportsHelpers | ||
{ | ||
internal static ReportedMetricClass[] MapToCommonModel(IReadOnlyList<MetricType> meteringClasses, string? rootNamespace) | ||
{ | ||
var reportedMetrics = meteringClasses | ||
.Select(meteringClass => new ReportedMetricClass( | ||
Name: meteringClass.Name, | ||
RootNamespace: rootNamespace ?? meteringClass.Namespace, | ||
Constraints: meteringClass.Constraints, | ||
Modifiers: meteringClass.Modifiers, | ||
Methods: meteringClass.Methods.Select(meteringMethod => new ReportedMetricMethod( | ||
MetricName: meteringMethod.MetricName ?? "(Missing Name)", | ||
Summary: meteringMethod.XmlDefinition ?? "(Missing Summary)", | ||
Kind: meteringMethod.InstrumentKind, | ||
Dimensions: meteringMethod.TagKeys, | ||
DimensionsDescriptions: meteringMethod.TagDescriptionDictionary)) | ||
.ToArray())); | ||
|
||
return reportedMetrics.ToArray(); | ||
} | ||
} |
This file contains 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.
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.
This is added because you have a new reported dependent on this , and Compliance report is only a part of that bigger report, which have the assemblyName at the very top of it.
so we dont need to replicate the assemblyName in the properties.
The value is defaulted to true, to avoid any breaking changes for backward computability