|
// 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.Reflection;
using Microsoft.CodeAnalysis;
namespace Generators
{
[Generator]
public partial class ProductVersionInfoGenerator : IIncrementalGenerator
{
public void Initialize(IncrementalGeneratorInitializationContext context)
{
context.RegisterPostInitializationOutput(ctx =>
{
string? informationalVersion = typeof(ProductVersionInfoGenerator).Assembly.GetCustomAttribute<AssemblyInformationalVersionAttribute>()?.InformationalVersion;
// strip semver metadata (git hash) followed by + sign
string? productVersion = informationalVersion?.Split('+')?[0];
if (string.IsNullOrEmpty(productVersion))
throw new InvalidOperationException($"Unable to obtain product version at build-time.");
// strip semver prerelease label followed by - sign for Environment.Version
Version versionObject = Version.Parse(productVersion.Split('-')[0]);
ctx.AddSource("ProductVersionInfo.g.cs", $@"// <auto-generated/>
namespace System
{{
public static partial class Environment
{{
/// <summary>
/// Gets a version consisting of the major, minor, build, and revision numbers of the common language runtime.
/// </summary>
public static Version Version => new Version({versionObject.ToString().Replace(".", ", ")});
}}
}}
namespace System.Runtime.InteropServices
{{
public static partial class RuntimeInformation
{{
/// <summary>
/// Gets the name of the .NET installation on which an app is running.
/// </summary>
public static string FrameworkDescription => "".NET {productVersion}"";
}}
}}");
});
}
}
}
|