// ------------------------------------------------------------------------------------------------- // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License (MIT). See LICENSE in the repo root for license information. // ------------------------------------------------------------------------------------------------- using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Reflection; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Formatting; using static Microsoft.CodeAnalysis.CSharp.SyntaxFactory; namespace Microsoft.Health.Extensions.BuildTimeCodeGenerator; internal class Program { public static void Main(string generatorName, FileInfo outputFile, string @namespace, string[] args = null) { string className = Path.GetFileName(outputFile.Name).Split('.')[0]; Type codeGeneratorType = Assembly.GetExecutingAssembly().GetTypes().SingleOrDefault(t => t.Name == generatorName) ?? throw new ArgumentException($"Generator '{generatorName} not found"); var generator = (ICodeGenerator)Activator.CreateInstance(codeGeneratorType, new object[] { args }); (MemberDeclarationSyntax[] declarations, UsingDirectiveSyntax[] usingDirectives) = generator.Generate(className); NamespaceDeclarationSyntax namespaceDeclaration = NamespaceDeclaration(IdentifierName(@namespace)) .AddUsings(usingDirectives) .AddMembers(declarations) .WithLeadingTrivia( Comment(@"//------------------------------------------------------------------------------ // // This code was generated by a tool. // // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. // //------------------------------------------------------------------------------ ")); // This formats in a somewhat nicer way than NormalizeWhitespace() using var workspace = new AdhocWorkspace(); var formattedSyntax = Formatter.Format(namespaceDeclaration, workspace); File.WriteAllText(outputFile.FullName, formattedSyntax.SyntaxTree.ToString()); } }