-
Notifications
You must be signed in to change notification settings - Fork 839
Add AmbientMetadata.Build component #6623
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
evgenyfedorov2
wants to merge
18
commits into
dotnet:main
Choose a base branch
from
evgenyfedorov2:users/evgenyfedorov2/add_build_metadata
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,485
−0
Open
Changes from all commits
Commits
Show all changes
18 commits
Select commit
Hold shift + click to select a range
812bd52
initial commit
evgenyfedorov2 3e81442
Fix warnings
evgenyfedorov2 59cc400
Merge branch 'main' into users/evgenyfedorov2/add_build_metadata
evgenyfedorov2 c89c277
Fix class name
evgenyfedorov2 524df26
Merge branch 'users/evgenyfedorov2/add_build_metadata' of https://git…
evgenyfedorov2 4172707
Remove obsolete code
e0b0fc8
Remove BuildDateTime
evgenyfedorov2 5f441d4
Remove empty json file
evgenyfedorov2 4d5a8ff
Use MSBuild properties
evgenyfedorov2 82c2dce
fix tests
evgenyfedorov2 047920f
Working version
evgenyfedorov2 e90c5b9
Update test/Libraries/Microsoft.Extensions.AmbientMetadata.Build.Test…
evgenyfedorov2 7ed6565
PR Comments
evgenyfedorov2 03c247d
PR Comments
evgenyfedorov2 3c07154
Merge branch 'main' into users/evgenyfedorov2/add_build_metadata
evgenyfedorov2 520b267
PR comments
evgenyfedorov2 9dd9936
Merge branch 'users/evgenyfedorov2/add_build_metadata' of https://git…
evgenyfedorov2 c7a1f22
PR comments
evgenyfedorov2 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
39 changes: 39 additions & 0 deletions
39
src/Generators/Microsoft.Gen.BuildMetadata/AnalyzerConfigOptionsExtensions.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,39 @@ | ||
// Licensed to the .NET Foundation under one or more agreements. | ||
// The .NET Foundation licenses this file to you under the MIT license. | ||
|
||
using Microsoft.CodeAnalysis.Diagnostics; | ||
|
||
namespace Microsoft.Gen.BuildMetadata; | ||
|
||
/// <summary> | ||
/// Extension methods for <see cref="AnalyzerConfigOptions"/> to simplify MSBuild property access. | ||
/// </summary> | ||
internal static class AnalyzerConfigOptionsExtensions | ||
{ | ||
private const string PropertyPrefix = "build_property."; | ||
|
||
/// <summary> | ||
/// Gets a boolean property value from MSBuild properties. | ||
/// Supports "true"/"false" values (case-insensitive). | ||
/// </summary> | ||
/// <param name="options">The analyzer configuration options.</param> | ||
/// <param name="propertyName">The property name (without "build_property." prefix).</param> | ||
/// <returns>True if the property value is "true", false otherwise.</returns> | ||
public static bool GetBooleanProperty(this AnalyzerConfigOptions options, string propertyName) | ||
{ | ||
var value = GetProperty(options, propertyName); | ||
return string.Equals(value, "true", System.StringComparison.OrdinalIgnoreCase); | ||
} | ||
|
||
/// <summary> | ||
/// Gets a string property value from MSBuild properties. | ||
/// </summary> | ||
/// <param name="options">The analyzer configuration options.</param> | ||
/// <param name="propertyName">The property name (without "build_property." prefix).</param> | ||
/// <returns>The property value, or null if not found.</returns> | ||
public static string? GetProperty(this AnalyzerConfigOptions options, string propertyName) | ||
{ | ||
var key = string.Concat(PropertyPrefix, propertyName); | ||
return options.TryGetValue(key, out var value) ? value : 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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,6 @@ | ||
// Licensed to the .NET Foundation under one or more agreements. | ||
// The .NET Foundation licenses this file to you under the MIT license. | ||
|
||
namespace Microsoft.Gen.BuildMetadata; | ||
|
||
internal readonly record struct BuildMetadata(string? BuildId, string? BuildNumber, string? SourceBranchName, string? SourceVersion); |
57 changes: 57 additions & 0 deletions
57
src/Generators/Microsoft.Gen.BuildMetadata/BuildMetadataGenerator.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,57 @@ | ||
// Licensed to the .NET Foundation under one or more agreements. | ||
// The .NET Foundation licenses this file to you under the MIT license. | ||
|
||
using System.Text; | ||
using Microsoft.CodeAnalysis; | ||
using Microsoft.CodeAnalysis.Diagnostics; | ||
using Microsoft.CodeAnalysis.Text; | ||
|
||
namespace Microsoft.Gen.BuildMetadata; | ||
|
||
/// <summary> | ||
/// Source generator that creates build metadata extensions from MSBuild properties. | ||
/// Supports both Azure DevOps and GitHub Actions build environments. | ||
/// </summary> | ||
[Generator] | ||
public sealed class BuildMetadataGenerator : IIncrementalGenerator | ||
{ | ||
/// <inheritdoc/> | ||
public void Initialize(IncrementalGeneratorInitializationContext context) | ||
{ | ||
var buildPropertiesPipeline = context.AnalyzerConfigOptionsProvider.Select((provider, ct) => | ||
{ | ||
return CreateBuildMetadata(provider.GlobalOptions); | ||
}); | ||
|
||
context.RegisterSourceOutput(buildPropertiesPipeline, Execute); | ||
} | ||
|
||
private static BuildMetadata CreateBuildMetadata(AnalyzerConfigOptions globalOptions) | ||
{ | ||
// Azure DevOps properties | ||
var azureBuildId = globalOptions.GetProperty("BuildMetadataAzureBuildId"); | ||
var azureBuildNumber = globalOptions.GetProperty("BuildMetadataAzureBuildNumber"); | ||
var azureSourceBranchName = globalOptions.GetProperty("BuildMetadataAzureSourceBranchName"); | ||
var azureSourceVersion = globalOptions.GetProperty("BuildMetadataAzureSourceVersion"); | ||
var isAzureDevOps = globalOptions.GetBooleanProperty("BuildMetadataIsAzureDevOps"); | ||
|
||
// GitHub Actions properties | ||
var gitHubRunId = globalOptions.GetProperty("BuildMetadataGitHubRunId"); | ||
var gitHubRunNumber = globalOptions.GetProperty("BuildMetadataGitHubRunNumber"); | ||
var gitHubRefName = globalOptions.GetProperty("BuildMetadataGitHubRefName"); | ||
var gitHubSha = globalOptions.GetProperty("BuildMetadataGitHubSha"); | ||
|
||
return new BuildMetadata( | ||
isAzureDevOps ? azureBuildId : gitHubRunId, | ||
isAzureDevOps ? azureBuildNumber : gitHubRunNumber, | ||
isAzureDevOps ? azureSourceBranchName : gitHubRefName, | ||
isAzureDevOps ? azureSourceVersion : gitHubSha); | ||
} | ||
|
||
private static void Execute(SourceProductionContext context, BuildMetadata buildMetadata) | ||
{ | ||
var emitter = new Emitter(buildMetadata); | ||
var result = emitter.Emit(); | ||
context.AddSource("BuildMetadataExtensions.g.cs", SourceText.From(result, Encoding.UTF8)); | ||
} | ||
} |
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,184 @@ | ||
// Licensed to the .NET Foundation under one or more agreements. | ||
// The .NET Foundation licenses this file to you under the MIT license. | ||
|
||
using System.Diagnostics.CodeAnalysis; | ||
using Microsoft.Gen.Shared; | ||
|
||
namespace Microsoft.Gen.BuildMetadata; | ||
|
||
[SuppressMessage("Format", "S1199", Justification = "For better visualization of how the generated code will look like.")] | ||
internal sealed class Emitter : EmitterBase | ||
evgenyfedorov2 marked this conversation as resolved.
Show resolved
Hide resolved
|
||
{ | ||
private const string DependencyInjectionNamespace = "global::Microsoft.Extensions.DependencyInjection."; | ||
private const string ConfigurationNamespace = "global::Microsoft.Extensions.Configuration."; | ||
private const string HostingNamespace = "global::Microsoft.Extensions.Hosting."; | ||
private readonly string? _buildId; | ||
private readonly string? _buildNumber; | ||
private readonly string? _sourceBranchName; | ||
private readonly string? _sourceVersion; | ||
|
||
public Emitter(BuildMetadata buildMetadata) | ||
{ | ||
_buildId = buildMetadata.BuildId; | ||
_buildNumber = buildMetadata.BuildNumber; | ||
_sourceBranchName = buildMetadata.SourceBranchName; | ||
_sourceVersion = buildMetadata.SourceVersion; | ||
} | ||
|
||
public string Emit() | ||
{ | ||
GenerateBuildMetadataExtensions(); | ||
return Capture(); | ||
} | ||
|
||
private void GenerateBuildMetadataSource() | ||
{ | ||
OutGeneratedCodeAttribute(); | ||
OutLn("[global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)]"); | ||
OutLn($"private sealed class BuildMetadataSource : {ConfigurationNamespace}IConfigurationSource"); | ||
OutOpenBrace(); | ||
{ | ||
OutLn("public string SectionName { get; }"); | ||
OutLn(); | ||
|
||
OutLn("public BuildMetadataSource(string sectionName)"); | ||
OutOpenBrace(); | ||
{ | ||
OutNullGuards(checkBuilder: false); | ||
OutLn("SectionName = sectionName;"); | ||
} | ||
|
||
OutCloseBrace(); | ||
OutLn(); | ||
OutLn($"public {ConfigurationNamespace}IConfigurationProvider Build({ConfigurationNamespace}IConfigurationBuilder builder)"); | ||
OutOpenBrace(); | ||
{ | ||
OutLn($"return new {ConfigurationNamespace}Memory.MemoryConfigurationProvider(new {ConfigurationNamespace}Memory.MemoryConfigurationSource())"); | ||
OutOpenBrace(); | ||
{ | ||
OutLn($$"""{ $"{SectionName}:buildid", "{{_buildId}}" },"""); | ||
OutLn($$"""{ $"{SectionName}:buildnumber", "{{_buildNumber}}" },"""); | ||
OutLn($$"""{ $"{SectionName}:sourcebranchname", "{{_sourceBranchName}}" },"""); | ||
OutLn($$"""{ $"{SectionName}:sourceversion", "{{_sourceVersion}}" },"""); | ||
} | ||
|
||
OutCloseBraceWithExtra(";"); | ||
} | ||
|
||
OutCloseBrace(); | ||
} | ||
|
||
OutCloseBrace(); | ||
} | ||
|
||
private void GenerateBuildMetadataExtensions() | ||
{ | ||
OutLn("namespace Microsoft.Extensions.AmbientMetadata"); | ||
OutOpenBrace(); | ||
{ | ||
OutGeneratedCodeAttribute(); | ||
OutLn("internal static class BuildMetadataGeneratedExtensions"); | ||
OutOpenBrace(); | ||
{ | ||
OutLn("private const string DefaultSectionName = \"ambientmetadata:build\";"); | ||
OutLn(); | ||
|
||
GenerateBuildMetadataSource(); | ||
OutLn(); | ||
|
||
OutLn($"public static {HostingNamespace}IHostBuilder UseBuildMetadata(this {HostingNamespace}IHostBuilder builder, string sectionName = DefaultSectionName)"); | ||
OutOpenBrace(); | ||
{ | ||
OutNullGuards(); | ||
OutLn("_ = builder.ConfigureHostConfiguration(configBuilder => configBuilder.AddBuildMetadata(sectionName))"); | ||
Indent(); | ||
OutLn(".ConfigureServices((hostBuilderContext, serviceCollection) =>"); | ||
Indent(); | ||
OutLn($"{DependencyInjectionNamespace}BuildMetadataServiceCollectionExtensions.AddBuildMetadata(serviceCollection, hostBuilderContext.Configuration.GetSection(sectionName)));"); | ||
Unindent(); | ||
Unindent(); | ||
OutLn(); | ||
|
||
OutLn("return builder;"); | ||
} | ||
|
||
OutCloseBrace(); | ||
OutLn(); | ||
|
||
OutLn("public static TBuilder UseBuildMetadata<TBuilder>(this TBuilder builder, string sectionName = DefaultSectionName)"); | ||
Indent(); | ||
OutLn($"where TBuilder : {HostingNamespace}IHostApplicationBuilder"); | ||
Unindent(); | ||
OutOpenBrace(); | ||
{ | ||
OutNullGuards(); | ||
OutLn("_ = builder.Configuration.AddBuildMetadata(sectionName);"); | ||
OutLn($"{DependencyInjectionNamespace}BuildMetadataServiceCollectionExtensions.AddBuildMetadata(builder.Services, builder.Configuration.GetSection(sectionName));"); | ||
OutLn(); | ||
|
||
OutLn("return builder;"); | ||
} | ||
|
||
OutCloseBrace(); | ||
OutLn(); | ||
|
||
#pragma warning disable S103 // Lines should not be too long | ||
OutLn($"public static {ConfigurationNamespace}IConfigurationBuilder AddBuildMetadata(this {ConfigurationNamespace}IConfigurationBuilder builder, string sectionName = DefaultSectionName)"); | ||
#pragma warning restore S103 // Lines should not be too long | ||
evgenyfedorov2 marked this conversation as resolved.
Show resolved
Hide resolved
|
||
OutOpenBrace(); | ||
{ | ||
OutNullGuards(); | ||
OutLn("return builder.Add(new BuildMetadataSource(sectionName));"); | ||
} | ||
|
||
OutCloseBrace(); | ||
} | ||
|
||
OutCloseBrace(); | ||
} | ||
|
||
OutCloseBrace(); | ||
} | ||
|
||
private void OutNullGuards(bool checkBuilder = true) | ||
{ | ||
OutPP("#if !NET"); | ||
|
||
if (checkBuilder) | ||
{ | ||
OutLn("if (builder is null)"); | ||
OutOpenBrace(); | ||
OutLn("throw new global::System.ArgumentNullException(nameof(builder));"); | ||
OutCloseBrace(); | ||
OutLn(); | ||
} | ||
|
||
OutLn("if (string.IsNullOrWhiteSpace(sectionName))"); | ||
OutOpenBrace(); | ||
{ | ||
OutLn("if (sectionName is null)"); | ||
OutOpenBrace(); | ||
{ | ||
OutLn("throw new global::System.ArgumentNullException(nameof(sectionName));"); | ||
} | ||
|
||
OutCloseBrace(); | ||
OutLn(); | ||
OutLn("throw new global::System.ArgumentException(\"The value cannot be an empty string or composed entirely of whitespace.\", nameof(sectionName));"); | ||
} | ||
|
||
OutCloseBrace(); | ||
|
||
OutPP("#else"); | ||
|
||
if (checkBuilder) | ||
{ | ||
OutLn("global::System.ArgumentNullException.ThrowIfNull(builder);"); | ||
} | ||
|
||
OutLn("global::System.ArgumentException.ThrowIfNullOrWhiteSpace(sectionName);"); | ||
|
||
OutPP("#endif"); | ||
OutLn(); | ||
} | ||
} |
37 changes: 37 additions & 0 deletions
37
src/Generators/Microsoft.Gen.BuildMetadata/Microsoft.Gen.BuildMetadata.csproj
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,37 @@ | ||
<Project Sdk="Microsoft.NET.Sdk"> | ||
<PropertyGroup> | ||
<RootNamespace>Microsoft.Gen.BuildMetadata</RootNamespace> | ||
<Description>Code generator to support Microsoft.Extensions.AmbientMetadata.Build</Description> | ||
<Workstream>Fundamentals</Workstream> | ||
</PropertyGroup> | ||
|
||
<PropertyGroup> | ||
<AnalyzerLanguage>cs</AnalyzerLanguage> | ||
<EnforceExtendedAnalyzerRules>true</EnforceExtendedAnalyzerRules> | ||
<InjectExperimentalAttributeOnLegacy>true</InjectExperimentalAttributeOnLegacy> | ||
<InjectSharedDiagnosticIds>true</InjectSharedDiagnosticIds> | ||
<InjectIsExternalInitOnLegacy>true</InjectIsExternalInitOnLegacy> | ||
<!-- CA1852 is for the internal shared type DiagDescriptorsBase. It can't be sealed because there are child classes in other components--> | ||
<NoWarn>$(NoWarn);EA0002;CA1852</NoWarn> | ||
</PropertyGroup> | ||
|
||
<PropertyGroup> | ||
<Stage>normal</Stage> | ||
<MinCodeCoverage>100</MinCodeCoverage> | ||
<MinMutationScore>75</MinMutationScore> | ||
</PropertyGroup> | ||
|
||
<ItemGroup> | ||
<PackageReference Include="Microsoft.CodeAnalysis.CSharp" PrivateAssets="all" /> | ||
</ItemGroup> | ||
|
||
<ItemGroup> | ||
<Compile Update="Parsing\Resources.Designer.cs" DesignTime="True" AutoGen="True" DependentUpon="Resources.resx" /> | ||
<Compile Include="..\Shared\*.cs" LinkBase="Shared" /> | ||
</ItemGroup> | ||
<ItemGroup> | ||
<InternalsVisibleToTest Include="Microsoft.Gen.BuildMetadata.Generated.Tests" /> | ||
<InternalsVisibleToTest Include="Microsoft.Gen.BuildMetadata.Unit.Tests" /> | ||
</ItemGroup> | ||
|
||
</Project> |
39 changes: 39 additions & 0 deletions
39
src/Libraries/Microsoft.Extensions.AmbientMetadata.Build/BuildMetadata.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,39 @@ | ||
// Licensed to the .NET Foundation under one or more agreements. | ||
// The .NET Foundation licenses this file to you under the MIT license. | ||
|
||
namespace Microsoft.Extensions.AmbientMetadata; | ||
|
||
/// <summary> | ||
/// Data model for the Build metadata. | ||
/// </summary> | ||
/// <remarks> | ||
/// The values are automatically grabbed from environment variables at build time in CI pipeline and saved in generated code. | ||
/// At startup time, the class properties will be initialized from the generated code. | ||
/// Currently supported CI pipelines: | ||
/// <list type="bullet"> | ||
/// <item><see href="https://learn.microsoft.com/azure/devops/pipelines/build/variables#build-variables-devops-services">Azure DevOps</see></item> | ||
/// <item><see href="https://docs.github.com/en/actions/reference/variables-reference#default-environment-variables">GitHub Actions</see></item> | ||
/// </list> | ||
/// </remarks> | ||
public class BuildMetadata | ||
{ | ||
/// <summary> | ||
/// Gets or sets the ID of the record for the build, also known as the run ID. | ||
/// </summary> | ||
public string? BuildId { get; set; } | ||
|
||
/// <summary> | ||
/// Gets or sets the name of the completed build, also known as the run number. | ||
/// </summary> | ||
public string? BuildNumber { get; set; } | ||
|
||
/// <summary> | ||
/// Gets or sets the name of the branch in the triggering repo the build was queued for, also known as the ref name. | ||
/// </summary> | ||
public string? SourceBranchName { get; set; } | ||
|
||
/// <summary> | ||
/// Gets or sets the latest version control change that is included in this build, also known as the commit SHA. | ||
/// </summary> | ||
public string? SourceVersion { get; set; } | ||
} |
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.
Is this suppression still needed? (I'm not sure what S1199 is about actually)
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.
It is a Sonar rule https://sonarqube.inria.fr/sonarqube/coding_rules?open=csharpsquid%3AS1199&rule_key=csharpsquid%3AS1199, kicks in because we have extra curly braces