private static void MapFile(string file, IEndpointRouteBuilder endpoint) { //use ManifestEmbeddedFileProvider endpoint.MapGet(file, async cnt => { var extension = Path.GetExtension(file); switch (extension) { case ".svg": extension = "image/svg+xml"; break; case ".js": extension = "application/javascript"; break; case ".css": extension = "text/css"; break; default: throw new ArgumentException("cannot know content from " + extension); } cnt.Response.ContentType = extension; var res = EmbeddedResource.GetContent(file); byte[] result = Encoding.UTF8.GetBytes(res); var m = new ReadOnlyMemory <byte>(result); await cnt.Response.BodyWriter.WriteAsync(m); }); }
public static IEndpointRouteBuilder MapSettingsView <T>(this IEndpointRouteBuilder endpoint, IConfiguration configuration, string nameFile = "appsettings.json", string endpointAPISettings = "/api/appsettings") where T : IAppSettingsConfig <T>, new() { MapFile("settingsUI/jsoneditor.js", endpoint); MapFile("settingsUI/jsoneditor.css", endpoint); MapFile("settingsUI/img/jsoneditor-icons.svg", endpoint); endpoint.MapGet("settingsUI", cnt => { cnt.Response.Redirect("settingsUI/index.html"); return(Task.CompletedTask); }); endpoint.MapGet("settingsUI/index.html", async cnt => { var res = EmbeddedResource.GetContent("settingsUI/index.html"); res = res.Replace("appSettingsClass.ClassName", Path.GetFileNameWithoutExtension(nameFile)); res = res.Replace("endpointAPISettings", endpointAPISettings); byte[] result = Encoding.UTF8.GetBytes(res); var m = new ReadOnlyMemory <byte>(result); cnt.Response.ContentType = "text/html"; await cnt.Response.BodyWriter.WriteAsync(m); }); return(endpoint); }
public string GenerateFile(string content, string rootTypeName, string namespaceName, string NameFile) { var json = JsonDocument.Parse(content); if (classModels == null) { classModels = new List <ClassModel>(); var jsonElement = json.RootElement; ResolveTypeRecursive(classModels, jsonElement, rootTypeName.Replace(".", "_"), null); } var appSettingsClass = classModels.First(it => it.parentClass == null); var t = EmbeddedResource.GetContent(NameFile); var template = Template.Parse(t); string generatedCode = template.Render(new { fullNameFile = rootTypeName, nameFileNoExt = rootTypeName, NamespaceName = namespaceName, ClassModels = classModels, ToolName = ThisAssembly.Info.Product, ToolVersion = ThisAssembly.Info.Version, appSettingsClass = appSettingsClass }, member => member.Name); return(generatedCode); }
public void Execute(GeneratorExecutionContext context) { context.CheckDebugger("ThisAssemblyProject"); if (!context.AnalyzerConfigOptions.GlobalOptions.TryGetValue("build_property.ThisAssemblyProject", out var values)) { return; } var properties = values.Split('|') .Select(prop => new KeyValuePair <string, string?>(prop, context.AnalyzerConfigOptions.GlobalOptions.TryGetValue("build_property." + prop, out var value) ? value : null)) .Where(pair => pair.Value != null) .Distinct(new KeyValueComparer()) .ToDictionary(x => x.Key, x => x.Value !); var model = new Model(properties); var language = context.ParseOptions.Language; var file = language.Replace("#", "Sharp") + ".sbntxt"; var template = Template.Parse(EmbeddedResource.GetContent(file), file); var output = template.Render(model, member => member.Name); context.AddSource("ThisAssembly.Project", SourceText.From(output, Encoding.UTF8)); }
public static SourceText Generate(ClassModel classModel) { var template = Template.Parse(EmbeddedResource.GetContent("FlatClassTemplate.txt")); GenerateFlattenMethodBody(classModel); GenerateToFullMethodBody(classModel); string output = template.Render(classModel, member => member.Name); output = Format(output); return(SourceText.From(output, Encoding.UTF8)); }
public void Execute(GeneratorExecutionContext context) { context.CheckDebugger("ThisAssemblyConstants"); var constantFiles = context.AdditionalFiles .Where(f => context.AnalyzerConfigOptions .GetOptions(f) .TryGetValue("build_metadata.AdditionalFiles.SourceItemType", out var itemType) && itemType == "Constant"); if (!constantFiles.Any()) { return; } var pairs = constantFiles.Select(f => { context.AnalyzerConfigOptions.GetOptions(f).TryGetValue("build_metadata.Constant.Value", out var value); context.AnalyzerConfigOptions.GetOptions(f).TryGetValue("build_metadata.Constant.Comment", out var comment); return(new Constant(Path.GetFileName(f.Path), value, string.IsNullOrWhiteSpace(comment) ? null : comment)); }).Where(x => x.Value != null).ToList(); var root = Area.Load(pairs); var language = context.ParseOptions.Language; var file = language.Replace("#", "Sharp") + ".sbntxt"; var template = Template.Parse(EmbeddedResource.GetContent(file), file); var output = template.Render(new Model(root), member => member.Name); // Apply formatting since indenting isn't that nice in Scriban when rendering nested // structures via functions. if (language == LanguageNames.CSharp) { output = Microsoft.CodeAnalysis.CSharp.SyntaxFactory.ParseCompilationUnit(output) .NormalizeWhitespace() .GetText() .ToString(); } //else if (language == LanguageNames.VisualBasic) //{ // output = Microsoft.CodeAnalysis.VisualBasic.SyntaxFactory.ParseCompilationUnit(output) // .NormalizeWhitespace() // .GetText() // .ToString(); //} context.ApplyDesignTimeFix(output, "ThisAssembly.Constants", language); context.AddSource("ThisAssembly.Constants", SourceText.From(output, Encoding.UTF8)); }
public void Execute(GeneratorExecutionContext context) { context.CheckDebugger("ThisAssemblyAssemblyInfo"); var metadata = context.Compilation.Assembly.GetAttributes() .Where(x => !string.IsNullOrEmpty(x.AttributeClass?.Name) && attributes.Contains(x.AttributeClass !.Name)) .Select(x => new KeyValuePair <string, string?>(x.AttributeClass !.Name.Substring(8).Replace("Attribute", ""), (string?)x.ConstructorArguments[0].Value)) .ToDictionary(x => x.Key, x => x.Value ?? ""); var model = new Model(metadata); var language = context.ParseOptions.Language; var file = language.Replace("#", "Sharp") + ".sbntxt"; var template = Template.Parse(EmbeddedResource.GetContent(file), file); var output = template.Render(model, member => member.Name); context.AddSource("ThisAssembly.Info", SourceText.From(output, Encoding.UTF8)); }
public void Execute(GeneratorExecutionContext context) { context.AddSource("FlattenSourceTypes.cs", SourceText.From(EmbeddedResource.GetContent("SourceTypes.cs"), Encoding.UTF8)); if (context.SyntaxReceiver is FlattenReceiver actorSyntaxReciver) { foreach (ClassDeclarationSyntax candidate in actorSyntaxReciver.Candidates) { var classModel = ClassModel.Create(candidate, context.Compilation, context); if (classModel != null) { context.AddSource($"{classModel.Name}-Flatten.cs", SourceCodeGenerator.Generate(classModel)); } } } }
public void Execute(GeneratorExecutionContext context) { context.CheckDebugger("ThisAssemblyMetadata"); var metadata = context.Compilation.Assembly.GetAttributes() .Where(x => x.AttributeClass?.Name == nameof(System.Reflection.AssemblyMetadataAttribute) && Microsoft.CodeAnalysis.CSharp.SyntaxFacts.IsValidIdentifier((string)x.ConstructorArguments[0].Value !)) .Select(x => new KeyValuePair <string, string>((string)x.ConstructorArguments[0].Value !, (string)x.ConstructorArguments[1].Value !)) .Distinct(new KeyValueComparer()) .ToDictionary(x => x.Key, x => x.Value); var model = new Model(metadata); var language = context.ParseOptions.Language; var file = language.Replace("#", "Sharp") + ".sbntxt"; var template = Template.Parse(EmbeddedResource.GetContent(file), file); var output = template.Render(model, member => member.Name); context.AddSource("ThisAssembly.Metadata", SourceText.From(output, Encoding.UTF8)); }
private void GenerateAttribute(GeneratorExecutionContext context) { var attributeSource = EmbeddedResource.GetContent(@"resources/WrapperValueObjectAttribute.cs"); context.AddSource("WrapperValueObjectAttribute.cs", SourceText.From(attributeSource, Encoding.UTF8)); }
public void Execute(GeneratorExecutionContext context) { var compilation = context.Compilation; var(simpleTypeHandlerInterfaceSymbol, typeHandlerInterfaceSymbol) = ( compilation.GetTypeByMetadataName("Npgsql.Internal.TypeHandling.INpgsqlSimpleTypeHandler`1"), compilation.GetTypeByMetadataName("Npgsql.Internal.TypeHandling.INpgsqlTypeHandler`1")); if (simpleTypeHandlerInterfaceSymbol is null || typeHandlerInterfaceSymbol is null) { throw new Exception("Could not find INpgsqlSimpleTypeHandler or INpgsqlTypeHandler"); } var template = Template.Parse(EmbeddedResource.GetContent("TypeHandler.snbtxt"), "TypeHandler.snbtxt"); foreach (var cds in ((MySyntaxReceiver)context.SyntaxReceiver !).TypeHandlerCandidates) { var semanticModel = compilation.GetSemanticModel(cds.SyntaxTree); if (semanticModel.GetDeclaredSymbol(cds) is not INamedTypeSymbol typeSymbol) { continue; } if (typeSymbol.AllInterfaces.Any(i => i.OriginalDefinition.Equals(simpleTypeHandlerInterfaceSymbol, SymbolEqualityComparer.Default))) { AugmentTypeHandler(template, typeSymbol, cds, isSimple: true); continue; } if (typeSymbol.AllInterfaces.Any(i => i.OriginalDefinition.Equals(typeHandlerInterfaceSymbol, SymbolEqualityComparer.Default))) { AugmentTypeHandler(template, typeSymbol, cds, isSimple: false); } } void AugmentTypeHandler( Template template, INamedTypeSymbol typeSymbol, ClassDeclarationSyntax classDeclarationSyntax, bool isSimple) { var usings = new HashSet <string>( new[] { "System", "System.Threading", "System.Threading.Tasks", "Npgsql.Internal" }.Concat(classDeclarationSyntax.SyntaxTree.GetCompilationUnitRoot().Usings .Where(u => u.Alias is null && u.StaticKeyword.IsKind(SyntaxKind.None)) .Select(u => u.Name.ToString()))); var interfaces = typeSymbol.AllInterfaces .Where(i => i.OriginalDefinition.Equals(isSimple ? simpleTypeHandlerInterfaceSymbol : typeHandlerInterfaceSymbol, SymbolEqualityComparer.Default) && !i.TypeArguments[0].IsAbstract); var output = template.Render(new { Usings = usings, TypeName = FormatTypeName(typeSymbol), Namespace = typeSymbol.ContainingNamespace.ToDisplayString(), IsSimple = isSimple, Interfaces = interfaces.Select(i => new { Name = FormatTypeName(i), HandledType = FormatTypeName(i.TypeArguments[0]), }) }); context.AddSource(typeSymbol.Name + ".Generated.cs", SourceText.From(output, Encoding.UTF8)); }
public void Execute(GeneratorExecutionContext context) { context.CheckDebugger("ThisAssemblyStrings"); var resourceFiles = context.AdditionalFiles .Where(f => context.AnalyzerConfigOptions .GetOptions(f) .TryGetValue("build_metadata.AdditionalFiles.SourceItemType", out var itemType) && itemType == "EmbeddedResource"); if (!resourceFiles.Any()) { return; } var language = context.ParseOptions.Language; var file = language.Replace("#", "Sharp") + ".sbntxt"; var template = Template.Parse(EmbeddedResource.GetContent(file), file); foreach (var resourceFile in resourceFiles) { var options = context.AnalyzerConfigOptions.GetOptions(resourceFile); if (!options.TryGetValue("build_metadata.AdditionalFiles.ManifestResourceName", out var resourceName) || string.IsNullOrEmpty(resourceName)) { continue; } var rootArea = ResourceFile.Load(resourceFile.Path, "Strings"); var model = new Model(rootArea, resourceName); model = model with { ResourceName = resourceName }; var output = template.Render(model, member => member.Name); // Apply formatting since indenting isn't that nice in Scriban when rendering nested // structures via functions. if (language == LanguageNames.CSharp) { output = Microsoft.CodeAnalysis.CSharp.SyntaxFactory.ParseCompilationUnit(output) .NormalizeWhitespace() .GetText() .ToString(); } //else if (language == LanguageNames.VisualBasic) //{ // output = Microsoft.CodeAnalysis.VisualBasic.SyntaxFactory.ParseCompilationUnit(output) // .NormalizeWhitespace() // .GetText() // .ToString(); //} context.ApplyDesignTimeFix(output, resourceName, language); context.AddSource(resourceName, SourceText.From(output, Encoding.UTF8)); } var extension = language == LanguageNames.CSharp ? "cs" : language == LanguageNames.VisualBasic ? "vb" : "fs"; var strings = EmbeddedResource.GetContent("ThisAssembly.Strings." + extension); context.ApplyDesignTimeFix(strings, "ThisAssembly.Strings", language); context.AddSource("ThisAssembly.Strings", SourceText.From(strings, Encoding.UTF8)); } }
int Execute() { var tooldir = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location); var invalidChars = Path.GetInvalidPathChars(); var project = extra.Where(arg => arg.IndexOfAny(invalidChars) == -1).FirstOrDefault(arg => File.Exists(arg)) ?? ""; var file = items ?? Path.GetTempFileName(); if (string.IsNullOrEmpty(project)) { var projects = Directory.EnumerateFiles(Directory.GetCurrentDirectory(), "*.*proj").ToList(); var solutions = Directory.EnumerateFiles(Directory.GetCurrentDirectory(), "*.sln").ToList(); // TODO: allow specifying which project. if (solutions.Count == 1) { project = solutions[0]; } else if (projects.Count > 1) { project = projects[0]; } } else { extra.Remove(project); } if (File.Exists(file)) { File.Delete(file); } var slnTargets = $"after.{Path.GetFileName(project)}.targets"; var deleteSlnTargets = false; var contentsOnly = false; try { if (project.EndsWith(".sln") && !File.Exists(slnTargets)) { File.WriteAllText(slnTargets, EmbeddedResource.GetContent("after.sln.targets"), Encoding.UTF8); deleteSlnTargets = true; } // Optimize the "build" so that it doesn't actually do a full compile if possible. if (!Execute(DotnetMuxer.Path.FullName, $"msbuild {project} {string.Join(' ', extra)} -p:dotnet-nugetize=\"{file}\" -t:\"GetPackageContents;Pack\"")) { // The error might have been caused by us not being able to write our slnTargets if (project.EndsWith(".sln") && !deleteSlnTargets) { ColorConsole.WriteLine($"Solution targets '{slnTargets}' already exists. NuGetizing all projects in the solution is therefore required.".Yellow()); } if (binlog) { TryOpenBinlog(); } return(-1); } if (!File.Exists(file)) { // Re-run requesting contents only. if (!Execute(DotnetMuxer.Path.FullName, $"msbuild {project} {string.Join(' ', extra)} -p:dotnet-nugetize-contents=true -p:dotnet-nugetize=\"{file}\" -t:\"GetPackageContents\"")) { // The error might have been caused by us not being able to write our slnTargets if (project.EndsWith(".sln") && !deleteSlnTargets) { ColorConsole.WriteLine($"Solution targets '{slnTargets}' already exists. NuGetizing all projects in the solution is therefore required.".Yellow()); } if (binlog) { TryOpenBinlog(); } return(-1); } contentsOnly = true; } } finally { if (File.Exists(slnTargets) && deleteSlnTargets) { File.Delete(slnTargets); } } if (!File.Exists(file)) { ColorConsole.WriteLine("Failed to discover nugetized content.".Red()); return(-1); } var doc = XDocument.Load(file); if (contentsOnly) { if (project.EndsWith(".sln")) { ColorConsole.WriteLine($"Solution {Path.GetFileName(project)} contains only non-packable project(s), rendering contributed package contents.".Yellow()); } else { ColorConsole.WriteLine($"Project {Path.GetFileName(project)} is not packable, rendering its contributed package contents.".Yellow()); } var dependencies = doc.Root.Descendants("PackageContent") .Where(x => "Dependency".Equals(x.Element("PackFolder")?.Value, StringComparison.OrdinalIgnoreCase)) .Distinct(AnonymousComparer.Create <XElement>(x => x.Attribute("Include").Value + "|" + x.Element("Version").Value + "|" + x.Element("TargetFramework").Value)) .OrderBy(x => x.Element("TargetFramework").Value) .ThenBy(x => x.Attribute("Include").Value) .ToList(); if (dependencies.Count > 0) { ColorConsole.WriteLine($" Dependencies:".Yellow()); foreach (var group in dependencies.GroupBy(x => x.Element("TargetFramework").Value)) { ColorConsole.WriteLine(" ", group.Key.Green()); foreach (var dependency in group) { ColorConsole.WriteLine(" ", dependency.Attribute("Include").Value.White(), $", {dependency.Element("Version").Value}".Gray()); } } } ColorConsole.WriteLine($" Contents:".Yellow()); var contents = doc.Root.Descendants("PackageContent") .Where(x => x.Element("PackagePath") != null) .Distinct(AnonymousComparer.Create <XElement>(x => x.Element("PackagePath").Value)) .OrderBy(x => Path.GetDirectoryName(x.Element("PackagePath").Value)) .ThenBy(x => x.Element("PackagePath").Value); Render(contents.ToList(), 0, 0, ""); Console.WriteLine(); } else { var foundPackage = false; foreach (var metadata in doc.Root.Descendants("PackageMetadata") .Distinct(AnonymousComparer.Create <XElement>( (x, y) => x.Element("PackageId")?.Value == y.Element("PackageId")?.Value, x => x.Element("PackageId")?.Value.GetHashCode() ?? 0))) { var packageId = metadata.Element("PackageId").Value; if (string.IsNullOrEmpty(packageId)) { continue; } foundPackage = true; ColorConsole.WriteLine($"Package: {Path.GetFileName(metadata.Element("NuPkg").Value)}".Yellow()); ColorConsole.WriteLine($" {metadata.Element("Nuspec").Value}".Yellow()); var width = metadata.Elements() .Select(x => x.Name.LocalName.Length) .OrderByDescending(x => x) .First(); foreach (var md in metadata.Elements() .Where(x => x.Name != "PackageId" && x.Name != "Nuspec" && x.Name != "NuPkg") .OrderBy(x => x.Name.LocalName)) { ColorConsole.WriteLine($" {md.Name.LocalName.PadRight(width)}: ", md.Value.White()); } var dependencies = doc.Root.Descendants("PackageContent") .Where(x => "Dependency".Equals(x.Element("PackFolder")?.Value, StringComparison.OrdinalIgnoreCase) && packageId == x.Element("PackageId")?.Value) .Distinct(AnonymousComparer.Create <XElement>(x => x.Attribute("Include").Value + "|" + x.Element("Version").Value + "|" + x.Element("TargetFramework").Value)) .OrderBy(x => x.Element("TargetFramework").Value) .ThenBy(x => x.Attribute("Include").Value) .ToList(); if (dependencies.Count > 0) { ColorConsole.WriteLine($" Dependencies:".Yellow()); foreach (var group in dependencies.GroupBy(x => x.Element("TargetFramework").Value)) { ColorConsole.WriteLine(" ", group.Key.Green()); foreach (var dependency in group) { ColorConsole.WriteLine(" ", dependency.Attribute("Include").Value.White(), $", {dependency.Element("Version").Value}".Gray()); } } } ColorConsole.WriteLine($" Contents:".Yellow()); var contents = doc.Root.Descendants("PackageContent") .Where(x => x.Element("PackagePath") != null && x.Element("PackageId")?.Value == packageId) .Distinct(AnonymousComparer.Create <XElement>(x => x.Element("PackagePath").Value)) .OrderBy(x => Path.GetDirectoryName(x.Element("PackagePath").Value)) .ThenBy(x => x.Element("PackagePath").Value); Render(contents.ToList(), 0, 0, ""); Console.WriteLine(); } if (!foundPackage) { ColorConsole.WriteLine($"No package content was found.".Red()); return(-1); } } Console.WriteLine(); if (items != null) { ColorConsole.WriteLine("> ", file.Yellow()); } if (binlog) { TryOpenBinlog(); } return(0); }