microsoft/healthcare-shared-components
Publicmirrored from https://github.com/microsoft/healthcare-shared-componentsAvailable
tools/Microsoft.Health.Extensions.BuildTimeCodeGenerator/Program.cs
53lines · modecode
| 1 | // ------------------------------------------------------------------------------------------------- |
| 2 | // Copyright (c) Microsoft Corporation. All rights reserved. |
| 3 | // Licensed under the MIT License (MIT). See LICENSE in the repo root for license information. |
| 4 | // ------------------------------------------------------------------------------------------------- |
| 5 | |
| 6 | using System; |
| 7 | using System.Collections.Generic; |
| 8 | using System.IO; |
| 9 | using System.Linq; |
| 10 | using System.Reflection; |
| 11 | using Microsoft.CodeAnalysis; |
| 12 | using Microsoft.CodeAnalysis.CSharp.Syntax; |
| 13 | using Microsoft.CodeAnalysis.Formatting; |
| 14 | using static Microsoft.CodeAnalysis.CSharp.SyntaxFactory; |
| 15 | |
| 16 | namespace Microsoft.Health.Extensions.BuildTimeCodeGenerator |
| 17 | { |
| 18 | internal class Program |
| 19 | { |
| 20 | private static HashSet<Assembly> cache = new HashSet<Assembly>(); |
| 21 | |
| 22 | public static void Main(string generatorName, FileInfo outputFile, string @namespace, string[] args = null) |
| 23 | { |
| 24 | string className = Path.GetFileName(outputFile.Name).Split('.')[0]; |
| 25 | |
| 26 | Type codeGeneratorType = Assembly.GetExecutingAssembly().GetTypes().SingleOrDefault(t => t.Name == generatorName) ?? throw new ArgumentException($"Generator '{generatorName} not found"); |
| 27 | var generator = (ICodeGenerator)Activator.CreateInstance(codeGeneratorType, new object[] { args }); |
| 28 | |
| 29 | (MemberDeclarationSyntax[] declarations, UsingDirectiveSyntax[] usingDirectives) = generator.Generate(className); |
| 30 | |
| 31 | NamespaceDeclarationSyntax namespaceDeclaration = |
| 32 | NamespaceDeclaration(IdentifierName(@namespace)) |
| 33 | .AddUsings(usingDirectives) |
| 34 | .AddMembers(declarations) |
| 35 | .WithLeadingTrivia( |
| 36 | Comment(@"//------------------------------------------------------------------------------ |
| 37 | // <auto-generated> |
| 38 | // This code was generated by a tool. |
| 39 | // |
| 40 | // Changes to this file may cause incorrect behavior and will be lost if |
| 41 | // the code is regenerated. |
| 42 | // </auto-generated> |
| 43 | //------------------------------------------------------------------------------ |
| 44 | ")); |
| 45 | |
| 46 | // This formats in a somewhat nicer way than NormalizeWhitespace() |
| 47 | using var workspace = new AdhocWorkspace(); |
| 48 | var formattedSyntax = Formatter.Format(namespaceDeclaration, workspace); |
| 49 | |
| 50 | File.WriteAllText(outputFile.FullName, formattedSyntax.SyntaxTree.ToString()); |
| 51 | } |
| 52 | } |
| 53 | } |
| 54 | |