Skip to content
Draft
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
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
// 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.IsNullOrEmpty(value) &&
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;
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,76 @@
// 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 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.BuildId, buildMetadata.BuildNumber, buildMetadata.SourceBranchName, buildMetadata.SourceVersion);
var result = emitter.Emit(context.CancellationToken);
context.AddSource("BuildMetadataExtensions.g.cs", SourceText.From(result, Encoding.UTF8));
}

private readonly struct BuildMetadata
{
public string? BuildId { get; }

public string? BuildNumber { get; }

public string? SourceBranchName { get; }

public string? SourceVersion { get; }

public BuildMetadata(string? buildId, string? buildNumber, string? sourceBranchName, string? sourceVersion)
{
BuildId = buildId;
BuildNumber = buildNumber;
SourceBranchName = sourceBranchName;
SourceVersion = sourceVersion;
}
}
}
160 changes: 160 additions & 0 deletions src/Generators/Microsoft.Gen.BuildMetadata/Emitter.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,160 @@
// 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
{
private readonly string? _buildId;
private readonly string? _buildNumber;
private readonly string? _sourceBranchName;
private readonly string? _sourceVersion;

public Emitter(string? buildId, string? buildNumber, string? sourceBranchName, string? sourceVersion)
{
_buildId = buildId;
_buildNumber = buildNumber;
_sourceBranchName = sourceBranchName;
_sourceVersion = sourceVersion;
}

public string Emit(CancellationToken cancellationToken)
{
cancellationToken.ThrowIfCancellationRequested();
GenerateBuildMetadataExtensions();
return Capture();
}

[SuppressMessage("Format", "IDE0055", Justification = "For better visualization of how the generated code will look like.")]
private void GenerateBuildMetadataSource()
{
OutGeneratedCodeAttribute();
OutLn("[EditorBrowsable(EditorBrowsableState.Never)]");
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", "{{_buildId}}" },""");
OutLn($$"""{ $"{SectionName}:buildnumber", "{{_buildNumber}}" },""");
OutLn($$"""{ $"{SectionName}:sourcebranchname", "{{_sourceBranchName}}" },""");
OutLn($$"""{ $"{SectionName}:sourceversion", "{{_sourceVersion}}" },""");
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 !NET");

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,38 @@
<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 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.Workspaces" PrivateAssets="all" />
</ItemGroup>

<ItemGroup>
<Compile Update="Parsing\Resources.Designer.cs" DesignTime="True" AutoGen="True" DependentUpon="Resources.resx" />
<Compile Include="..\Shared\*.cs" LinkBase="Shared" />
<None Include="Microsoft.Gen.BuildMetadata.props" Pack="true" PackagePath="build" Visible="false" />
</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,28 @@
<Project>
<PropertyGroup>
<!-- Azure DevOps MSBuild properties - use Azure DevOps environment variables if available, otherwise use empty string -->
<BuildMetadataAzureBuildId Condition="'$(BuildMetadataAzureBuildId)' == ''">$(Build_BuildId)</BuildMetadataAzureBuildId>
<BuildMetadataAzureBuildNumber Condition="'$(BuildMetadataAzureBuildNumber)' == ''">$(Build_BuildNumber)</BuildMetadataAzureBuildNumber>
<BuildMetadataAzureSourceBranchName Condition="'$(BuildMetadataAzureSourceBranchName)' == ''">$(Build_SourceBranchName)</BuildMetadataAzureSourceBranchName>
<BuildMetadataAzureSourceVersion Condition="'$(BuildMetadataAzureSourceVersion)' == ''">$(Build_SourceVersion)</BuildMetadataAzureSourceVersion>
<BuildMetadataIsAzureDevOps Condition="'$(BuildMetadataIsAzureDevOps)' == ''">$(TF_BUILD)</BuildMetadataIsAzureDevOps>

<!-- GitHub Actions MSBuild properties - use GitHub Actions environment variables if available, otherwise use empty string -->
<BuildMetadataGitHubRunId Condition="'$(BuildMetadataGitHubRunId)' == ''">$(GITHUB_RUN_ID)</BuildMetadataGitHubRunId>
<BuildMetadataGitHubRunNumber Condition="'$(BuildMetadataGitHubRunNumber)' == ''">$(GITHUB_RUN_NUMBER)</BuildMetadataGitHubRunNumber>
<BuildMetadataGitHubRefName Condition="'$(BuildMetadataGitHubRefName)' == ''">$(GITHUB_REF_NAME)</BuildMetadataGitHubRefName>
<BuildMetadataGitHubSha Condition="'$(BuildMetadataGitHubSha)' == ''">$(GITHUB_SHA)</BuildMetadataGitHubSha>
</PropertyGroup>

<ItemGroup>
<CompilerVisibleProperty Include="BuildMetadataAzureBuildId" />
<CompilerVisibleProperty Include="BuildMetadataAzureBuildNumber" />
<CompilerVisibleProperty Include="BuildMetadataAzureSourceBranchName" />
<CompilerVisibleProperty Include="BuildMetadataAzureSourceVersion" />
<CompilerVisibleProperty Include="BuildMetadataIsAzureDevOps" />
<CompilerVisibleProperty Include="BuildMetadataGitHubRunId" />
<CompilerVisibleProperty Include="BuildMetadataGitHubRunNumber" />
<CompilerVisibleProperty Include="BuildMetadataGitHubRefName" />
<CompilerVisibleProperty Include="BuildMetadataGitHubSha" />
</ItemGroup>
</Project>
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; }
}
Loading
Loading