using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using Microsoft.Build.Framework; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.CSharp.Syntax; using Polonium.Tasks; // ReSharper disable once CheckNamespace public class GenerateRegistryPassThrough : PoloniumTask { [Required] public string ProjectDir { get; set; } public override bool Execute() { try { StringBuilder sb = new(); string csFile = Directory .GetFiles($"{ProjectDir}src", "PoloniumRegistry.cs", SearchOption.TopDirectoryOnly) .FirstOrDefault(); string code = File.ReadAllText(csFile!); sb.AppendLine("#pragma warning disable IDE0130"); foreach (string use in GetUsings(code)) sb.AppendLine(use); sb .AppendLine("using System.Collections.Generic;") .AppendLine("// ReSharper disable once CheckNamespace") .AppendLine("public static partial class GlobalRegistry") .AppendLine("{"); SyntaxTree tree = CSharpSyntaxTree.ParseText(code); CompilationUnitSyntax root = tree.GetCompilationUnitRoot(); ClassDeclarationSyntax clas = root .DescendantNodes() .OfType() .FirstOrDefault(cls => cls.Identifier.Text == "PoloniumRegistry"); IEnumerable properties = clas?.Members .OfType() .Where(m => m.AttributeLists .SelectMany(a => a.Attributes) .Any(a => a.Name.ToString() == "RegistryPassThrough")); if (properties is null) return false; foreach (PropertyDeclarationSyntax property in properties) { if (HasGetterOnly(property)) sb.AppendLine($" public static {GetDisplayName(property.Type)} {property.Identifier.ToString()} => PoloniumRegistry.{property.Identifier.ValueText};"); else { sb .AppendLine($" public static {GetDisplayName(property.Type)} {property.Identifier.ToString()}") .AppendLine(" {") .AppendLine($" get => PoloniumRegistry.{property.Identifier.ValueText};") .AppendLine($" set => PoloniumRegistry.{property.Identifier.ValueText} = value;") .AppendLine(" }"); } } sb .AppendLine("}") .AppendLine("#pragma warning restore IDE0130"); File.WriteAllText($"{ProjectDir}Package/embedded/Patches/RegistryPassThrough.p.cs", sb.ToString()); return true; } catch (Exception e) { Log.LogErrorFromException(e); return false; } } }