-
Notifications
You must be signed in to change notification settings - Fork 840
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
base: main
Are you sure you want to change the base?
Changes from 2 commits
812bd52
3e81442
59cc400
c89c277
524df26
4172707
e0b0fc8
5f441d4
4d5a8ff
82c2dce
047920f
e90c5b9
7ed6565
03c247d
3c07154
520b267
9dd9936
c7a1f22
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,75 @@ | ||
| // 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.Immutable; | ||
| using System.Text; | ||
| using Microsoft.CodeAnalysis; | ||
| using Microsoft.CodeAnalysis.Text; | ||
|
|
||
| namespace Microsoft.Gen.BuildMetadata; | ||
|
|
||
| [Generator] | ||
| public class BuildMetadataGenerator : IIncrementalGenerator | ||
| { | ||
| private static DateTimeOffset _initializeDateTime = DateTimeOffset.UtcNow; | ||
|
|
||
| /// <inheritdoc/> | ||
| public void Initialize(IncrementalGeneratorInitializationContext context) | ||
| { | ||
| context.RegisterSourceOutput(context.CompilationProvider, (spc, compilation) => Execute(compilation, spc)); | ||
| } | ||
|
|
||
| private static void Execute(Compilation compilation, SourceProductionContext context) | ||
| { | ||
| Model.BuildDateTime = _initializeDateTime; | ||
|
|
||
| OverwriteModelValuesForTesting(compilation.Assembly.GetAttributes()); | ||
|
|
||
| EnsureBackwardsCompatibility(context); | ||
|
|
||
| var e = new Emitter(); | ||
| var result = e.EmitExtensions(context.CancellationToken); | ||
| context.AddSource("BuildMetadataExtensions.g.cs", SourceText.From(result, Encoding.UTF8)); | ||
| } | ||
|
|
||
| private static void EnsureBackwardsCompatibility(SourceProductionContext context) | ||
| { | ||
| var e = new Emitter(); | ||
| var result = e.Emit(context.CancellationToken); | ||
| context.AddSource("BuildMetadataInitializer.g.cs", SourceText.From(result, Encoding.UTF8)); | ||
| } | ||
|
|
||
| private static void OverwriteModelValuesForTesting(ImmutableArray<AttributeData> attributes) | ||
| { | ||
| const int TestAttributeConstructorArgumentsLength = 5; | ||
|
|
||
| if (attributes.IsDefaultOrEmpty || attributes[0].ConstructorArguments.Length != TestAttributeConstructorArgumentsLength) | ||
evgenyfedorov2 marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
| { | ||
| return; | ||
| } | ||
|
|
||
| // internal attribute has five constructor args: | ||
| // buildId, buildNumber, sourceBranchName, sourceVersion, buildDateTime | ||
| var attribute = attributes[0]; | ||
|
|
||
| #pragma warning disable S109 // Magic numbers should not be used | ||
| #pragma warning disable S1067 // Expressions should not be too complex | ||
| if ( | ||
| attribute.ConstructorArguments[0].Value is string buildId && | ||
| attribute.ConstructorArguments[1].Value is string buildNumber && | ||
| attribute.ConstructorArguments[2].Value is string sourceBranchName && | ||
| attribute.ConstructorArguments[3].Value is string sourceVersion && | ||
| attribute.ConstructorArguments[4].Value is int buildDateTime) | ||
| { | ||
| Model.IsAzureDevOps = true; | ||
| Model.AzureBuildId = buildId; | ||
| Model.AzureBuildNumber = buildNumber; | ||
| Model.AzureSourceBranchName = sourceBranchName; | ||
| Model.AzureSourceVersion = sourceVersion; | ||
| Model.BuildDateTime = DateTimeOffset.FromUnixTimeSeconds(buildDateTime); | ||
| } | ||
| #pragma warning restore S1067 // Expressions should not be too complex | ||
| #pragma warning restore S109 // Magic numbers should not be used | ||
| } | ||
| } | ||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,178 @@ | ||
| // 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 System.Threading; | ||
| using Microsoft.Gen.Shared; | ||
|
|
||
| namespace Microsoft.Gen.BuildMetadata; | ||
|
|
||
| internal sealed class Emitter : EmitterBase | ||
evgenyfedorov2 marked this conversation as resolved.
Show resolved
Hide resolved
|
||
| { | ||
| public string Emit(CancellationToken cancellationToken) | ||
| { | ||
| cancellationToken.ThrowIfCancellationRequested(); | ||
| GenerateBuildMetadataInitializer(); | ||
| return Capture(); | ||
| } | ||
|
|
||
| public string EmitExtensions(CancellationToken cancellationToken) | ||
| { | ||
| cancellationToken.ThrowIfCancellationRequested(); | ||
evgenyfedorov2 marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
| GenerateBuildMetadataExtensions(); | ||
| return Capture(); | ||
| } | ||
|
|
||
| [SuppressMessage("Format", "IDE0055", Justification = "For better visualization of how the generated code will look like.")] | ||
| private void GenerateBuildMetadataInitializer() | ||
| { | ||
| OutLn($"namespace Microsoft.Extensions.AmbientMetadata"); | ||
| OutOpenBrace(); | ||
| OutGeneratedCodeAttribute(); | ||
| OutLn($"internal static class BuildMetadataInitializer"); | ||
| OutOpenBrace(); | ||
| OutLn($"public static BuildMetadata WithEnvironmentVariables()"); | ||
| OutOpenBrace(); | ||
| OutLn($"return new BuildMetadata"); | ||
| OutOpenBrace(); | ||
| OutLn($"BuildId = \"{Model.BuildId}\","); | ||
| OutLn($"BuildNumber = \"{Model.BuildNumber}\","); | ||
| OutLn($"SourceBranchName = \"{Model.SourceBranchName}\","); | ||
| OutLn($"SourceVersion = \"{Model.SourceVersion}\","); | ||
| OutLn($"BuildDateTime = \"{Model.BuildDateTime:s}\","); | ||
| OutCloseBraceWithExtra(";"); | ||
| OutCloseBrace(); | ||
| OutCloseBrace(); | ||
| OutCloseBrace(); | ||
| } | ||
|
|
||
| [SuppressMessage("Format", "IDE0055", Justification = "For better visualization of how the generated code will look like.")] | ||
| private void GenerateBuildMetadataSource() | ||
| { | ||
| OutGeneratedCodeAttribute(); | ||
| OutLn("[EditorBrowsable(EditorBrowsableState.Never)]"); | ||
evgenyfedorov2 marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
| OutLn("private sealed class BuildMetadataSource : IConfigurationSource"); | ||
| OutOpenBrace(); | ||
| OutLn("public string SectionName { get; }"); | ||
| OutLn(); | ||
|
|
||
| OutLn("public BuildMetadataSource(string sectionName)"); | ||
| OutOpenBrace(); | ||
| OutNullGuards(checkBuilder: false); | ||
| OutLn("SectionName = sectionName;"); | ||
| OutCloseBrace(); | ||
| OutLn(); | ||
|
|
||
| OutLn("public IConfigurationProvider Build(IConfigurationBuilder builder)"); | ||
| OutOpenBrace(); | ||
| OutLn("return new MemoryConfigurationProvider(new MemoryConfigurationSource())"); | ||
| OutOpenBrace(); | ||
| OutLn($$"""{ $"{SectionName}:buildid", "{{Model.BuildId}}" },"""); | ||
| OutLn($$"""{ $"{SectionName}:buildnumber", "{{Model.BuildNumber}}" },"""); | ||
| OutLn($$"""{ $"{SectionName}:sourcebranchname", "{{Model.SourceBranchName}}" },"""); | ||
| OutLn($$"""{ $"{SectionName}:sourceversion", "{{Model.SourceVersion}}" },"""); | ||
| OutLn($$"""{ $"{SectionName}:builddatetime", "{{Model.BuildDateTime:s}}" },"""); | ||
| OutCloseBraceWithExtra(";"); | ||
| OutCloseBrace(); | ||
| OutCloseBrace(); | ||
| } | ||
|
|
||
| [SuppressMessage("Format", "IDE0055", Justification = "For better visualization of how the generated code will look like.")] | ||
| private void GenerateBuildMetadataExtensions() | ||
| { | ||
| OutLn("namespace Microsoft.Extensions.AmbientMetadata"); | ||
| OutOpenBrace(); | ||
| OutLn("using System;"); | ||
| OutLn("using System.ComponentModel;"); | ||
| OutLn("using System.Diagnostics.CodeAnalysis;"); | ||
| OutLn("using Microsoft.Extensions.Configuration;"); | ||
| OutLn("using Microsoft.Extensions.Configuration.Memory;"); | ||
| OutLn("using Microsoft.Extensions.DependencyInjection;"); | ||
| OutLn("using Microsoft.Extensions.Hosting;"); | ||
| OutLn(); | ||
|
|
||
| OutGeneratedCodeAttribute(); | ||
| OutLn("internal static class BuildMetadataGeneratedExtensions"); | ||
| OutOpenBrace(); | ||
| OutLn("private const string DefaultSectionName = \"ambientmetadata:build\";"); | ||
| OutLn(); | ||
|
|
||
| GenerateBuildMetadataSource(); | ||
| OutLn(); | ||
|
|
||
| OutLn("public static IHostBuilder UseBuildMetadata(this IHostBuilder builder, string sectionName = DefaultSectionName)"); | ||
| OutOpenBrace(); | ||
| OutNullGuards(); | ||
| OutLn("_ = builder.ConfigureHostConfiguration(configBuilder => configBuilder.AddBuildMetadata(sectionName))"); | ||
| Indent(); | ||
| OutLn(".ConfigureServices((hostBuilderContext, serviceCollection) =>"); | ||
| Indent(); | ||
| OutLn("serviceCollection.AddBuildMetadata(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 : IHostApplicationBuilder"); | ||
| Unindent(); | ||
| OutOpenBrace(); | ||
| OutNullGuards(); | ||
| OutLn("_ = builder.Configuration.AddBuildMetadata(sectionName);"); | ||
| OutLn("_ = builder.Services.AddBuildMetadata(builder.Configuration.GetSection(sectionName));"); | ||
| OutLn(); | ||
|
|
||
| OutLn("return builder;"); | ||
| OutCloseBrace(); | ||
| OutLn(); | ||
|
|
||
| OutLn("public static IConfigurationBuilder AddBuildMetadata(this IConfigurationBuilder builder, string sectionName = DefaultSectionName)"); | ||
| OutOpenBrace(); | ||
| OutNullGuards(); | ||
| OutLn("return builder.Add(new BuildMetadataSource(sectionName));"); | ||
| OutCloseBrace(); | ||
| OutCloseBrace(); | ||
| OutCloseBrace(); | ||
| } | ||
|
|
||
| [SuppressMessage("Format", "IDE0055", Justification = "For better visualization of how the generated code will look like.")] | ||
| private void OutNullGuards(bool checkBuilder = true) | ||
| { | ||
| OutPP("#if NETFRAMEWORK"); | ||
evgenyfedorov2 marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
|
|
||
| if (checkBuilder) | ||
| { | ||
| OutLn("if (builder is null)"); | ||
| OutOpenBrace(); | ||
| OutLn("throw new ArgumentNullException(nameof(builder));"); | ||
| OutCloseBrace(); | ||
| OutLn(); | ||
| } | ||
|
|
||
| OutLn("if (string.IsNullOrWhiteSpace(sectionName))"); | ||
| OutOpenBrace(); | ||
| OutLn("if (sectionName is null)"); | ||
| OutOpenBrace(); | ||
| OutLn("throw new ArgumentNullException(nameof(sectionName));"); | ||
| OutCloseBrace(); | ||
| OutLn(); | ||
| OutLn("throw new ArgumentException(\"The value cannot be an empty string or composed entirely of whitespace.\", nameof(sectionName));"); | ||
| OutCloseBrace(); | ||
|
|
||
| OutPP("#else"); | ||
|
|
||
| if (checkBuilder) | ||
| { | ||
| OutLn("ArgumentNullException.ThrowIfNull(builder);"); | ||
| } | ||
|
|
||
| OutLn("ArgumentException.ThrowIfNullOrWhiteSpace(sectionName);"); | ||
|
|
||
| OutPP("#endif"); | ||
| OutLn(); | ||
| } | ||
| } | ||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,28 @@ | ||
| // 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.ComponentModel; | ||
| using System.Diagnostics.CodeAnalysis; | ||
|
|
||
| namespace Microsoft.Gen.BuildMetadata; | ||
|
|
||
| /// <summary> | ||
| /// Attribute used to verify build metadata in tests. | ||
| /// </summary> | ||
| /// <remarks> | ||
| /// It must be public for Roslyn SDK to be able to access it. | ||
| /// </remarks> | ||
| [ExcludeFromCodeCoverage] | ||
| [EditorBrowsable(EditorBrowsableState.Never)] | ||
| [AttributeUsage(AttributeTargets.Assembly, Inherited = false, AllowMultiple = false)] | ||
| public sealed class GenerateBuildMetadataAttribute : Attribute | ||
| { | ||
| #pragma warning disable IDE0060 // Remove unused parameter | ||
| #pragma warning disable CA1019 // Define accessors for attribute arguments | ||
| public GenerateBuildMetadataAttribute(string buildId, string buildNumber, string sourceBranchName, string sourceVersion, int buildDateTime) | ||
| { | ||
| } | ||
| #pragma warning restore CA1019 // Define accessors for attribute arguments | ||
| #pragma warning restore IDE0060 // Remove unused parameter | ||
| } |
| 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> | ||
| <!-- CA1852 is for the internal shared type DiagDescriptiorsBase. It can't be sealed because there are child classes in other components--> | ||
evgenyfedorov2 marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
| <NoWarn>$(NoWarn);EA0002;CA1852</NoWarn> | ||
| </PropertyGroup> | ||
|
|
||
| <PropertyGroup> | ||
| <Stage>normal</Stage> | ||
| <MinCodeCoverage>100</MinCodeCoverage> | ||
| <MinMutationScore>75</MinMutationScore> | ||
| </PropertyGroup> | ||
|
|
||
| <ItemGroup> | ||
| <PackageReference Include="Microsoft.CodeAnalysis.CSharp.Workspaces" PrivateAssets="all" /> | ||
evgenyfedorov2 marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
| </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> | ||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,32 @@ | ||
| // Licensed to the .NET Foundation under one or more agreements. | ||
| // The .NET Foundation licenses this file to you under the MIT license. | ||
|
|
||
| using System; | ||
|
|
||
| #pragma warning disable RS1035 // Do not use APIs banned for analyzers | ||
| #pragma warning disable S2223 // Non-constant static fields should not be visible - internal in order to be able to override this for tests | ||
|
|
||
| namespace Microsoft.Gen.BuildMetadata; | ||
|
|
||
| internal static class Model | ||
| { | ||
| // Azure DevOps environment variables: https://learn.microsoft.com/azure/devops/pipelines/build/variables#build-variables-devops-services | ||
| internal static string? AzureBuildId = Environment.GetEnvironmentVariable("Build_BuildId"); | ||
| internal static string? AzureBuildNumber = Environment.GetEnvironmentVariable("Build_BuildNumber"); | ||
| internal static string? AzureSourceBranchName = Environment.GetEnvironmentVariable("Build_SourceBranchName"); | ||
|
||
| internal static string? AzureSourceVersion = Environment.GetEnvironmentVariable("Build_SourceVersion"); | ||
|
|
||
| // GitHub Actions environment variables: https://docs.github.com/en/actions/learn-github-actions/variables#default-environment-variables | ||
| internal static string? GitHubRunId = Environment.GetEnvironmentVariable("GITHUB_RUN_ID"); | ||
| internal static string? GitHubRunNumber = Environment.GetEnvironmentVariable("GITHUB_RUN_NUMBER"); | ||
| internal static string? GitHubRefName = Environment.GetEnvironmentVariable("GITHUB_REF_NAME"); | ||
| internal static string? GitHubSha = Environment.GetEnvironmentVariable("GITHUB_SHA"); | ||
|
|
||
| internal static bool IsAzureDevOps = string.Equals(Environment.GetEnvironmentVariable("TF_BUILD"), "true", StringComparison.OrdinalIgnoreCase); | ||
|
|
||
| public static string? BuildId => IsAzureDevOps ? AzureBuildId : GitHubRunId; | ||
| public static string? BuildNumber => IsAzureDevOps ? AzureBuildNumber : GitHubRunNumber; | ||
| public static string? SourceBranchName => IsAzureDevOps ? AzureSourceBranchName : GitHubRefName; | ||
| public static string? SourceVersion => IsAzureDevOps ? AzureSourceVersion : GitHubSha; | ||
| public static DateTimeOffset? BuildDateTime { get; set; } = DateTimeOffset.UtcNow; | ||
| } | ||
Uh oh!
There was an error while loading. Please reload this page.