From 6318f80c42cc56809ac291d4bc185e521e9e7d2e Mon Sep 17 00:00:00 2001 From: Senn Geerts Date: Sat, 6 Jul 2024 14:27:12 +0200 Subject: [PATCH 01/23] #196 Publish a global dotnet tool --- .editorconfig | 4 +- .gitattributes | 1 + Saunter.sln | 16 + src/AsyncApi.Saunter.Generator.Cli/Args.cs | 12 + .../AsyncApi.Saunter.Generator.Cli.csproj | 31 ++ .../Commands/Tofile.cs | 54 +++ .../Commands/TofileInternal.cs | 183 ++++++++++ src/AsyncApi.Saunter.Generator.Cli/Program.cs | 32 ++ .../SwashbuckleImport/CommandRunner.cs | 145 ++++++++ .../SwashbuckleImport/HostFactoryResolver.cs | 325 ++++++++++++++++++ .../SwashbuckleImport/HostingApplication.cs | 118 +++++++ .../SwashbuckleImport/readme.md | 3 + src/AsyncApi.Saunter.Generator.Cli/readme.md | 13 + 13 files changed, 936 insertions(+), 1 deletion(-) create mode 100644 .gitattributes create mode 100644 src/AsyncApi.Saunter.Generator.Cli/Args.cs create mode 100644 src/AsyncApi.Saunter.Generator.Cli/AsyncApi.Saunter.Generator.Cli.csproj create mode 100644 src/AsyncApi.Saunter.Generator.Cli/Commands/Tofile.cs create mode 100644 src/AsyncApi.Saunter.Generator.Cli/Commands/TofileInternal.cs create mode 100644 src/AsyncApi.Saunter.Generator.Cli/Program.cs create mode 100644 src/AsyncApi.Saunter.Generator.Cli/SwashbuckleImport/CommandRunner.cs create mode 100644 src/AsyncApi.Saunter.Generator.Cli/SwashbuckleImport/HostFactoryResolver.cs create mode 100644 src/AsyncApi.Saunter.Generator.Cli/SwashbuckleImport/HostingApplication.cs create mode 100644 src/AsyncApi.Saunter.Generator.Cli/SwashbuckleImport/readme.md create mode 100644 src/AsyncApi.Saunter.Generator.Cli/readme.md diff --git a/.editorconfig b/.editorconfig index fe3bd5da..5209be73 100644 --- a/.editorconfig +++ b/.editorconfig @@ -14,10 +14,12 @@ spelling_exclusion_path = SpellingExclusions.dic indent_size = 4 insert_final_newline = true charset = utf-8-bom +end_of_line = lf # XML project files [*.{csproj,vbproj,vcxproj,vcxproj.filters,proj,projitems,shproj}] -indent_size = 4 +indent_size = 2 +end_of_line = lf # XML config files [*.{props,targets,ruleset,config,nuspec,resx,vsixmanifest,vsct}] diff --git a/.gitattributes b/.gitattributes new file mode 100644 index 00000000..07764a78 --- /dev/null +++ b/.gitattributes @@ -0,0 +1 @@ +* text eol=lf \ No newline at end of file diff --git a/Saunter.sln b/Saunter.sln index 46277661..bd69f05e 100644 --- a/Saunter.sln +++ b/Saunter.sln @@ -18,6 +18,7 @@ EndProject Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Solution Items", "Solution Items", "{E0D34C77-924E-4F6B-9289-5A2F07D125A8}" ProjectSection(SolutionItems) = preProject .editorconfig = .editorconfig + .gitattributes = .gitattributes CHANGELOG.md = CHANGELOG.md .github\workflows\ci.yaml = .github\workflows\ci.yaml README.md = README.md @@ -28,6 +29,8 @@ Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Saunter.IntegrationTests.Re EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Saunter.Tests.MarkerTypeTests", "test\Saunter.Tests.MarkerTypeTests\Saunter.Tests.MarkerTypeTests.csproj", "{02284473-6DE7-4EE0-8433-2AC295045549}" EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "AsyncAPI.Saunter.Generator.Cli", "src\AsyncApi.Saunter.Generator.Cli\AsyncAPI.Saunter.Generator.Cli.csproj", "{6C102D4D-3DA4-4763-B75E-C15E33E7E94A}" +EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution Debug|Any CPU = Debug|Any CPU @@ -98,6 +101,18 @@ Global {02284473-6DE7-4EE0-8433-2AC295045549}.Release|x64.Build.0 = Release|Any CPU {02284473-6DE7-4EE0-8433-2AC295045549}.Release|x86.ActiveCfg = Release|Any CPU {02284473-6DE7-4EE0-8433-2AC295045549}.Release|x86.Build.0 = Release|Any CPU + {6C102D4D-3DA4-4763-B75E-C15E33E7E94A}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {6C102D4D-3DA4-4763-B75E-C15E33E7E94A}.Debug|Any CPU.Build.0 = Debug|Any CPU + {6C102D4D-3DA4-4763-B75E-C15E33E7E94A}.Debug|x64.ActiveCfg = Debug|Any CPU + {6C102D4D-3DA4-4763-B75E-C15E33E7E94A}.Debug|x64.Build.0 = Debug|Any CPU + {6C102D4D-3DA4-4763-B75E-C15E33E7E94A}.Debug|x86.ActiveCfg = Debug|Any CPU + {6C102D4D-3DA4-4763-B75E-C15E33E7E94A}.Debug|x86.Build.0 = Debug|Any CPU + {6C102D4D-3DA4-4763-B75E-C15E33E7E94A}.Release|Any CPU.ActiveCfg = Release|Any CPU + {6C102D4D-3DA4-4763-B75E-C15E33E7E94A}.Release|Any CPU.Build.0 = Release|Any CPU + {6C102D4D-3DA4-4763-B75E-C15E33E7E94A}.Release|x64.ActiveCfg = Release|Any CPU + {6C102D4D-3DA4-4763-B75E-C15E33E7E94A}.Release|x64.Build.0 = Release|Any CPU + {6C102D4D-3DA4-4763-B75E-C15E33E7E94A}.Release|x86.ActiveCfg = Release|Any CPU + {6C102D4D-3DA4-4763-B75E-C15E33E7E94A}.Release|x86.Build.0 = Release|Any CPU EndGlobalSection GlobalSection(SolutionProperties) = preSolution HideSolutionNode = FALSE @@ -108,6 +123,7 @@ Global {F188D4A7-BBCB-464F-A370-2BD84D18EA79} = {6ABD4842-47AF-49A5-B057-0EBA64416789} {7CD09B89-130A-41AF-ADAE-2166C4ED695B} = {6491E321-2D02-44AB-9116-D722FE169595} {02284473-6DE7-4EE0-8433-2AC295045549} = {6491E321-2D02-44AB-9116-D722FE169595} + {6C102D4D-3DA4-4763-B75E-C15E33E7E94A} = {28D4C365-FDED-49AE-A97D-36202E24A55A} EndGlobalSection GlobalSection(ExtensibilityGlobals) = postSolution SolutionGuid = {2F85D9DA-DBCF-4F13-8C42-5719F1469B2E} diff --git a/src/AsyncApi.Saunter.Generator.Cli/Args.cs b/src/AsyncApi.Saunter.Generator.Cli/Args.cs new file mode 100644 index 00000000..243315da --- /dev/null +++ b/src/AsyncApi.Saunter.Generator.Cli/Args.cs @@ -0,0 +1,12 @@ +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information. + +// ReSharper disable once CheckNamespace +public static partial class Program +{ + internal const string StartupAssemblyArgument = "startupassembly"; + internal const string DocArgument = "doc"; + internal const string FormatOption = "--format"; + internal const string OutputOption = "--output"; +} diff --git a/src/AsyncApi.Saunter.Generator.Cli/AsyncApi.Saunter.Generator.Cli.csproj b/src/AsyncApi.Saunter.Generator.Cli/AsyncApi.Saunter.Generator.Cli.csproj new file mode 100644 index 00000000..bf10ee04 --- /dev/null +++ b/src/AsyncApi.Saunter.Generator.Cli/AsyncApi.Saunter.Generator.Cli.csproj @@ -0,0 +1,31 @@ + + + + net8.0 + Exe + enable + 12 + AsyncAPI.Saunter.Generator.Cli + + AsyncAPI Command Line Tools + Exe + true + AsyncAPI.Saunter.Generator.Cli + + asyncapi + true + + + + + + + + + + + + + + + diff --git a/src/AsyncApi.Saunter.Generator.Cli/Commands/Tofile.cs b/src/AsyncApi.Saunter.Generator.Cli/Commands/Tofile.cs new file mode 100644 index 00000000..dda464ff --- /dev/null +++ b/src/AsyncApi.Saunter.Generator.Cli/Commands/Tofile.cs @@ -0,0 +1,54 @@ +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information. + +using System.Diagnostics; +using System.Reflection; +using static Program; + +namespace AsyncApi.Saunter.Generator.Cli.Commands; + +internal class Tofile +{ + internal static Func, int> Run(string[] args) => namedArgs => + { + if (!File.Exists(namedArgs[StartupAssemblyArgument])) + { + throw new FileNotFoundException(namedArgs[StartupAssemblyArgument]); + } + + var depsFile = namedArgs[StartupAssemblyArgument].Replace(".dll", ".deps.json"); + var runtimeConfig = namedArgs[StartupAssemblyArgument].Replace(".dll", ".runtimeconfig.json"); + var commandName = args[0]; + + var subProcessArguments = new string[args.Length - 1]; + if (subProcessArguments.Length > 0) + { + Array.Copy(args, 1, subProcessArguments, 0, subProcessArguments.Length); + } + + var subProcessCommandLine = + $"exec --depsfile {EscapePath(depsFile)} " + + $"--runtimeconfig {EscapePath(runtimeConfig)} " + + $"--additional-deps AsyncAPI.Saunter.Generator.Cli.deps.json " + + //$"--additionalprobingpath {EscapePath(typeof(Program).GetTypeInfo().Assembly.Location)} " + + $"{EscapePath(typeof(Program).GetTypeInfo().Assembly.Location)} " + + $"_{commandName} {string.Join(" ", subProcessArguments.Select(EscapePath))}"; + + try + { + var subProcess = Process.Start("dotnet", subProcessCommandLine); + subProcess.WaitForExit(); + return subProcess.ExitCode; + } + catch (Exception e) + { + throw new Exception("Running internal _tofile failed.", e); + } + }; + + private static string EscapePath(string path) + { + return path.Contains(' ') ? "\"" + path + "\"" : path; + } +} diff --git a/src/AsyncApi.Saunter.Generator.Cli/Commands/TofileInternal.cs b/src/AsyncApi.Saunter.Generator.Cli/Commands/TofileInternal.cs new file mode 100644 index 00000000..616769b4 --- /dev/null +++ b/src/AsyncApi.Saunter.Generator.Cli/Commands/TofileInternal.cs @@ -0,0 +1,183 @@ +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information. + +using LEGO.AsyncAPI.Readers; +using Microsoft.Extensions.Options; +using Saunter.Serialization; +using Saunter; +using System.Runtime.Loader; +using System.Reflection; +using LEGO.AsyncAPI; +using LEGO.AsyncAPI.Models; +using Microsoft.Extensions.DependencyInjection; +using AsyncApi.Saunter.Generator.Cli.SwashbuckleImport; +using Microsoft.AspNetCore.Hosting; +using Microsoft.AspNetCore; +using Microsoft.Extensions.Hosting; +using static Program; + +namespace AsyncApi.Saunter.Generator.Cli.Commands; + +internal class TofileInternal +{ + internal static int Run(IDictionary namedArgs) + { + // 1) Configure host with provided startupassembly + var startupAssembly = AssemblyLoadContext.Default.LoadFromAssemblyPath(Path.Combine(Directory.GetCurrentDirectory(), namedArgs[StartupAssemblyArgument])); + + // 2) Build a service container that's based on the startup assembly + var serviceProvider = GetServiceProvider(startupAssembly); + + // 3) Retrieve AsyncAPI via configured provider + var documentProvider = serviceProvider.GetService(); + var asyncapiOptions = serviceProvider.GetService>(); + var documentSerializer = serviceProvider.GetRequiredService(); + + if (!asyncapiOptions.Value.NamedApis.TryGetValue(namedArgs[DocArgument], out var prototype)) + { + throw new ArgumentOutOfRangeException(DocArgument, namedArgs[DocArgument], $"Requested AsyncAPI document not found: '{namedArgs[DocArgument]}'. Known document(s): {string.Join(", ", asyncapiOptions.Value.NamedApis.Keys)}."); + } + var asyncApiSchema = documentProvider.GetDocument(asyncapiOptions.Value, prototype); + var asyncApiSchemaJson = documentSerializer.Serialize(asyncApiSchema); + var asyncApiDocument = new AsyncApiStringReader().Read(asyncApiSchemaJson, out var diagnostic); + if (diagnostic.Errors.Any()) + { + Console.Error.WriteLine($"AsyncAPI Schema is not valid ({diagnostic.Errors.Count} Error(s), {diagnostic.Warnings.Count} Warning(s)):" + + $"{Environment.NewLine}{string.Join(Environment.NewLine, diagnostic.Errors.Select(x => $"- {x}"))}"); + } + + // 4) Serialize to specified output location or stdout + var outputPath = namedArgs.TryGetValue(OutputOption, out var arg1) ? Path.Combine(Directory.GetCurrentDirectory(), arg1) : null; + + if (!string.IsNullOrEmpty(outputPath)) + { + var directoryPath = Path.GetDirectoryName(outputPath); + if (!string.IsNullOrEmpty(directoryPath) && !Directory.Exists(directoryPath)) + { + Directory.CreateDirectory(directoryPath); + } + } + + var exportJson = true; + var exportYml = false; + var exportYaml = false; + if (namedArgs.TryGetValue(FormatOption, out var format)) + { + var splitted = format.Split(',').Select(x => x.Trim()).ToList(); + exportJson = splitted.Any(x => x.Equals("json", StringComparison.OrdinalIgnoreCase)); + exportYml = splitted.Any(x => x.Equals("yml", StringComparison.OrdinalIgnoreCase)); + exportYaml = splitted.Any(x => x.Equals("yaml", StringComparison.OrdinalIgnoreCase)); + } + + if (exportJson) + { + WriteFile(AddFileExtension(outputPath, "json"), stream => asyncApiDocument.SerializeAsJson(stream, AsyncApiVersion.AsyncApi2_0)); + } + + if (exportYml) + { + WriteFile(AddFileExtension(outputPath, "yml"), stream => asyncApiDocument.SerializeAsYaml(stream, AsyncApiVersion.AsyncApi2_0)); + } + + if (exportYaml) + { + WriteFile(AddFileExtension(outputPath, "yaml"), stream => asyncApiDocument.SerializeAsYaml(stream, AsyncApiVersion.AsyncApi2_0)); + } + + return 0; + } + + private static void WriteFile(string outputPath, Action writeAction) + { + using var stream = outputPath != null ? File.Create(outputPath) : Console.OpenStandardOutput(); + writeAction(stream); + + if (outputPath != null) + { + Console.WriteLine($"AsyncAPI {Path.GetExtension(outputPath)[1..]} successfully written to {outputPath}"); + } + } + + private static string AddFileExtension(string outputPath, string extension) + { + if (outputPath == null) + { + return outputPath; + } + + if (outputPath.EndsWith(extension, StringComparison.OrdinalIgnoreCase)) + { + return outputPath; + } + + return $"{TrimEnd(outputPath, ".json", ".yml", ".yaml")}.{extension}"; + } + + private static string TrimEnd(string str, params string[] trims) + { + foreach (var trim in trims) + { + if (str.EndsWith(trim, StringComparison.OrdinalIgnoreCase)) + { + str = str[..^trim.Length]; + } + } + return str; + } + + private static IServiceProvider GetServiceProvider(Assembly startupAssembly) + { + if (TryGetCustomHost(startupAssembly, "AsyncAPIHostFactory", "CreateHost", out IHost host)) + { + return host.Services; + } + + if (TryGetCustomHost(startupAssembly, "AsyncAPIWebHostFactory", "CreateWebHost", out IWebHost webHost)) + { + return webHost.Services; + } + + try + { + return WebHost.CreateDefaultBuilder().UseStartup(startupAssembly.GetName().Name).Build().Services; + } + catch + { + var serviceProvider = HostingApplication.GetServiceProvider(startupAssembly); + + if (serviceProvider != null) + { + return serviceProvider; + } + + throw; + } + } + + private static bool TryGetCustomHost(Assembly startupAssembly, string factoryClassName, string factoryMethodName, out THost host) + { + // Scan the assembly for any types that match the provided naming convention + var factoryTypes = startupAssembly.DefinedTypes.Where(t => t.Name == factoryClassName).ToList(); + + if (factoryTypes.Count == 0) + { + host = default; + return false; + } + else if (factoryTypes.Count > 1) + { + throw new InvalidOperationException($"Multiple {factoryClassName} classes detected"); + } + + var factoryMethod = factoryTypes.Single().GetMethod(factoryMethodName, BindingFlags.Public | BindingFlags.Static); + + if (factoryMethod == null || factoryMethod.ReturnType != typeof(THost)) + { + throw new InvalidOperationException($"{factoryClassName} class detected but does not contain a public static method called {factoryMethodName} with return type {typeof(THost).Name}"); + } + + host = (THost)factoryMethod.Invoke(null, null); + return true; + } +} diff --git a/src/AsyncApi.Saunter.Generator.Cli/Program.cs b/src/AsyncApi.Saunter.Generator.Cli/Program.cs new file mode 100644 index 00000000..33471b73 --- /dev/null +++ b/src/AsyncApi.Saunter.Generator.Cli/Program.cs @@ -0,0 +1,32 @@ +using AsyncApi.Saunter.Generator.Cli.Commands; +using AsyncApi.Saunter.Generator.Cli.SwashbuckleImport; + +// Helper to simplify command line parsing etc. +var runner = new CommandRunner("dotnet asyncapi", "AsyncAPI Command Line Tools", Console.Out); + +// NOTE: The "dotnet asyncapi tofile" command does not serve the request directly. Instead, it invokes a corresponding +// command (called _tofile) via "dotnet exec" so that the runtime configuration (*.runtimeconfig & *.deps.json) of the +// provided startupassembly can be used instead of the tool's. This is neccessary to successfully load the +// startupassembly and it's transitive dependencies. See https://github.com/dotnet/coreclr/issues/13277 for more. + +// > dotnet asyncapi tofile ... +runner.SubCommand("tofile", "retrieves AsyncAPI from a startup assembly, and writes to file ", c => +{ + c.Argument(StartupAssemblyArgument, "relative path to the application's startup assembly"); + c.Argument(DocArgument, "name of the AsyncAPI doc you want to retrieve, as configured in your startup class"); + c.Option(OutputOption, "relative path where the AsyncAPI will be output, defaults to stdout"); + c.Option(FormatOption, "exports AsyncAPI in json and/or yml format [Default json]"); + c.OnRun(Tofile.Run(args)); +}); + +// > dotnet asyncapi _tofile ... (* should only be invoked via "dotnet exec") +runner.SubCommand("_tofile", "", c => +{ + c.Argument(StartupAssemblyArgument, ""); + c.Argument(DocArgument, ""); + c.Option(OutputOption, ""); + c.Option(FormatOption, ""); + c.OnRun(TofileInternal.Run); +}); + +return runner.Run(args); diff --git a/src/AsyncApi.Saunter.Generator.Cli/SwashbuckleImport/CommandRunner.cs b/src/AsyncApi.Saunter.Generator.Cli/SwashbuckleImport/CommandRunner.cs new file mode 100644 index 00000000..c3c8eca0 --- /dev/null +++ b/src/AsyncApi.Saunter.Generator.Cli/SwashbuckleImport/CommandRunner.cs @@ -0,0 +1,145 @@ +namespace AsyncApi.Saunter.Generator.Cli.SwashbuckleImport; + +internal class CommandRunner +{ + private readonly Dictionary _argumentDescriptors; + private readonly Dictionary _optionDescriptors; + private Func, int> _runFunc; + private readonly List _subRunners; + private readonly TextWriter _output; + + public CommandRunner(string commandName, string commandDescription, TextWriter output) + { + CommandName = commandName; + CommandDescription = commandDescription; + _argumentDescriptors = []; + _optionDescriptors = []; + _runFunc = (_) => 1; // no-op + _subRunners = []; + _output = output; + } + + public string CommandName { get; private set; } + + public string CommandDescription { get; private set; } + + public void Argument(string name, string description) + { + _argumentDescriptors.Add(name, description); + } + + public void Option(string name, string description, bool isFlag = false) + { + if (!name.StartsWith("--")) throw new ArgumentException("name of option must begin with --"); + _optionDescriptors.Add(name, new OptionDescriptor { Description = description, IsFlag = isFlag }); + } + + public void OnRun(Func, int> runFunc) + { + _runFunc = runFunc; + } + + public void SubCommand(string name, string description, Action configAction) + { + var runner = new CommandRunner($"{CommandName} {name}", description, _output); + configAction(runner); + _subRunners.Add(runner); + } + + public int Run(IEnumerable args) + { + if (args.Any()) + { + var subRunner = _subRunners.FirstOrDefault(r => r.CommandName.Split(' ').Last() == args.First()); + if (subRunner != null) return subRunner.Run(args.Skip(1)); + } + + if (_subRunners.Any() || !TryParseArgs(args, out IDictionary namedArgs)) + { + PrintUsage(); + return 1; + } + + return _runFunc(namedArgs); + } + + private bool TryParseArgs(IEnumerable args, out IDictionary namedArgs) + { + namedArgs = new Dictionary(); + var argsQueue = new Queue(args); + + // Process options first + while (argsQueue.Any() && argsQueue.Peek().StartsWith("--")) + { + // Ensure it's a known option + var name = argsQueue.Dequeue(); + if (!_optionDescriptors.TryGetValue(name, out OptionDescriptor optionDescriptor)) + return false; + + // If it's not a flag, ensure it's followed by a corresponding value + if (!optionDescriptor.IsFlag && (!argsQueue.Any() || argsQueue.Peek().StartsWith("--"))) + return false; + + namedArgs.Add(name, (!optionDescriptor.IsFlag ? argsQueue.Dequeue() : null)); + } + + // Process required args - ensure corresponding values are provided + foreach (var name in _argumentDescriptors.Keys) + { + if (!argsQueue.Any() || argsQueue.Peek().StartsWith("--")) return false; + namedArgs.Add(name, argsQueue.Dequeue()); + } + + return argsQueue.Count() == 0; + } + + private void PrintUsage() + { + if (_subRunners.Any()) + { + // List sub commands + _output.WriteLine(CommandDescription); + _output.WriteLine("Commands:"); + foreach (var runner in _subRunners) + { + var shortName = runner.CommandName.Split(' ').Last(); + if (shortName.StartsWith("_")) continue; // convention to hide commands + _output.WriteLine($" {shortName}: {runner.CommandDescription}"); + } + _output.WriteLine(); + } + else + { + // Usage for this command + var optionsPart = _optionDescriptors.Any() ? "[options] " : ""; + var argParts = _argumentDescriptors.Keys.Select(name => $"[{name}]"); + _output.WriteLine($"Usage: {CommandName} {optionsPart}{string.Join(" ", argParts)}"); + _output.WriteLine(); + + // Arguments + foreach (var entry in _argumentDescriptors) + { + _output.WriteLine($"{entry.Key}:"); + _output.WriteLine($" {entry.Value}"); + _output.WriteLine(); + } + + // Options + if (_optionDescriptors.Any()) + { + _output.WriteLine("options:"); + foreach (var entry in _optionDescriptors) + { + _output.WriteLine($" {entry.Key}: {entry.Value.Description}"); + } + _output.WriteLine(); + } + } + } + + private struct OptionDescriptor + { + public string Description; + public bool IsFlag; + } +} diff --git a/src/AsyncApi.Saunter.Generator.Cli/SwashbuckleImport/HostFactoryResolver.cs b/src/AsyncApi.Saunter.Generator.Cli/SwashbuckleImport/HostFactoryResolver.cs new file mode 100644 index 00000000..29d3e96e --- /dev/null +++ b/src/AsyncApi.Saunter.Generator.Cli/SwashbuckleImport/HostFactoryResolver.cs @@ -0,0 +1,325 @@ +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. + +using System.Diagnostics; +using System.Reflection; + +namespace Microsoft.Extensions.Hosting; + +internal sealed class HostFactoryResolver +{ + private const BindingFlags DeclaredOnlyLookup = BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Static | BindingFlags.DeclaredOnly; + + public const string BuildWebHost = nameof(BuildWebHost); + public const string CreateWebHostBuilder = nameof(CreateWebHostBuilder); + public const string CreateHostBuilder = nameof(CreateHostBuilder); + + // The amount of time we wait for the diagnostic source events to fire + private static readonly TimeSpan s_defaultWaitTimeout = Debugger.IsAttached ? Timeout.InfiniteTimeSpan : TimeSpan.FromSeconds(30); + + public static Func ResolveWebHostFactory(Assembly assembly) + { + return ResolveFactory(assembly, BuildWebHost); + } + + public static Func ResolveWebHostBuilderFactory(Assembly assembly) + { + return ResolveFactory(assembly, CreateWebHostBuilder); + } + + public static Func ResolveHostBuilderFactory(Assembly assembly) + { + return ResolveFactory(assembly, CreateHostBuilder); + } + + // This helpers encapsulates all of the complex logic required to: + // 1. Execute the entry point of the specified assembly in a different thread. + // 2. Wait for the diagnostic source events to fire + // 3. Give the caller a chance to execute logic to mutate the IHostBuilder + // 4. Resolve the instance of the applications's IHost + // 5. Allow the caller to determine if the entry point has completed + public static Func ResolveHostFactory(Assembly assembly, + TimeSpan? waitTimeout = null, + bool stopApplication = true, + Action configureHostBuilder = null, + Action entrypointCompleted = null) + { + if (assembly.EntryPoint is null) + { + return null; + } + + try + { + // Attempt to load hosting and check the version to make sure the events + // even have a chance of firing (they were added in .NET >= 6) + var hostingAssembly = Assembly.Load("Microsoft.Extensions.Hosting"); + if (hostingAssembly.GetName().Version is Version version && version.Major < 6) + { + return null; + } + + // We're using a version >= 6 so the events can fire. If they don't fire + // then it's because the application isn't using the hosting APIs + } + catch + { + // There was an error loading the extensions assembly, return null. + return null; + } + + return args => new HostingListener(args, assembly.EntryPoint, waitTimeout ?? s_defaultWaitTimeout, stopApplication, configureHostBuilder, entrypointCompleted).CreateHost(); + } + + private static Func ResolveFactory(Assembly assembly, string name) + { + var programType = assembly?.EntryPoint?.DeclaringType; + if (programType == null) + { + return null; + } + + var factory = programType.GetMethod(name, DeclaredOnlyLookup); + if (!IsFactory(factory)) + { + return null; + } + + return args => (T)factory.Invoke(null, [args]); + } + + // TReturn Factory(string[] args); + private static bool IsFactory(MethodInfo factory) + { + return factory != null + && typeof(TReturn).IsAssignableFrom(factory.ReturnType) + && factory.GetParameters().Length == 1 + && typeof(string[]).Equals(factory.GetParameters()[0].ParameterType); + } + + // Used by EF tooling without any Hosting references. Looses some return type safety checks. + public static Func ResolveServiceProviderFactory(Assembly assembly, TimeSpan? waitTimeout = null) + { + // Prefer the older patterns by default for back compat. + var webHostFactory = ResolveWebHostFactory(assembly); + if (webHostFactory != null) + { + return args => + { + var webHost = webHostFactory(args); + return GetServiceProvider(webHost); + }; + } + + var webHostBuilderFactory = ResolveWebHostBuilderFactory(assembly); + if (webHostBuilderFactory != null) + { + return args => + { + var webHostBuilder = webHostBuilderFactory(args); + var webHost = Build(webHostBuilder); + return GetServiceProvider(webHost); + }; + } + + var hostBuilderFactory = ResolveHostBuilderFactory(assembly); + if (hostBuilderFactory != null) + { + return args => + { + var hostBuilder = hostBuilderFactory(args); + var host = Build(hostBuilder); + return GetServiceProvider(host); + }; + } + + var hostFactory = ResolveHostFactory(assembly, waitTimeout: waitTimeout); + if (hostFactory != null) + { + return args => + { + var host = hostFactory(args); + return GetServiceProvider(host); + }; + } + + return null; + } + + private static object Build(object builder) + { + var buildMethod = builder.GetType().GetMethod("Build"); + return buildMethod?.Invoke(builder, []); + } + + private static IServiceProvider GetServiceProvider(object host) + { + if (host == null) + { + return null; + } + var hostType = host.GetType(); + var servicesProperty = hostType.GetProperty("Services", DeclaredOnlyLookup); + return (IServiceProvider)servicesProperty?.GetValue(host); + } + + private sealed class HostingListener : IObserver, IObserver> + { + private readonly string[] _args; + private readonly MethodInfo _entryPoint; + private readonly TimeSpan _waitTimeout; + private readonly bool _stopApplication; + + private readonly TaskCompletionSource _hostTcs = new(); + private IDisposable _disposable; + private readonly Action _configure; + private readonly Action _entrypointCompleted; + private static readonly AsyncLocal _currentListener = new(); + + public HostingListener( + string[] args, + MethodInfo entryPoint, + TimeSpan waitTimeout, + bool stopApplication, + Action configure, + Action entrypointCompleted) + { + _args = args; + _entryPoint = entryPoint; + _waitTimeout = waitTimeout; + _stopApplication = stopApplication; + _configure = configure; + _entrypointCompleted = entrypointCompleted; + } + + public object CreateHost() + { + using var subscription = DiagnosticListener.AllListeners.Subscribe(this); + + // Kick off the entry point on a new thread so we don't block the current one + // in case we need to timeout the execution + var thread = new Thread(() => + { + Exception exception = null; + + try + { + // Set the async local to the instance of the HostingListener so we can filter events that + // aren't scoped to this execution of the entry point. + _currentListener.Value = this; + + var parameters = _entryPoint.GetParameters(); + if (parameters.Length == 0) + { + _entryPoint.Invoke(null, []); + } + else + { + _entryPoint.Invoke(null, [_args]); + } + + // Try to set an exception if the entry point returns gracefully, this will force + // build to throw + _hostTcs.TrySetException(new InvalidOperationException("Unable to build IHost")); + } + catch (TargetInvocationException tie) when (tie.InnerException is StopTheHostException) + { + // The host was stopped by our own logic + } + catch (TargetInvocationException tie) + { + exception = tie.InnerException ?? tie; + + // Another exception happened, propagate that to the caller + _hostTcs.TrySetException(exception); + } + catch (Exception ex) + { + exception = ex; + + // Another exception happened, propagate that to the caller + _hostTcs.TrySetException(ex); + } + finally + { + // Signal that the entry point is completed + _entrypointCompleted?.Invoke(exception); + } + }) + { + // Make sure this doesn't hang the process + IsBackground = true + }; + + // Start the thread + thread.Start(); + + try + { + // Wait before throwing an exception + if (!_hostTcs.Task.Wait(_waitTimeout)) + { + throw new InvalidOperationException("Unable to build IHost"); + } + } + catch (AggregateException) when (_hostTcs.Task.IsCompleted) + { + // Lets this propagate out of the call to GetAwaiter().GetResult() + } + + Debug.Assert(_hostTcs.Task.IsCompleted); + + return _hostTcs.Task.GetAwaiter().GetResult(); + } + + public void OnCompleted() + { + _disposable?.Dispose(); + } + + public void OnError(Exception error) + { + } + + public void OnNext(DiagnosticListener value) + { + if (_currentListener.Value != this) + { + // Ignore events that aren't for this listener + return; + } + + if (value.Name == "Microsoft.Extensions.Hosting") + { + _disposable = value.Subscribe(this); + } + } + + public void OnNext(KeyValuePair value) + { + if (_currentListener.Value != this) + { + // Ignore events that aren't for this listener + return; + } + + if (value.Key == "HostBuilding") + { + _configure?.Invoke(value.Value); + } + + if (value.Key == "HostBuilt") + { + _hostTcs.TrySetResult(value.Value); + + if (_stopApplication) + { + // Stop the host from running further + throw new StopTheHostException(); + } + } + } + + private sealed class StopTheHostException : Exception; + } +} diff --git a/src/AsyncApi.Saunter.Generator.Cli/SwashbuckleImport/HostingApplication.cs b/src/AsyncApi.Saunter.Generator.Cli/SwashbuckleImport/HostingApplication.cs new file mode 100644 index 00000000..e4635aff --- /dev/null +++ b/src/AsyncApi.Saunter.Generator.Cli/SwashbuckleImport/HostingApplication.cs @@ -0,0 +1,118 @@ +using System.Reflection; +using Microsoft.AspNetCore.Hosting.Server; +using Microsoft.AspNetCore.Http.Features; +#if NETCOREAPP3_0_OR_GREATER +using Microsoft.Extensions.DependencyInjection; +#endif +using Microsoft.Extensions.Hosting; + +namespace AsyncApi.Saunter.Generator.Cli.SwashbuckleImport; + +// Represents an application that uses Microsoft.Extensions.Hosting and supports +// the various entry point flavors. The final model *does not* have an explicit CreateHost entry point and thus inverts the typical flow where the +// execute Main and we wait for events to fire in order to access the appropriate state. +// This is what allows top level statements to work, but getting the IServiceProvider is slightly more complex. +internal class HostingApplication +{ + internal static IServiceProvider GetServiceProvider(Assembly assembly) + { +#if NETCOREAPP2_1 + return null; +#else + // We're disabling the default server and the console host lifetime. This will disable: + // 1. Listening on ports + // 2. Logging to the console from the default host. + // This is essentially what the test server does in order to get access to the application's + // IServicerProvider *and* middleware pipeline. + void ConfigureHostBuilder(object hostBuilder) + { + ((IHostBuilder)hostBuilder).ConfigureServices((context, services) => + { + services.AddSingleton(); + services.AddSingleton(); + + for (var i = services.Count - 1; i >= 0; i--) + { + // exclude all implementations of IHostedService + // except Microsoft.AspNetCore.Hosting.GenericWebHostService because that one will build/configure + // the WebApplication/Middleware pipeline in the case of the GenericWebHostBuilder. + var registration = services[i]; + if (registration.ServiceType == typeof(IHostedService) + && registration.ImplementationType is not { FullName: "Microsoft.AspNetCore.Hosting.GenericWebHostService" }) + { + services.RemoveAt(i); + } + } + }); + } + + var waitForStartTcs = new TaskCompletionSource(); + + void OnEntryPointExit(Exception exception) + { + // If the entry point exited, we'll try to complete the wait + if (exception != null) + { + waitForStartTcs.TrySetException(exception); + } + else + { + waitForStartTcs.TrySetResult(null); + } + } + + // If all of the existing techniques fail, then try to resolve the ResolveHostFactory + var factory = HostFactoryResolver.ResolveHostFactory(assembly, + stopApplication: false, + configureHostBuilder: ConfigureHostBuilder, + entrypointCompleted: OnEntryPointExit); + + // We're unable to resolve the factory. This could mean the application wasn't referencing the right + // version of hosting. + if (factory == null) + { + return null; + } + + try + { + // Get the IServiceProvider from the host + var assemblyName = assembly.GetName()?.FullName ?? string.Empty; + // We set the application name in the hosting environment to the startup assembly + // to avoid falling back to the entry assembly (dotnet-swagger) when configuring our + // application. + var services = ((IHost)factory([$"--{HostDefaults.ApplicationKey}={assemblyName}"])).Services; + + // Wait for the application to start so that we know it's fully configured. This is important because + // we need the middleware pipeline to be configured before we access the ISwaggerProvider in + // in the IServiceProvider + var applicationLifetime = services.GetRequiredService(); + + using var registration = applicationLifetime.ApplicationStarted.Register(() => waitForStartTcs.TrySetResult(null)); + waitForStartTcs.Task.Wait(); + + return services; + } + catch (InvalidOperationException) + { + // We're unable to resolve the host, swallow the exception and return null + } + + return null; +#endif + } + + private class NoopHostLifetime : IHostLifetime + { + public Task StopAsync(CancellationToken cancellationToken) => Task.CompletedTask; + public Task WaitForStartAsync(CancellationToken cancellationToken) => Task.CompletedTask; + } + + private class NoopServer : IServer + { + public IFeatureCollection Features { get; } = new FeatureCollection(); + public void Dispose() { } + public Task StartAsync(IHttpApplication application, CancellationToken cancellationToken) => Task.CompletedTask; + public Task StopAsync(CancellationToken cancellationToken) => Task.CompletedTask; + } +} diff --git a/src/AsyncApi.Saunter.Generator.Cli/SwashbuckleImport/readme.md b/src/AsyncApi.Saunter.Generator.Cli/SwashbuckleImport/readme.md new file mode 100644 index 00000000..babea97b --- /dev/null +++ b/src/AsyncApi.Saunter.Generator.Cli/SwashbuckleImport/readme.md @@ -0,0 +1,3 @@ +This code is taken from [Swashbuckle.AspNetCore.Cli](https://github.com/domaindrivendev/Swashbuckle.AspNetCore/tree/master/src/Swashbuckle.AspNetCore.Cli) + +Since Swashbuckle.AspNetCore.Cli is delivered as a tool, code cannot be reference through Nuget. \ No newline at end of file diff --git a/src/AsyncApi.Saunter.Generator.Cli/readme.md b/src/AsyncApi.Saunter.Generator.Cli/readme.md new file mode 100644 index 00000000..afb7f457 --- /dev/null +++ b/src/AsyncApi.Saunter.Generator.Cli/readme.md @@ -0,0 +1,13 @@ +# AsyncApi Generator.Cli Tool + +## Tool usage +``` +dotnet asyncapi tofile --output [output-path] --format [json,yml,yaml] [startup-assembly] [asyncapi-document-name] +``` + +## Tool options +startup-assembly: the file path to the entrypoint dotnet DLL that hosts AsyncAPI document(s). +asyncapi-document-name: (optional) The name of the AsyncAPI document as defined in the startup class by the ```.ConfigureNamedAsyncApi()```-method. If not specified, all documents will be exported. + +--output: the output path or the file name. File extension can be omitted, as the --format file determine the file extension. +--format: the output formats to generate, can be a combination of json, yml and/or yaml. File extension is appended to the output path. From 2162d72adb996d85d5a14f0dd4b07673cf5ffb73 Mon Sep 17 00:00:00 2001 From: Senn Geerts Date: Sat, 6 Jul 2024 14:36:00 +0200 Subject: [PATCH 02/23] #196 Publish a global dotnet tool -- Api/API casing fix --- Saunter.sln | 2 +- .../Args.cs | 0 .../AsyncAPI.Saunter.Generator.Cli.csproj} | 0 .../Commands/Tofile.cs | 0 .../Commands/TofileInternal.cs | 0 .../Program.cs | 0 .../SwashbuckleImport/CommandRunner.cs | 0 .../SwashbuckleImport/HostFactoryResolver.cs | 0 .../SwashbuckleImport/HostingApplication.cs | 0 .../SwashbuckleImport/readme.md | 0 .../readme.md | 0 11 files changed, 1 insertion(+), 1 deletion(-) rename src/{AsyncApi.Saunter.Generator.Cli => AsyncAPI.Saunter.Generator.Cli}/Args.cs (100%) rename src/{AsyncApi.Saunter.Generator.Cli/AsyncApi.Saunter.Generator.Cli.csproj => AsyncAPI.Saunter.Generator.Cli/AsyncAPI.Saunter.Generator.Cli.csproj} (100%) rename src/{AsyncApi.Saunter.Generator.Cli => AsyncAPI.Saunter.Generator.Cli}/Commands/Tofile.cs (100%) rename src/{AsyncApi.Saunter.Generator.Cli => AsyncAPI.Saunter.Generator.Cli}/Commands/TofileInternal.cs (100%) rename src/{AsyncApi.Saunter.Generator.Cli => AsyncAPI.Saunter.Generator.Cli}/Program.cs (100%) rename src/{AsyncApi.Saunter.Generator.Cli => AsyncAPI.Saunter.Generator.Cli}/SwashbuckleImport/CommandRunner.cs (100%) rename src/{AsyncApi.Saunter.Generator.Cli => AsyncAPI.Saunter.Generator.Cli}/SwashbuckleImport/HostFactoryResolver.cs (100%) rename src/{AsyncApi.Saunter.Generator.Cli => AsyncAPI.Saunter.Generator.Cli}/SwashbuckleImport/HostingApplication.cs (100%) rename src/{AsyncApi.Saunter.Generator.Cli => AsyncAPI.Saunter.Generator.Cli}/SwashbuckleImport/readme.md (100%) rename src/{AsyncApi.Saunter.Generator.Cli => AsyncAPI.Saunter.Generator.Cli}/readme.md (100%) diff --git a/Saunter.sln b/Saunter.sln index bd69f05e..2aff09fa 100644 --- a/Saunter.sln +++ b/Saunter.sln @@ -29,7 +29,7 @@ Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Saunter.IntegrationTests.Re EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Saunter.Tests.MarkerTypeTests", "test\Saunter.Tests.MarkerTypeTests\Saunter.Tests.MarkerTypeTests.csproj", "{02284473-6DE7-4EE0-8433-2AC295045549}" EndProject -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "AsyncAPI.Saunter.Generator.Cli", "src\AsyncApi.Saunter.Generator.Cli\AsyncAPI.Saunter.Generator.Cli.csproj", "{6C102D4D-3DA4-4763-B75E-C15E33E7E94A}" +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "AsyncAPI.Saunter.Generator.Cli", "src\AsyncAPI.Saunter.Generator.Cli\AsyncAPI.Saunter.Generator.Cli.csproj", "{6C102D4D-3DA4-4763-B75E-C15E33E7E94A}" EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution diff --git a/src/AsyncApi.Saunter.Generator.Cli/Args.cs b/src/AsyncAPI.Saunter.Generator.Cli/Args.cs similarity index 100% rename from src/AsyncApi.Saunter.Generator.Cli/Args.cs rename to src/AsyncAPI.Saunter.Generator.Cli/Args.cs diff --git a/src/AsyncApi.Saunter.Generator.Cli/AsyncApi.Saunter.Generator.Cli.csproj b/src/AsyncAPI.Saunter.Generator.Cli/AsyncAPI.Saunter.Generator.Cli.csproj similarity index 100% rename from src/AsyncApi.Saunter.Generator.Cli/AsyncApi.Saunter.Generator.Cli.csproj rename to src/AsyncAPI.Saunter.Generator.Cli/AsyncAPI.Saunter.Generator.Cli.csproj diff --git a/src/AsyncApi.Saunter.Generator.Cli/Commands/Tofile.cs b/src/AsyncAPI.Saunter.Generator.Cli/Commands/Tofile.cs similarity index 100% rename from src/AsyncApi.Saunter.Generator.Cli/Commands/Tofile.cs rename to src/AsyncAPI.Saunter.Generator.Cli/Commands/Tofile.cs diff --git a/src/AsyncApi.Saunter.Generator.Cli/Commands/TofileInternal.cs b/src/AsyncAPI.Saunter.Generator.Cli/Commands/TofileInternal.cs similarity index 100% rename from src/AsyncApi.Saunter.Generator.Cli/Commands/TofileInternal.cs rename to src/AsyncAPI.Saunter.Generator.Cli/Commands/TofileInternal.cs diff --git a/src/AsyncApi.Saunter.Generator.Cli/Program.cs b/src/AsyncAPI.Saunter.Generator.Cli/Program.cs similarity index 100% rename from src/AsyncApi.Saunter.Generator.Cli/Program.cs rename to src/AsyncAPI.Saunter.Generator.Cli/Program.cs diff --git a/src/AsyncApi.Saunter.Generator.Cli/SwashbuckleImport/CommandRunner.cs b/src/AsyncAPI.Saunter.Generator.Cli/SwashbuckleImport/CommandRunner.cs similarity index 100% rename from src/AsyncApi.Saunter.Generator.Cli/SwashbuckleImport/CommandRunner.cs rename to src/AsyncAPI.Saunter.Generator.Cli/SwashbuckleImport/CommandRunner.cs diff --git a/src/AsyncApi.Saunter.Generator.Cli/SwashbuckleImport/HostFactoryResolver.cs b/src/AsyncAPI.Saunter.Generator.Cli/SwashbuckleImport/HostFactoryResolver.cs similarity index 100% rename from src/AsyncApi.Saunter.Generator.Cli/SwashbuckleImport/HostFactoryResolver.cs rename to src/AsyncAPI.Saunter.Generator.Cli/SwashbuckleImport/HostFactoryResolver.cs diff --git a/src/AsyncApi.Saunter.Generator.Cli/SwashbuckleImport/HostingApplication.cs b/src/AsyncAPI.Saunter.Generator.Cli/SwashbuckleImport/HostingApplication.cs similarity index 100% rename from src/AsyncApi.Saunter.Generator.Cli/SwashbuckleImport/HostingApplication.cs rename to src/AsyncAPI.Saunter.Generator.Cli/SwashbuckleImport/HostingApplication.cs diff --git a/src/AsyncApi.Saunter.Generator.Cli/SwashbuckleImport/readme.md b/src/AsyncAPI.Saunter.Generator.Cli/SwashbuckleImport/readme.md similarity index 100% rename from src/AsyncApi.Saunter.Generator.Cli/SwashbuckleImport/readme.md rename to src/AsyncAPI.Saunter.Generator.Cli/SwashbuckleImport/readme.md diff --git a/src/AsyncApi.Saunter.Generator.Cli/readme.md b/src/AsyncAPI.Saunter.Generator.Cli/readme.md similarity index 100% rename from src/AsyncApi.Saunter.Generator.Cli/readme.md rename to src/AsyncAPI.Saunter.Generator.Cli/readme.md From 55895a2afc5dd17acd0eac6161a2b289388ac4fa Mon Sep 17 00:00:00 2001 From: Senn Geerts Date: Sat, 6 Jul 2024 14:43:36 +0200 Subject: [PATCH 03/23] #196 .NET8 --- .github/workflows/ci.yaml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/ci.yaml b/.github/workflows/ci.yaml index bf470245..0cfc8f79 100644 --- a/.github/workflows/ci.yaml +++ b/.github/workflows/ci.yaml @@ -22,7 +22,7 @@ jobs: node-version: 'lts/*' # latest LTS version - uses: actions/setup-dotnet@v2 with: - dotnet-version: '6.0.x' # SDK Version to use; x will use the latest version of the channel + dotnet-version: '8.0.x' # SDK Version to use; x will use the latest version of the channel - name: Run NPM install run: npm ci From 6ba3409ef277262b518045921850df6184c2b2f3 Mon Sep 17 00:00:00 2001 From: Senn Geerts Date: Sat, 6 Jul 2024 14:46:59 +0200 Subject: [PATCH 04/23] #196 .NET6 --- .github/workflows/ci.yaml | 2 +- .../AsyncAPI.Saunter.Generator.Cli.csproj | 3 +-- 2 files changed, 2 insertions(+), 3 deletions(-) diff --git a/.github/workflows/ci.yaml b/.github/workflows/ci.yaml index 0cfc8f79..bf470245 100644 --- a/.github/workflows/ci.yaml +++ b/.github/workflows/ci.yaml @@ -22,7 +22,7 @@ jobs: node-version: 'lts/*' # latest LTS version - uses: actions/setup-dotnet@v2 with: - dotnet-version: '8.0.x' # SDK Version to use; x will use the latest version of the channel + dotnet-version: '6.0.x' # SDK Version to use; x will use the latest version of the channel - name: Run NPM install run: npm ci diff --git a/src/AsyncAPI.Saunter.Generator.Cli/AsyncAPI.Saunter.Generator.Cli.csproj b/src/AsyncAPI.Saunter.Generator.Cli/AsyncAPI.Saunter.Generator.Cli.csproj index bf10ee04..0181dacd 100644 --- a/src/AsyncAPI.Saunter.Generator.Cli/AsyncAPI.Saunter.Generator.Cli.csproj +++ b/src/AsyncAPI.Saunter.Generator.Cli/AsyncAPI.Saunter.Generator.Cli.csproj @@ -1,7 +1,7 @@  - net8.0 + net6.0 Exe enable 12 @@ -11,7 +11,6 @@ Exe true AsyncAPI.Saunter.Generator.Cli - asyncapi true From 74c9cff2ef59a98d152cce29c1dea628e44b11f2 Mon Sep 17 00:00:00 2001 From: Senn Geerts Date: Sat, 6 Jul 2024 14:52:06 +0200 Subject: [PATCH 05/23] #196 I'd like .NET8 more, request both for ci --- .github/workflows/ci.yaml | 4 +++- .../AsyncAPI.Saunter.Generator.Cli.csproj | 2 +- 2 files changed, 4 insertions(+), 2 deletions(-) diff --git a/.github/workflows/ci.yaml b/.github/workflows/ci.yaml index bf470245..8eb5bb44 100644 --- a/.github/workflows/ci.yaml +++ b/.github/workflows/ci.yaml @@ -22,7 +22,9 @@ jobs: node-version: 'lts/*' # latest LTS version - uses: actions/setup-dotnet@v2 with: - dotnet-version: '6.0.x' # SDK Version to use; x will use the latest version of the channel + dotnet-version: | + 6.0.x # SDK Version to use; x will use the latest version of the channel + 8.0.x - name: Run NPM install run: npm ci diff --git a/src/AsyncAPI.Saunter.Generator.Cli/AsyncAPI.Saunter.Generator.Cli.csproj b/src/AsyncAPI.Saunter.Generator.Cli/AsyncAPI.Saunter.Generator.Cli.csproj index 0181dacd..b5539990 100644 --- a/src/AsyncAPI.Saunter.Generator.Cli/AsyncAPI.Saunter.Generator.Cli.csproj +++ b/src/AsyncAPI.Saunter.Generator.Cli/AsyncAPI.Saunter.Generator.Cli.csproj @@ -1,7 +1,7 @@  - net6.0 + net8.0 Exe enable 12 From cc5d95213b31791140fc771b770142038cf8787d Mon Sep 17 00:00:00 2001 From: Senn Geerts Date: Sat, 6 Jul 2024 15:01:07 +0200 Subject: [PATCH 06/23] #196 I'd like .NET8 more, request both for ci? --- .github/workflows/ci.yaml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/ci.yaml b/.github/workflows/ci.yaml index 8eb5bb44..d262e704 100644 --- a/.github/workflows/ci.yaml +++ b/.github/workflows/ci.yaml @@ -23,7 +23,7 @@ jobs: - uses: actions/setup-dotnet@v2 with: dotnet-version: | - 6.0.x # SDK Version to use; x will use the latest version of the channel + 6.0.x 8.0.x - name: Run NPM install From 569a30ac5efdd4547c0798226b96c09e8cfd23c4 Mon Sep 17 00:00:00 2001 From: Senn Geerts Date: Sat, 6 Jul 2024 17:20:14 +0200 Subject: [PATCH 07/23] #196 Fixed resolving, added support for multiple asyncAPI documents, default all. Added support for env vars --- src/AsyncAPI.Saunter.Generator.Cli/Args.cs | 4 +- .../AsyncAPI.Saunter.Generator.Cli.csproj | 5 +- .../Commands/Tofile.cs | 18 +-- .../Commands/TofileInternal.cs | 118 +++++++++--------- .../Internal/DependencyResolver.cs | 28 +++++ src/AsyncAPI.Saunter.Generator.Cli/Program.cs | 21 ++-- src/AsyncAPI.Saunter.Generator.Cli/readme.md | 12 +- 7 files changed, 118 insertions(+), 88 deletions(-) create mode 100644 src/AsyncAPI.Saunter.Generator.Cli/Internal/DependencyResolver.cs diff --git a/src/AsyncAPI.Saunter.Generator.Cli/Args.cs b/src/AsyncAPI.Saunter.Generator.Cli/Args.cs index 243315da..cafc79b3 100644 --- a/src/AsyncAPI.Saunter.Generator.Cli/Args.cs +++ b/src/AsyncAPI.Saunter.Generator.Cli/Args.cs @@ -6,7 +6,9 @@ public static partial class Program { internal const string StartupAssemblyArgument = "startupassembly"; - internal const string DocArgument = "doc"; + internal const string DocOption = "--doc"; internal const string FormatOption = "--format"; + internal const string FileNameOption = "--filename"; internal const string OutputOption = "--output"; + internal const string EnvOption = "--env"; } diff --git a/src/AsyncAPI.Saunter.Generator.Cli/AsyncAPI.Saunter.Generator.Cli.csproj b/src/AsyncAPI.Saunter.Generator.Cli/AsyncAPI.Saunter.Generator.Cli.csproj index b5539990..63a8b166 100644 --- a/src/AsyncAPI.Saunter.Generator.Cli/AsyncAPI.Saunter.Generator.Cli.csproj +++ b/src/AsyncAPI.Saunter.Generator.Cli/AsyncAPI.Saunter.Generator.Cli.csproj @@ -1,7 +1,6 @@  - net8.0 Exe enable 12 @@ -11,8 +10,8 @@ Exe true AsyncAPI.Saunter.Generator.Cli - asyncapi - true + AsyncAPI.NET + net8.0;net6.0 diff --git a/src/AsyncAPI.Saunter.Generator.Cli/Commands/Tofile.cs b/src/AsyncAPI.Saunter.Generator.Cli/Commands/Tofile.cs index dda464ff..9faa30c9 100644 --- a/src/AsyncAPI.Saunter.Generator.Cli/Commands/Tofile.cs +++ b/src/AsyncAPI.Saunter.Generator.Cli/Commands/Tofile.cs @@ -27,24 +27,16 @@ internal static Func, int> Run(string[] args) => nam Array.Copy(args, 1, subProcessArguments, 0, subProcessArguments.Length); } + var assembly = typeof(Program).GetTypeInfo().Assembly; var subProcessCommandLine = $"exec --depsfile {EscapePath(depsFile)} " + $"--runtimeconfig {EscapePath(runtimeConfig)} " + - $"--additional-deps AsyncAPI.Saunter.Generator.Cli.deps.json " + - //$"--additionalprobingpath {EscapePath(typeof(Program).GetTypeInfo().Assembly.Location)} " + - $"{EscapePath(typeof(Program).GetTypeInfo().Assembly.Location)} " + + $"{EscapePath(assembly.Location)} " + $"_{commandName} {string.Join(" ", subProcessArguments.Select(EscapePath))}"; - try - { - var subProcess = Process.Start("dotnet", subProcessCommandLine); - subProcess.WaitForExit(); - return subProcess.ExitCode; - } - catch (Exception e) - { - throw new Exception("Running internal _tofile failed.", e); - } + var subProcess = Process.Start("dotnet", subProcessCommandLine); + subProcess.WaitForExit(); + return subProcess.ExitCode; }; private static string EscapePath(string path) diff --git a/src/AsyncAPI.Saunter.Generator.Cli/Commands/TofileInternal.cs b/src/AsyncAPI.Saunter.Generator.Cli/Commands/TofileInternal.cs index 616769b4..00ea898f 100644 --- a/src/AsyncAPI.Saunter.Generator.Cli/Commands/TofileInternal.cs +++ b/src/AsyncAPI.Saunter.Generator.Cli/Commands/TofileInternal.cs @@ -27,6 +27,18 @@ internal static int Run(IDictionary namedArgs) var startupAssembly = AssemblyLoadContext.Default.LoadFromAssemblyPath(Path.Combine(Directory.GetCurrentDirectory(), namedArgs[StartupAssemblyArgument])); // 2) Build a service container that's based on the startup assembly + var envVars = namedArgs.TryGetValue(EnvOption, out var x) ? x.Split(',').Select(x => x.Trim()) : Array.Empty(); + foreach (var envVar in envVars.Select(x => x.Split('=').Select(x => x.Trim()).ToList())) + { + if (envVar.Count == 2) + { + Environment.SetEnvironmentVariable(envVar[0], envVar[1], EnvironmentVariableTarget.Process); + } + else + { + throw new ArgumentOutOfRangeException(EnvOption, namedArgs[EnvOption], "Environment variable should be in the format: env1=value1,env2=value2"); + } + } var serviceProvider = GetServiceProvider(startupAssembly); // 3) Retrieve AsyncAPI via configured provider @@ -34,55 +46,60 @@ internal static int Run(IDictionary namedArgs) var asyncapiOptions = serviceProvider.GetService>(); var documentSerializer = serviceProvider.GetRequiredService(); - if (!asyncapiOptions.Value.NamedApis.TryGetValue(namedArgs[DocArgument], out var prototype)) + var documentNames = namedArgs.TryGetValue(DocOption, out var doc) ? [doc] : asyncapiOptions.Value.NamedApis.Keys; + var fileTemplate = namedArgs.TryGetValue(FileNameOption, out var template) ? template : "{document}_asyncapi.{extension}"; + foreach (var documentName in documentNames) { - throw new ArgumentOutOfRangeException(DocArgument, namedArgs[DocArgument], $"Requested AsyncAPI document not found: '{namedArgs[DocArgument]}'. Known document(s): {string.Join(", ", asyncapiOptions.Value.NamedApis.Keys)}."); - } - var asyncApiSchema = documentProvider.GetDocument(asyncapiOptions.Value, prototype); - var asyncApiSchemaJson = documentSerializer.Serialize(asyncApiSchema); - var asyncApiDocument = new AsyncApiStringReader().Read(asyncApiSchemaJson, out var diagnostic); - if (diagnostic.Errors.Any()) - { - Console.Error.WriteLine($"AsyncAPI Schema is not valid ({diagnostic.Errors.Count} Error(s), {diagnostic.Warnings.Count} Warning(s)):" + - $"{Environment.NewLine}{string.Join(Environment.NewLine, diagnostic.Errors.Select(x => $"- {x}"))}"); - } + if (!asyncapiOptions.Value.NamedApis.TryGetValue(documentName, out var prototype)) + { + throw new ArgumentOutOfRangeException(DocOption, documentName, $"Requested AsyncAPI document not found: '{documentName}'. Known document(s): {string.Join(", ", asyncapiOptions.Value.NamedApis.Keys)}."); + } - // 4) Serialize to specified output location or stdout - var outputPath = namedArgs.TryGetValue(OutputOption, out var arg1) ? Path.Combine(Directory.GetCurrentDirectory(), arg1) : null; + var asyncApiSchema = documentProvider.GetDocument(asyncapiOptions.Value, prototype); + var asyncApiSchemaJson = documentSerializer.Serialize(asyncApiSchema); + var asyncApiDocument = new AsyncApiStringReader().Read(asyncApiSchemaJson, out var diagnostic); + if (diagnostic.Errors.Any()) + { + Console.Error.WriteLine($"AsyncAPI Schema '{documentName}' is not valid ({diagnostic.Errors.Count} Error(s), {diagnostic.Warnings.Count} Warning(s)):" + + $"{Environment.NewLine}{string.Join(Environment.NewLine, diagnostic.Errors.Select(x => $"- {x}"))}"); + } - if (!string.IsNullOrEmpty(outputPath)) - { - var directoryPath = Path.GetDirectoryName(outputPath); - if (!string.IsNullOrEmpty(directoryPath) && !Directory.Exists(directoryPath)) + // 4) Serialize to specified output location or stdout + var outputPath = namedArgs.TryGetValue(OutputOption, out var arg1) ? Path.Combine(Directory.GetCurrentDirectory(), arg1) : null; + if (!string.IsNullOrEmpty(outputPath)) { - Directory.CreateDirectory(directoryPath); + var directoryPath = Path.GetDirectoryName(outputPath); + if (!string.IsNullOrEmpty(directoryPath) && !Directory.Exists(directoryPath)) + { + Directory.CreateDirectory(directoryPath); + } } - } - var exportJson = true; - var exportYml = false; - var exportYaml = false; - if (namedArgs.TryGetValue(FormatOption, out var format)) - { - var splitted = format.Split(',').Select(x => x.Trim()).ToList(); - exportJson = splitted.Any(x => x.Equals("json", StringComparison.OrdinalIgnoreCase)); - exportYml = splitted.Any(x => x.Equals("yml", StringComparison.OrdinalIgnoreCase)); - exportYaml = splitted.Any(x => x.Equals("yaml", StringComparison.OrdinalIgnoreCase)); - } + var exportJson = true; + var exportYml = false; + var exportYaml = false; + if (namedArgs.TryGetValue(FormatOption, out var format)) + { + var splitted = format.Split(',').Select(x => x.Trim()).ToList(); + exportJson = splitted.Any(x => x.Equals("json", StringComparison.OrdinalIgnoreCase)); + exportYml = splitted.Any(x => x.Equals("yml", StringComparison.OrdinalIgnoreCase)); + exportYaml = splitted.Any(x => x.Equals("yaml", StringComparison.OrdinalIgnoreCase)); + } - if (exportJson) - { - WriteFile(AddFileExtension(outputPath, "json"), stream => asyncApiDocument.SerializeAsJson(stream, AsyncApiVersion.AsyncApi2_0)); - } + if (exportJson) + { + WriteFile(AddFileExtension(outputPath, fileTemplate, documentName, "json"), stream => asyncApiDocument.SerializeAsJson(stream, AsyncApiVersion.AsyncApi2_0)); + } - if (exportYml) - { - WriteFile(AddFileExtension(outputPath, "yml"), stream => asyncApiDocument.SerializeAsYaml(stream, AsyncApiVersion.AsyncApi2_0)); - } + if (exportYml) + { + WriteFile(AddFileExtension(outputPath, fileTemplate, documentName, "yml"), stream => asyncApiDocument.SerializeAsYaml(stream, AsyncApiVersion.AsyncApi2_0)); + } - if (exportYaml) - { - WriteFile(AddFileExtension(outputPath, "yaml"), stream => asyncApiDocument.SerializeAsYaml(stream, AsyncApiVersion.AsyncApi2_0)); + if (exportYaml) + { + WriteFile(AddFileExtension(outputPath, fileTemplate, documentName, "yaml"), stream => asyncApiDocument.SerializeAsYaml(stream, AsyncApiVersion.AsyncApi2_0)); + } } return 0; @@ -99,31 +116,14 @@ private static void WriteFile(string outputPath, Action writeAction) } } - private static string AddFileExtension(string outputPath, string extension) + private static string AddFileExtension(string outputPath, string fileTemplate, string documentName, string extension) { if (outputPath == null) { return outputPath; } - if (outputPath.EndsWith(extension, StringComparison.OrdinalIgnoreCase)) - { - return outputPath; - } - - return $"{TrimEnd(outputPath, ".json", ".yml", ".yaml")}.{extension}"; - } - - private static string TrimEnd(string str, params string[] trims) - { - foreach (var trim in trims) - { - if (str.EndsWith(trim, StringComparison.OrdinalIgnoreCase)) - { - str = str[..^trim.Length]; - } - } - return str; + return Path.Combine(outputPath, fileTemplate.Replace("{document}", documentName).Replace("{extension}", extension)); } private static IServiceProvider GetServiceProvider(Assembly startupAssembly) diff --git a/src/AsyncAPI.Saunter.Generator.Cli/Internal/DependencyResolver.cs b/src/AsyncAPI.Saunter.Generator.Cli/Internal/DependencyResolver.cs new file mode 100644 index 00000000..e6ef1bc3 --- /dev/null +++ b/src/AsyncAPI.Saunter.Generator.Cli/Internal/DependencyResolver.cs @@ -0,0 +1,28 @@ +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information. + +using System.Reflection; + +namespace AsyncAPI.Saunter.Generator.Cli.Internal; + +internal static class DependencyResolver +{ + public static void Init() + { + var basePath = Path.GetDirectoryName(typeof(Program).GetTypeInfo().Assembly.Location); + AppDomain.CurrentDomain.AssemblyResolve += (sender, args) => + { + var requestedAssembly = new AssemblyName(args.Name); + var fullPath = Path.Combine(basePath, $"{requestedAssembly.Name}.dll"); + if (File.Exists(fullPath)) + { + var assembly = Assembly.LoadFile(fullPath); + return assembly; + } + + Console.WriteLine($"Could not resolve assembly: {args.Name}, requested by {args.RequestingAssembly?.FullName}"); + return default; + }; + } +} diff --git a/src/AsyncAPI.Saunter.Generator.Cli/Program.cs b/src/AsyncAPI.Saunter.Generator.Cli/Program.cs index 33471b73..4d174c60 100644 --- a/src/AsyncAPI.Saunter.Generator.Cli/Program.cs +++ b/src/AsyncAPI.Saunter.Generator.Cli/Program.cs @@ -1,31 +1,38 @@ using AsyncApi.Saunter.Generator.Cli.Commands; using AsyncApi.Saunter.Generator.Cli.SwashbuckleImport; +using AsyncAPI.Saunter.Generator.Cli.Internal; + +DependencyResolver.Init(); // Helper to simplify command line parsing etc. -var runner = new CommandRunner("dotnet asyncapi", "AsyncAPI Command Line Tools", Console.Out); +var runner = new CommandRunner("dotnet asyncapi.net", "AsyncAPI Command Line Tools", Console.Out); // NOTE: The "dotnet asyncapi tofile" command does not serve the request directly. Instead, it invokes a corresponding // command (called _tofile) via "dotnet exec" so that the runtime configuration (*.runtimeconfig & *.deps.json) of the // provided startupassembly can be used instead of the tool's. This is neccessary to successfully load the // startupassembly and it's transitive dependencies. See https://github.com/dotnet/coreclr/issues/13277 for more. -// > dotnet asyncapi tofile ... +// > dotnet asyncapi.net tofile ... runner.SubCommand("tofile", "retrieves AsyncAPI from a startup assembly, and writes to file ", c => { c.Argument(StartupAssemblyArgument, "relative path to the application's startup assembly"); - c.Argument(DocArgument, "name of the AsyncAPI doc you want to retrieve, as configured in your startup class"); - c.Option(OutputOption, "relative path where the AsyncAPI will be output, defaults to stdout"); - c.Option(FormatOption, "exports AsyncAPI in json and/or yml format [Default json]"); + c.Option(DocOption, "name(s) of the AsyncAPI documents you want to retrieve, as configured in your startup class [defaults to all documents]"); + c.Option(OutputOption, "relative path where the AsyncAPI will be output [defaults to stdout]"); + c.Option(FileNameOption, "defines the file name template, {document} and {extension} template variables can be used [defaults to \"{document}_asyncapi.{extension}\"]"); + c.Option(FormatOption, "exports AsyncAPI in json and/or yml format [defaults to json]"); + c.Option(EnvOption, "define environment variable(s) for the application during generation of the AsyncAPI files [defaults to empty, can be used to define for example ASPNETCORE_ENVIRONMENT]"); c.OnRun(Tofile.Run(args)); }); -// > dotnet asyncapi _tofile ... (* should only be invoked via "dotnet exec") +// > dotnet asyncapi.net _tofile ... (* should only be invoked via "dotnet exec") runner.SubCommand("_tofile", "", c => { c.Argument(StartupAssemblyArgument, ""); - c.Argument(DocArgument, ""); + c.Option(DocOption, ""); c.Option(OutputOption, ""); + c.Option(FileNameOption, ""); c.Option(FormatOption, ""); + c.Option(EnvOption, ""); c.OnRun(TofileInternal.Run); }); diff --git a/src/AsyncAPI.Saunter.Generator.Cli/readme.md b/src/AsyncAPI.Saunter.Generator.Cli/readme.md index afb7f457..6c73c716 100644 --- a/src/AsyncAPI.Saunter.Generator.Cli/readme.md +++ b/src/AsyncAPI.Saunter.Generator.Cli/readme.md @@ -1,13 +1,15 @@ # AsyncApi Generator.Cli Tool +A dotnet tool to generate AsyncAPI specification files based of dotnet DLL (The application itself). ## Tool usage ``` -dotnet asyncapi tofile --output [output-path] --format [json,yml,yaml] [startup-assembly] [asyncapi-document-name] +dotnet asyncapi.net tofile --output [output-path] --format [json,yml,yaml] --doc [asyncapi-document-name] [startup-assembly] ``` - -## Tool options startup-assembly: the file path to the entrypoint dotnet DLL that hosts AsyncAPI document(s). -asyncapi-document-name: (optional) The name of the AsyncAPI document as defined in the startup class by the ```.ConfigureNamedAsyncApi()```-method. If not specified, all documents will be exported. ---output: the output path or the file name. File extension can be omitted, as the --format file determine the file extension. +## Tool options +--doc: The name of the AsyncAPI document as defined in the startup class by the ```.ConfigureNamedAsyncApi()```-method. If not specified, all documents will be exported. +--output: relative path where the AsyncAPI will be output [defaults to stdout] +--filename: the template for the outputted file names. Default: "{document}_asyncapi.{extension}" --format: the output formats to generate, can be a combination of json, yml and/or yaml. File extension is appended to the output path. +--env: define environment variable(s) for the application From 0419101890e3db925295aa449a331517bb19718d Mon Sep 17 00:00:00 2001 From: Senn Geerts Date: Sat, 6 Jul 2024 18:28:04 +0200 Subject: [PATCH 08/23] #196 Test for dotnet cli tool, added support for default asyncapi document --- Saunter.sln | 17 +- .../Commands/TofileInternal.cs | 37 ++- src/AsyncAPI.Saunter.Generator.Cli/readme.md | 10 +- ...syncAPI.Saunter.Generator.Cli.Tests.csproj | 28 +++ .../DotnetCliToolTests.cs | 234 ++++++++++++++++++ 5 files changed, 312 insertions(+), 14 deletions(-) create mode 100644 test/AsyncAPI.Saunter.Generator.Cli.Tests/AsyncAPI.Saunter.Generator.Cli.Tests.csproj create mode 100644 test/AsyncAPI.Saunter.Generator.Cli.Tests/DotnetCliToolTests.cs diff --git a/Saunter.sln b/Saunter.sln index 2aff09fa..43967dd8 100644 --- a/Saunter.sln +++ b/Saunter.sln @@ -29,7 +29,9 @@ Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Saunter.IntegrationTests.Re EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Saunter.Tests.MarkerTypeTests", "test\Saunter.Tests.MarkerTypeTests\Saunter.Tests.MarkerTypeTests.csproj", "{02284473-6DE7-4EE0-8433-2AC295045549}" EndProject -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "AsyncAPI.Saunter.Generator.Cli", "src\AsyncAPI.Saunter.Generator.Cli\AsyncAPI.Saunter.Generator.Cli.csproj", "{6C102D4D-3DA4-4763-B75E-C15E33E7E94A}" +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "AsyncAPI.Saunter.Generator.Cli", "src\AsyncAPI.Saunter.Generator.Cli\AsyncAPI.Saunter.Generator.Cli.csproj", "{6C102D4D-3DA4-4763-B75E-C15E33E7E94A}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "AsyncAPI.Saunter.Generator.Cli.Tests", "test\AsyncAPI.Saunter.Generator.Cli.Tests\AsyncAPI.Saunter.Generator.Cli.Tests.csproj", "{18AD0249-0436-4A26-9972-B97BA6905A54}" EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution @@ -113,6 +115,18 @@ Global {6C102D4D-3DA4-4763-B75E-C15E33E7E94A}.Release|x64.Build.0 = Release|Any CPU {6C102D4D-3DA4-4763-B75E-C15E33E7E94A}.Release|x86.ActiveCfg = Release|Any CPU {6C102D4D-3DA4-4763-B75E-C15E33E7E94A}.Release|x86.Build.0 = Release|Any CPU + {18AD0249-0436-4A26-9972-B97BA6905A54}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {18AD0249-0436-4A26-9972-B97BA6905A54}.Debug|Any CPU.Build.0 = Debug|Any CPU + {18AD0249-0436-4A26-9972-B97BA6905A54}.Debug|x64.ActiveCfg = Debug|Any CPU + {18AD0249-0436-4A26-9972-B97BA6905A54}.Debug|x64.Build.0 = Debug|Any CPU + {18AD0249-0436-4A26-9972-B97BA6905A54}.Debug|x86.ActiveCfg = Debug|Any CPU + {18AD0249-0436-4A26-9972-B97BA6905A54}.Debug|x86.Build.0 = Debug|Any CPU + {18AD0249-0436-4A26-9972-B97BA6905A54}.Release|Any CPU.ActiveCfg = Release|Any CPU + {18AD0249-0436-4A26-9972-B97BA6905A54}.Release|Any CPU.Build.0 = Release|Any CPU + {18AD0249-0436-4A26-9972-B97BA6905A54}.Release|x64.ActiveCfg = Release|Any CPU + {18AD0249-0436-4A26-9972-B97BA6905A54}.Release|x64.Build.0 = Release|Any CPU + {18AD0249-0436-4A26-9972-B97BA6905A54}.Release|x86.ActiveCfg = Release|Any CPU + {18AD0249-0436-4A26-9972-B97BA6905A54}.Release|x86.Build.0 = Release|Any CPU EndGlobalSection GlobalSection(SolutionProperties) = preSolution HideSolutionNode = FALSE @@ -124,6 +138,7 @@ Global {7CD09B89-130A-41AF-ADAE-2166C4ED695B} = {6491E321-2D02-44AB-9116-D722FE169595} {02284473-6DE7-4EE0-8433-2AC295045549} = {6491E321-2D02-44AB-9116-D722FE169595} {6C102D4D-3DA4-4763-B75E-C15E33E7E94A} = {28D4C365-FDED-49AE-A97D-36202E24A55A} + {18AD0249-0436-4A26-9972-B97BA6905A54} = {6491E321-2D02-44AB-9116-D722FE169595} EndGlobalSection GlobalSection(ExtensibilityGlobals) = postSolution SolutionGuid = {2F85D9DA-DBCF-4F13-8C42-5719F1469B2E} diff --git a/src/AsyncAPI.Saunter.Generator.Cli/Commands/TofileInternal.cs b/src/AsyncAPI.Saunter.Generator.Cli/Commands/TofileInternal.cs index 00ea898f..a3477c7a 100644 --- a/src/AsyncAPI.Saunter.Generator.Cli/Commands/TofileInternal.cs +++ b/src/AsyncAPI.Saunter.Generator.Cli/Commands/TofileInternal.cs @@ -15,12 +15,16 @@ using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore; using Microsoft.Extensions.Hosting; +using Saunter.AsyncApiSchema.v2; using static Program; +using AsyncApiDocument = Saunter.AsyncApiSchema.v2.AsyncApiDocument; namespace AsyncApi.Saunter.Generator.Cli.Commands; internal class TofileInternal { + private const string defaultDocumentName = null; + internal static int Run(IDictionary namedArgs) { // 1) Configure host with provided startupassembly @@ -43,24 +47,41 @@ internal static int Run(IDictionary namedArgs) // 3) Retrieve AsyncAPI via configured provider var documentProvider = serviceProvider.GetService(); - var asyncapiOptions = serviceProvider.GetService>(); + var asyncapiOptions = serviceProvider.GetService>().Value; var documentSerializer = serviceProvider.GetRequiredService(); - var documentNames = namedArgs.TryGetValue(DocOption, out var doc) ? [doc] : asyncapiOptions.Value.NamedApis.Keys; + var documentNames = namedArgs.TryGetValue(DocOption, out var doc) ? [doc] : asyncapiOptions.NamedApis.Keys; var fileTemplate = namedArgs.TryGetValue(FileNameOption, out var template) ? template : "{document}_asyncapi.{extension}"; + if (documentNames.Count == 0) + { + if (asyncapiOptions.AssemblyMarkerTypes.Any()) + { + documentNames = [defaultDocumentName]; + } + else + { + throw new ArgumentOutOfRangeException(DocOption, $"No AsyncAPI documents found: {DocOption} = '{doc}'. Known document(s): {string.Join(", ", asyncapiOptions.NamedApis.Keys)}."); + } + } + foreach (var documentName in documentNames) { - if (!asyncapiOptions.Value.NamedApis.TryGetValue(documentName, out var prototype)) + AsyncApiDocument prototype; + if (documentName == defaultDocumentName) + { + prototype = asyncapiOptions.AsyncApi; + } + else if (!asyncapiOptions.NamedApis.TryGetValue(documentName, out prototype)) { - throw new ArgumentOutOfRangeException(DocOption, documentName, $"Requested AsyncAPI document not found: '{documentName}'. Known document(s): {string.Join(", ", asyncapiOptions.Value.NamedApis.Keys)}."); + throw new ArgumentOutOfRangeException(DocOption, documentName, $"Requested AsyncAPI document not found: '{documentName}'. Known document(s): {string.Join(", ", asyncapiOptions.NamedApis.Keys)}."); } - var asyncApiSchema = documentProvider.GetDocument(asyncapiOptions.Value, prototype); - var asyncApiSchemaJson = documentSerializer.Serialize(asyncApiSchema); + var schema = documentProvider.GetDocument(asyncapiOptions, prototype); + var asyncApiSchemaJson = documentSerializer.Serialize(schema); var asyncApiDocument = new AsyncApiStringReader().Read(asyncApiSchemaJson, out var diagnostic); if (diagnostic.Errors.Any()) { - Console.Error.WriteLine($"AsyncAPI Schema '{documentName}' is not valid ({diagnostic.Errors.Count} Error(s), {diagnostic.Warnings.Count} Warning(s)):" + + Console.Error.WriteLine($"AsyncAPI Schema '{documentName ?? "default"}' is not valid ({diagnostic.Errors.Count} Error(s), {diagnostic.Warnings.Count} Warning(s)):" + $"{Environment.NewLine}{string.Join(Environment.NewLine, diagnostic.Errors.Select(x => $"- {x}"))}"); } @@ -123,7 +144,7 @@ private static string AddFileExtension(string outputPath, string fileTemplate, s return outputPath; } - return Path.Combine(outputPath, fileTemplate.Replace("{document}", documentName).Replace("{extension}", extension)); + return Path.Combine(outputPath, fileTemplate.Replace("{document}", documentName == defaultDocumentName ? "" : documentName).Replace("{extension}", extension).TrimStart('_')); } private static IServiceProvider GetServiceProvider(Assembly startupAssembly) diff --git a/src/AsyncAPI.Saunter.Generator.Cli/readme.md b/src/AsyncAPI.Saunter.Generator.Cli/readme.md index 6c73c716..11d3c9b4 100644 --- a/src/AsyncAPI.Saunter.Generator.Cli/readme.md +++ b/src/AsyncAPI.Saunter.Generator.Cli/readme.md @@ -8,8 +8,8 @@ dotnet asyncapi.net tofile --output [output-path] --format [json,yml,yaml] --doc startup-assembly: the file path to the entrypoint dotnet DLL that hosts AsyncAPI document(s). ## Tool options ---doc: The name of the AsyncAPI document as defined in the startup class by the ```.ConfigureNamedAsyncApi()```-method. If not specified, all documents will be exported. ---output: relative path where the AsyncAPI will be output [defaults to stdout] ---filename: the template for the outputted file names. Default: "{document}_asyncapi.{extension}" ---format: the output formats to generate, can be a combination of json, yml and/or yaml. File extension is appended to the output path. ---env: define environment variable(s) for the application +--doc: The name of the AsyncAPI document as defined in the startup class by the ```.ConfigureNamedAsyncApi()```-method. If not specified, all documents will be exported. +--output: relative path where the AsyncAPI will be output [defaults to stdout] +--filename: the template for the outputted file names. Default: "{document}_asyncapi.{extension}" +--format: the output formats to generate, can be a combination of json, yml and/or yaml. File extension is appended to the output path. +--env: define environment variable(s) for the application diff --git a/test/AsyncAPI.Saunter.Generator.Cli.Tests/AsyncAPI.Saunter.Generator.Cli.Tests.csproj b/test/AsyncAPI.Saunter.Generator.Cli.Tests/AsyncAPI.Saunter.Generator.Cli.Tests.csproj new file mode 100644 index 00000000..8d3e969c --- /dev/null +++ b/test/AsyncAPI.Saunter.Generator.Cli.Tests/AsyncAPI.Saunter.Generator.Cli.Tests.csproj @@ -0,0 +1,28 @@ + + + + net8.0 + enable + enable + + false + true + + + + + + + + + + + + + + + + + + + diff --git a/test/AsyncAPI.Saunter.Generator.Cli.Tests/DotnetCliToolTests.cs b/test/AsyncAPI.Saunter.Generator.Cli.Tests/DotnetCliToolTests.cs new file mode 100644 index 00000000..3d6c7324 --- /dev/null +++ b/test/AsyncAPI.Saunter.Generator.Cli.Tests/DotnetCliToolTests.cs @@ -0,0 +1,234 @@ +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information. + +using System.Diagnostics; +using Shouldly; +using Xunit.Abstractions; + +namespace AsyncAPI.Saunter.Generator.Cli.Tests; + +public class DotnetCliToolTests(ITestOutputHelper output) +{ + private string RunTool(string args, int expectedExitCode = 0) + { + var process = Process.Start(new ProcessStartInfo("dotnet") + { + Arguments = $"../../../../../src/AsyncAPI.Saunter.Generator.Cli/bin/Debug/net6.0/AsyncAPI.Saunter.Generator.Cli.dll tofile {args}", + RedirectStandardOutput = true, + RedirectStandardError = true, + }); + process.WaitForExit(); + var stdOut = process.StandardOutput.ReadToEnd().Trim(); + var stdError = process.StandardError.ReadToEnd().Trim(); + output.WriteLine(stdOut); + output.WriteLine(stdError); + + process.ExitCode.ShouldBe(expectedExitCode); + //stdError.ShouldBeEmpty(); LEGO lib doesn't like id: "id is not a valid property at #/components/schemas/lightMeasuredEvent"" + return stdOut; + } + + [Fact] + public void DefaultCallPrintsCommandInfo() + { + var stdOut = RunTool("", 1); + + stdOut.ShouldBe(""" + Usage: dotnet asyncapi.net tofile [options] [startupassembly] + + startupassembly: + relative path to the application's startup assembly + + options: + --doc: name(s) of the AsyncAPI documents you want to retrieve, as configured in your startup class [defaults to all documents] + --output: relative path where the AsyncAPI will be output [defaults to stdout] + --filename: defines the file name template, {document} and {extension} template variables can be used [defaults to "{document}_asyncapi.{extension}"] + --format: exports AsyncAPI in json and/or yml format [defaults to json] + --env: define environment variable(s) for the application during generation of the AsyncAPI files [defaults to empty, can be used to define for example ASPNETCORE_ENVIRONMENT] + """, StringCompareShould.IgnoreLineEndings); + } + + [Fact] + public void StreetlightsAPIExportSpecTest() + { + var path = Directory.GetCurrentDirectory(); + output.WriteLine($"Output path: {path}"); + var stdOut = RunTool($"--output {path} --format json,yml,yaml ../../../../../examples/StreetlightsAPI/bin/Debug/net6.0/StreetlightsAPI.dll"); + + stdOut.ShouldNotBeEmpty(); + stdOut.ShouldContain($"AsyncAPI yaml successfully written to {Path.Combine(path, "asyncapi.yaml")}"); + stdOut.ShouldContain($"AsyncAPI yml successfully written to {Path.Combine(path, "asyncapi.yml")}"); + stdOut.ShouldContain($"AsyncAPI json successfully written to {Path.Combine(path, "asyncapi.json")}"); + + File.Exists("asyncapi.yml").ShouldBeTrue("asyncapi.yml"); + File.Exists("asyncapi.yaml").ShouldBeTrue("asyncapi.yaml"); + File.Exists("asyncapi.json").ShouldBeTrue("asyncapi.json"); + + var yml = File.ReadAllText("asyncapi.yml"); + yml.ShouldBe(""" + asyncapi: 2.6.0 + info: + title: Streetlights API + version: 1.0.0 + description: The Smartylighting Streetlights API allows you to remotely manage the city lights. + license: + name: Apache 2.0 + url: https://www.apache.org/licenses/LICENSE-2.0 + servers: + mosquitto: + url: test.mosquitto.org + protocol: mqtt + webapi: + url: localhost:5000 + protocol: http + defaultContentType: application/json + channels: + publish/light/measured: + servers: + - webapi + publish: + operationId: MeasureLight + summary: Inform about environmental lighting conditions for a particular streetlight. + tags: + - name: Light + message: + $ref: '#/components/messages/lightMeasuredEvent' + subscribe/light/measured: + servers: + - mosquitto + subscribe: + operationId: PublishLightMeasurement + summary: Subscribe to environmental lighting conditions for a particular streetlight. + tags: + - name: Light + message: + payload: + $ref: '#/components/schemas/lightMeasuredEvent' + components: + schemas: + lightMeasuredEvent: + type: object + properties: + id: + type: integer + format: int32 + description: Id of the streetlight. + lumens: + type: integer + format: int32 + description: Light intensity measured in lumens. + sentAt: + type: string + format: date-time + description: Light intensity measured in lumens. + additionalProperties: false + messages: + lightMeasuredEvent: + payload: + $ref: '#/components/schemas/lightMeasuredEvent' + name: lightMeasuredEvent + """, "yaml"); + + var yaml = File.ReadAllText("asyncapi.yaml"); + yaml.ShouldBe(yml, "yml"); + + var json = File.ReadAllText("asyncapi.json"); + json.ShouldBe(""" + { + "asyncapi": "2.6.0", + "info": { + "title": "Streetlights API", + "version": "1.0.0", + "description": "The Smartylighting Streetlights API allows you to remotely manage the city lights.", + "license": { + "name": "Apache 2.0", + "url": "https://www.apache.org/licenses/LICENSE-2.0" + } + }, + "servers": { + "mosquitto": { + "url": "test.mosquitto.org", + "protocol": "mqtt" + }, + "webapi": { + "url": "localhost:5000", + "protocol": "http" + } + }, + "defaultContentType": "application/json", + "channels": { + "publish/light/measured": { + "servers": [ + "webapi" + ], + "publish": { + "operationId": "MeasureLight", + "summary": "Inform about environmental lighting conditions for a particular streetlight.", + "tags": [ + { + "name": "Light" + } + ], + "message": { + "$ref": "#/components/messages/lightMeasuredEvent" + } + } + }, + "subscribe/light/measured": { + "servers": [ + "mosquitto" + ], + "subscribe": { + "operationId": "PublishLightMeasurement", + "summary": "Subscribe to environmental lighting conditions for a particular streetlight.", + "tags": [ + { + "name": "Light" + } + ], + "message": { + "payload": { + "$ref": "#/components/schemas/lightMeasuredEvent" + } + } + } + } + }, + "components": { + "schemas": { + "lightMeasuredEvent": { + "type": "object", + "properties": { + "id": { + "type": "integer", + "format": "int32", + "description": "Id of the streetlight." + }, + "lumens": { + "type": "integer", + "format": "int32", + "description": "Light intensity measured in lumens." + }, + "sentAt": { + "type": "string", + "format": "date-time", + "description": "Light intensity measured in lumens." + } + }, + "additionalProperties": false + } + }, + "messages": { + "lightMeasuredEvent": { + "payload": { + "$ref": "#/components/schemas/lightMeasuredEvent" + }, + "name": "lightMeasuredEvent" + } + } + } + } + """, "json"); + } +} From b29a1ab720d7ed962b527bbf12bd43251b9982c2 Mon Sep 17 00:00:00 2001 From: Senn Geerts Date: Sat, 6 Jul 2024 19:31:17 +0200 Subject: [PATCH 09/23] #196 Pack_Install_Run_Uninstall Test --- ...syncAPI.Saunter.Generator.Cli.Tests.csproj | 6 ++ .../PackAndInstallLocalTests.cs | 56 +++++++++++++++++++ .../asyncapi.cmd | 1 + 3 files changed, 63 insertions(+) create mode 100644 test/AsyncAPI.Saunter.Generator.Cli.Tests/PackAndInstallLocalTests.cs create mode 100644 test/AsyncAPI.Saunter.Generator.Cli.Tests/asyncapi.cmd diff --git a/test/AsyncAPI.Saunter.Generator.Cli.Tests/AsyncAPI.Saunter.Generator.Cli.Tests.csproj b/test/AsyncAPI.Saunter.Generator.Cli.Tests/AsyncAPI.Saunter.Generator.Cli.Tests.csproj index 8d3e969c..c1b63ddd 100644 --- a/test/AsyncAPI.Saunter.Generator.Cli.Tests/AsyncAPI.Saunter.Generator.Cli.Tests.csproj +++ b/test/AsyncAPI.Saunter.Generator.Cli.Tests/AsyncAPI.Saunter.Generator.Cli.Tests.csproj @@ -25,4 +25,10 @@ + + + PreserveNewest + + + diff --git a/test/AsyncAPI.Saunter.Generator.Cli.Tests/PackAndInstallLocalTests.cs b/test/AsyncAPI.Saunter.Generator.Cli.Tests/PackAndInstallLocalTests.cs new file mode 100644 index 00000000..fe082871 --- /dev/null +++ b/test/AsyncAPI.Saunter.Generator.Cli.Tests/PackAndInstallLocalTests.cs @@ -0,0 +1,56 @@ +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information. + +using System.Diagnostics; +using Shouldly; +using Xunit.Abstractions; + +namespace AsyncAPI.Saunter.Generator.Cli.Tests; + +public class PackAndInstallLocalTests(ITestOutputHelper output) +{ + private string Run(string file, string args, string workingDirectory, int expectedExitCode = 0) + { + var process = Process.Start(new ProcessStartInfo(file) + { + Arguments = args, + WorkingDirectory = workingDirectory, + RedirectStandardOutput = true, + RedirectStandardError = true, + UseShellExecute = false, + }); + process.WaitForExit(TimeSpan.FromSeconds(20)); + var stdOut = process.StandardOutput.ReadToEnd().Trim(); + var stdError = process.StandardError.ReadToEnd().Trim(); + output.WriteLine($"### Output of \"{file} {args}\""); + output.WriteLine(stdOut); + output.WriteLine(stdError); + + process.ExitCode.ShouldBe(expectedExitCode); + return stdOut; + } + + [Fact] + public void Pack_Install_Run_Uninstall_Test() + { + var stdOut = this.Run("dotnet", "pack", "../../../../../src/AsyncAPI.Saunter.Generator.Cli"); + stdOut.ShouldContain("Successfully created package"); + + stdOut = this.Run("dotnet", "tool install --global --add-source ./bin/release AsyncAPI.Saunter.Generator.Cli", "../../../../../src/AsyncAPI.Saunter.Generator.Cli"); + stdOut.ShouldBeOneOf("You can invoke the tool using the following command: AsyncAPI.NET\r\nTool 'asyncapi.saunter.generator.cli' (version '1.0.0') was successfully installed.", + "Tool 'asyncapi.saunter.generator.cli' was reinstalled with the stable version (version '1.0.0')."); + + stdOut = this.Run("dotnet", "tool list -g asyncapi.saunter.generator.cli", ""); + stdOut.ShouldContain("AsyncAPI.NET"); + + stdOut = this.Run("asyncapi.cmd", "", "", 1); + stdOut.ShouldContain("tofile: retrieves AsyncAPI from a startup assembly, and writes to file"); + + stdOut = this.Run("dotnet", "tool uninstall -g asyncapi.saunter.generator.cli", ""); + stdOut.ShouldContain(" was successfully uninstalled."); + + stdOut = this.Run("dotnet", "tool list -g asyncapi.saunter.generator.cli", "", 1); + stdOut.ShouldNotContain("AsyncAPI.NET"); + } +} diff --git a/test/AsyncAPI.Saunter.Generator.Cli.Tests/asyncapi.cmd b/test/AsyncAPI.Saunter.Generator.Cli.Tests/asyncapi.cmd new file mode 100644 index 00000000..b75bbd67 --- /dev/null +++ b/test/AsyncAPI.Saunter.Generator.Cli.Tests/asyncapi.cmd @@ -0,0 +1 @@ +AsyncAPI.NET \ No newline at end of file From 12593dce086296dce363b6384889077ceca13f5b Mon Sep 17 00:00:00 2001 From: Senn Geerts Date: Sat, 6 Jul 2024 19:31:17 +0200 Subject: [PATCH 10/23] #196 Pack_Install_Run_Uninstall fix casing in test, add meta data to package --- .../AsyncAPI.Saunter.Generator.Cli.csproj | 19 ++++++- ...syncAPI.Saunter.Generator.Cli.Tests.csproj | 6 ++ .../PackAndInstallLocalTests.cs | 56 +++++++++++++++++++ .../asyncapi.cmd | 1 + 4 files changed, 79 insertions(+), 3 deletions(-) create mode 100644 test/AsyncAPI.Saunter.Generator.Cli.Tests/PackAndInstallLocalTests.cs create mode 100644 test/AsyncAPI.Saunter.Generator.Cli.Tests/asyncapi.cmd diff --git a/src/AsyncAPI.Saunter.Generator.Cli/AsyncAPI.Saunter.Generator.Cli.csproj b/src/AsyncAPI.Saunter.Generator.Cli/AsyncAPI.Saunter.Generator.Cli.csproj index 63a8b166..3b07d834 100644 --- a/src/AsyncAPI.Saunter.Generator.Cli/AsyncAPI.Saunter.Generator.Cli.csproj +++ b/src/AsyncAPI.Saunter.Generator.Cli/AsyncAPI.Saunter.Generator.Cli.csproj @@ -2,16 +2,24 @@ Exe + net8.0;net6.0 enable 12 AsyncAPI.Saunter.Generator.Cli AsyncAPI Command Line Tools - Exe + AsyncAPI Initiative true AsyncAPI.Saunter.Generator.Cli AsyncAPI.NET - net8.0;net6.0 + asyncapi;aspnetcore;openapi;documentation;amqp;generator;cli;tool + readme.md + logo.png + https://github.com/asyncapi/saunter + true + https://github.com/asyncapi/saunter + MIT + false @@ -25,5 +33,10 @@ - + + + + + + diff --git a/test/AsyncAPI.Saunter.Generator.Cli.Tests/AsyncAPI.Saunter.Generator.Cli.Tests.csproj b/test/AsyncAPI.Saunter.Generator.Cli.Tests/AsyncAPI.Saunter.Generator.Cli.Tests.csproj index 8d3e969c..c1b63ddd 100644 --- a/test/AsyncAPI.Saunter.Generator.Cli.Tests/AsyncAPI.Saunter.Generator.Cli.Tests.csproj +++ b/test/AsyncAPI.Saunter.Generator.Cli.Tests/AsyncAPI.Saunter.Generator.Cli.Tests.csproj @@ -25,4 +25,10 @@ + + + PreserveNewest + + + diff --git a/test/AsyncAPI.Saunter.Generator.Cli.Tests/PackAndInstallLocalTests.cs b/test/AsyncAPI.Saunter.Generator.Cli.Tests/PackAndInstallLocalTests.cs new file mode 100644 index 00000000..34930f30 --- /dev/null +++ b/test/AsyncAPI.Saunter.Generator.Cli.Tests/PackAndInstallLocalTests.cs @@ -0,0 +1,56 @@ +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information. + +using System.Diagnostics; +using Shouldly; +using Xunit.Abstractions; + +namespace AsyncAPI.Saunter.Generator.Cli.Tests; + +public class PackAndInstallLocalTests(ITestOutputHelper output) +{ + private string Run(string file, string args, string workingDirectory, int expectedExitCode = 0) + { + var process = Process.Start(new ProcessStartInfo(file) + { + Arguments = args, + WorkingDirectory = workingDirectory, + RedirectStandardOutput = true, + RedirectStandardError = true, + UseShellExecute = false, + }); + process.WaitForExit(TimeSpan.FromSeconds(20)); + var stdOut = process.StandardOutput.ReadToEnd().Trim(); + var stdError = process.StandardError.ReadToEnd().Trim(); + output.WriteLine($"### Output of \"{file} {args}\""); + output.WriteLine(stdOut); + output.WriteLine(stdError); + + process.ExitCode.ShouldBe(expectedExitCode); + return stdOut; + } + + [Fact] + public void Pack_Install_Run_Uninstall_Test() + { + var stdOut = this.Run("dotnet", "pack", "../../../../../src/AsyncAPI.Saunter.Generator.Cli"); + stdOut.ShouldContain("Successfully created package"); + + stdOut = this.Run("dotnet", "tool install --global --add-source ./bin/Release AsyncAPI.Saunter.Generator.Cli", "../../../../../src/AsyncAPI.Saunter.Generator.Cli"); + stdOut.ShouldBeOneOf("You can invoke the tool using the following command: AsyncAPI.NET\r\nTool 'asyncapi.saunter.generator.cli' (version '1.0.0') was successfully installed.", + "Tool 'asyncapi.saunter.generator.cli' was reinstalled with the stable version (version '1.0.0')."); + + stdOut = this.Run("dotnet", "tool list -g asyncapi.saunter.generator.cli", ""); + stdOut.ShouldContain("AsyncAPI.NET"); + + stdOut = this.Run("asyncapi.cmd", "", "", 1); + stdOut.ShouldContain("tofile: retrieves AsyncAPI from a startup assembly, and writes to file"); + + stdOut = this.Run("dotnet", "tool uninstall -g asyncapi.saunter.generator.cli", ""); + stdOut.ShouldContain(" was successfully uninstalled."); + + stdOut = this.Run("dotnet", "tool list -g asyncapi.saunter.generator.cli", "", 1); + stdOut.ShouldNotContain("AsyncAPI.NET"); + } +} diff --git a/test/AsyncAPI.Saunter.Generator.Cli.Tests/asyncapi.cmd b/test/AsyncAPI.Saunter.Generator.Cli.Tests/asyncapi.cmd new file mode 100644 index 00000000..b75bbd67 --- /dev/null +++ b/test/AsyncAPI.Saunter.Generator.Cli.Tests/asyncapi.cmd @@ -0,0 +1 @@ +AsyncAPI.NET \ No newline at end of file From e70166076b8e3fff1108c4e963ff87876c66610a Mon Sep 17 00:00:00 2001 From: Senn Geerts Date: Sat, 6 Jul 2024 19:53:57 +0200 Subject: [PATCH 11/23] #196 fix warnings, fix permission --- .../AsyncAPI.Saunter.Generator.Cli.Tests.csproj | 1 - test/AsyncAPI.Saunter.Generator.Cli.Tests/asyncapi.cmd | 0 2 files changed, 1 deletion(-) mode change 100644 => 100755 test/AsyncAPI.Saunter.Generator.Cli.Tests/asyncapi.cmd diff --git a/test/AsyncAPI.Saunter.Generator.Cli.Tests/AsyncAPI.Saunter.Generator.Cli.Tests.csproj b/test/AsyncAPI.Saunter.Generator.Cli.Tests/AsyncAPI.Saunter.Generator.Cli.Tests.csproj index c1b63ddd..3a1e115b 100644 --- a/test/AsyncAPI.Saunter.Generator.Cli.Tests/AsyncAPI.Saunter.Generator.Cli.Tests.csproj +++ b/test/AsyncAPI.Saunter.Generator.Cli.Tests/AsyncAPI.Saunter.Generator.Cli.Tests.csproj @@ -3,7 +3,6 @@ net8.0 enable - enable false true diff --git a/test/AsyncAPI.Saunter.Generator.Cli.Tests/asyncapi.cmd b/test/AsyncAPI.Saunter.Generator.Cli.Tests/asyncapi.cmd old mode 100644 new mode 100755 From d9b558c24435ac03fb74e81b27a97026fd48fedb Mon Sep 17 00:00:00 2001 From: Senn Geerts Date: Sat, 6 Jul 2024 19:57:40 +0200 Subject: [PATCH 12/23] #196 unix needs a shebang --- test/AsyncAPI.Saunter.Generator.Cli.Tests/asyncapi.cmd | 1 + 1 file changed, 1 insertion(+) diff --git a/test/AsyncAPI.Saunter.Generator.Cli.Tests/asyncapi.cmd b/test/AsyncAPI.Saunter.Generator.Cli.Tests/asyncapi.cmd index b75bbd67..1f61f620 100755 --- a/test/AsyncAPI.Saunter.Generator.Cli.Tests/asyncapi.cmd +++ b/test/AsyncAPI.Saunter.Generator.Cli.Tests/asyncapi.cmd @@ -1 +1,2 @@ +#!/bin/bash AsyncAPI.NET \ No newline at end of file From f0af6d1ce920145af1a0bb43db5a60398bef476d Mon Sep 17 00:00:00 2001 From: Senn Geerts Date: Sat, 6 Jul 2024 20:04:13 +0200 Subject: [PATCH 13/23] #196 sourcelink properties --- .../AsyncAPI.Saunter.Generator.Cli.csproj | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/src/AsyncAPI.Saunter.Generator.Cli/AsyncAPI.Saunter.Generator.Cli.csproj b/src/AsyncAPI.Saunter.Generator.Cli/AsyncAPI.Saunter.Generator.Cli.csproj index 3b07d834..0400c5ab 100644 --- a/src/AsyncAPI.Saunter.Generator.Cli/AsyncAPI.Saunter.Generator.Cli.csproj +++ b/src/AsyncAPI.Saunter.Generator.Cli/AsyncAPI.Saunter.Generator.Cli.csproj @@ -17,9 +17,12 @@ logo.png https://github.com/asyncapi/saunter true + true https://github.com/asyncapi/saunter MIT false + true + snupkg @@ -28,6 +31,9 @@ + + + From a379a3e47a7fdbc23aa2dc5d2c3d044fac89e1e4 Mon Sep 17 00:00:00 2001 From: Senn Geerts Date: Sun, 7 Jul 2024 00:32:09 +0200 Subject: [PATCH 14/23] #197 Produce AsyncAPI documents at build time --- Saunter.sln | 17 ++++- examples/StreetlightsAPI/.gitignore | 1 + .../StreetlightsAPI/StreetlightsAPI.csproj | 4 ++ .../AsyncAPI.Saunter.Generator.Build.csproj | 63 +++++++++++++++++++ .../AsyncAPI.Saunter.Generator.Build.props | 11 ++++ .../AsyncAPI.Saunter.Generator.Build.targets | 17 +++++ .../readme.md | 27 ++++++++ .../AsyncAPI.Saunter.Generator.Cli.csproj | 2 +- .../Commands/Tofile.cs | 2 +- .../Commands/TofileInternal.cs | 17 +++-- .../SwashbuckleImport/CommandRunner.cs | 1 + 11 files changed, 149 insertions(+), 13 deletions(-) create mode 100644 examples/StreetlightsAPI/.gitignore create mode 100644 src/AsyncAPI.Saunter.Generator.Build/AsyncAPI.Saunter.Generator.Build.csproj create mode 100644 src/AsyncAPI.Saunter.Generator.Build/build/AsyncAPI.Saunter.Generator.Build.props create mode 100644 src/AsyncAPI.Saunter.Generator.Build/build/AsyncAPI.Saunter.Generator.Build.targets create mode 100644 src/AsyncAPI.Saunter.Generator.Build/readme.md diff --git a/Saunter.sln b/Saunter.sln index 43967dd8..c746b5ea 100644 --- a/Saunter.sln +++ b/Saunter.sln @@ -31,7 +31,9 @@ Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Saunter.Tests.MarkerTypeTes EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "AsyncAPI.Saunter.Generator.Cli", "src\AsyncAPI.Saunter.Generator.Cli\AsyncAPI.Saunter.Generator.Cli.csproj", "{6C102D4D-3DA4-4763-B75E-C15E33E7E94A}" EndProject -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "AsyncAPI.Saunter.Generator.Cli.Tests", "test\AsyncAPI.Saunter.Generator.Cli.Tests\AsyncAPI.Saunter.Generator.Cli.Tests.csproj", "{18AD0249-0436-4A26-9972-B97BA6905A54}" +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "AsyncAPI.Saunter.Generator.Cli.Tests", "test\AsyncAPI.Saunter.Generator.Cli.Tests\AsyncAPI.Saunter.Generator.Cli.Tests.csproj", "{18AD0249-0436-4A26-9972-B97BA6905A54}" +EndProject +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "AsyncAPI.Saunter.Generator.Build", "src\AsyncAPI.Saunter.Generator.Build\AsyncAPI.Saunter.Generator.Build.csproj", "{A320E670-5CB0-4815-AF67-D8D09FC92A2A}" EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution @@ -127,6 +129,18 @@ Global {18AD0249-0436-4A26-9972-B97BA6905A54}.Release|x64.Build.0 = Release|Any CPU {18AD0249-0436-4A26-9972-B97BA6905A54}.Release|x86.ActiveCfg = Release|Any CPU {18AD0249-0436-4A26-9972-B97BA6905A54}.Release|x86.Build.0 = Release|Any CPU + {A320E670-5CB0-4815-AF67-D8D09FC92A2A}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {A320E670-5CB0-4815-AF67-D8D09FC92A2A}.Debug|Any CPU.Build.0 = Debug|Any CPU + {A320E670-5CB0-4815-AF67-D8D09FC92A2A}.Debug|x64.ActiveCfg = Debug|Any CPU + {A320E670-5CB0-4815-AF67-D8D09FC92A2A}.Debug|x64.Build.0 = Debug|Any CPU + {A320E670-5CB0-4815-AF67-D8D09FC92A2A}.Debug|x86.ActiveCfg = Debug|Any CPU + {A320E670-5CB0-4815-AF67-D8D09FC92A2A}.Debug|x86.Build.0 = Debug|Any CPU + {A320E670-5CB0-4815-AF67-D8D09FC92A2A}.Release|Any CPU.ActiveCfg = Release|Any CPU + {A320E670-5CB0-4815-AF67-D8D09FC92A2A}.Release|Any CPU.Build.0 = Release|Any CPU + {A320E670-5CB0-4815-AF67-D8D09FC92A2A}.Release|x64.ActiveCfg = Release|Any CPU + {A320E670-5CB0-4815-AF67-D8D09FC92A2A}.Release|x64.Build.0 = Release|Any CPU + {A320E670-5CB0-4815-AF67-D8D09FC92A2A}.Release|x86.ActiveCfg = Release|Any CPU + {A320E670-5CB0-4815-AF67-D8D09FC92A2A}.Release|x86.Build.0 = Release|Any CPU EndGlobalSection GlobalSection(SolutionProperties) = preSolution HideSolutionNode = FALSE @@ -139,6 +153,7 @@ Global {02284473-6DE7-4EE0-8433-2AC295045549} = {6491E321-2D02-44AB-9116-D722FE169595} {6C102D4D-3DA4-4763-B75E-C15E33E7E94A} = {28D4C365-FDED-49AE-A97D-36202E24A55A} {18AD0249-0436-4A26-9972-B97BA6905A54} = {6491E321-2D02-44AB-9116-D722FE169595} + {A320E670-5CB0-4815-AF67-D8D09FC92A2A} = {28D4C365-FDED-49AE-A97D-36202E24A55A} EndGlobalSection GlobalSection(ExtensibilityGlobals) = postSolution SolutionGuid = {2F85D9DA-DBCF-4F13-8C42-5719F1469B2E} diff --git a/examples/StreetlightsAPI/.gitignore b/examples/StreetlightsAPI/.gitignore new file mode 100644 index 00000000..78c834f3 --- /dev/null +++ b/examples/StreetlightsAPI/.gitignore @@ -0,0 +1 @@ +specs/ \ No newline at end of file diff --git a/examples/StreetlightsAPI/StreetlightsAPI.csproj b/examples/StreetlightsAPI/StreetlightsAPI.csproj index 43f0b54f..3185dffc 100644 --- a/examples/StreetlightsAPI/StreetlightsAPI.csproj +++ b/examples/StreetlightsAPI/StreetlightsAPI.csproj @@ -3,6 +3,10 @@ net6.0 false + true + json,yml + streetlights.{extension} + specs diff --git a/src/AsyncAPI.Saunter.Generator.Build/AsyncAPI.Saunter.Generator.Build.csproj b/src/AsyncAPI.Saunter.Generator.Build/AsyncAPI.Saunter.Generator.Build.csproj new file mode 100644 index 00000000..e9591e8b --- /dev/null +++ b/src/AsyncAPI.Saunter.Generator.Build/AsyncAPI.Saunter.Generator.Build.csproj @@ -0,0 +1,63 @@ + + + + net6.0;net8.0 + enable + 12 + true + + AsyncAPI Build Tools + AsyncAPI Initiative + AsyncAPI.Saunter.Generator.Build + asyncapi;aspnetcore;openapi;documentation;amqp;generator;build;tool + readme.md + logo.png + https://github.com/asyncapi/saunter + true + true + false + false + https://github.com/asyncapi/saunter + MIT + false + 0.0.24 + tools/$(Configuration) + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/src/AsyncAPI.Saunter.Generator.Build/build/AsyncAPI.Saunter.Generator.Build.props b/src/AsyncAPI.Saunter.Generator.Build/build/AsyncAPI.Saunter.Generator.Build.props new file mode 100644 index 00000000..f59b5b6e --- /dev/null +++ b/src/AsyncAPI.Saunter.Generator.Build/build/AsyncAPI.Saunter.Generator.Build.props @@ -0,0 +1,11 @@ + + + + true + json + ./ + + + + + \ No newline at end of file diff --git a/src/AsyncAPI.Saunter.Generator.Build/build/AsyncAPI.Saunter.Generator.Build.targets b/src/AsyncAPI.Saunter.Generator.Build/build/AsyncAPI.Saunter.Generator.Build.targets new file mode 100644 index 00000000..19f35357 --- /dev/null +++ b/src/AsyncAPI.Saunter.Generator.Build/build/AsyncAPI.Saunter.Generator.Build.targets @@ -0,0 +1,17 @@ + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/src/AsyncAPI.Saunter.Generator.Build/readme.md b/src/AsyncAPI.Saunter.Generator.Build/readme.md new file mode 100644 index 00000000..6b5971d1 --- /dev/null +++ b/src/AsyncAPI.Saunter.Generator.Build/readme.md @@ -0,0 +1,27 @@ +# AsyncApi Generator.Build Nuget Package +A nuget package to generate AsyncAPI specification files at build time, based on code-first attributes. + +# Customizations +The AsyncAPI spec generation can be configured through properties in the csproj-file (or .props files): +``` + + + + + + + + +``` + +Defaults are the same as the underlying [Generator.Cli tool](https://www.nuget.org/packages/AsyncAPI.Saunter.Generator.Cli). + +If the ```AsyncAPI.Saunter.Generator.Build``` Nuget package is referenced, the default is to generate AsyncAPI spec files at build time. + +- AsyncAPIGenerateDocumentsOnBuild: Whether to actually generate AsyncAPI spec files on build (true or false, default: true) +- AsyncAPIDocumentFormats: Format of the expected AsyncAPI spec files (json, yml or yaml, default: json) +- AsyncAPIDocumentOutputPath: Output path for the AsyncAPI spec files, relative to the csproj location. (default is the csproj root path: ./) +- AsyncAPIDocumentNames: The AsyncAPI documents to generate. (default: generate all known documents) +- AsyncAPIDocumentFilename: Template of the AsyncAPI spec files (default: "{document}_asyncapi.{extension}") +- AsyncAPIDocumentEnvVars: Environment variable(s) to set during generation of the AsyncAPI spec files (default: none, Example: "ASPNETCORE_ENVIRONMENT=Development") +None of these properties are mandatory. By only referencing the [AsyncAPI.Saunter.Generator.Build](https://www.nuget.org/packages/AsyncAPI.Saunter.Generator.Build) Nuget package a json AsyncAPI spec file will be generated for all AsyncAPI documents. \ No newline at end of file diff --git a/src/AsyncAPI.Saunter.Generator.Cli/AsyncAPI.Saunter.Generator.Cli.csproj b/src/AsyncAPI.Saunter.Generator.Cli/AsyncAPI.Saunter.Generator.Cli.csproj index 0400c5ab..a4d8449f 100644 --- a/src/AsyncAPI.Saunter.Generator.Cli/AsyncAPI.Saunter.Generator.Cli.csproj +++ b/src/AsyncAPI.Saunter.Generator.Cli/AsyncAPI.Saunter.Generator.Cli.csproj @@ -2,7 +2,7 @@ Exe - net8.0;net6.0 + net6.0;net8.0 enable 12 AsyncAPI.Saunter.Generator.Cli diff --git a/src/AsyncAPI.Saunter.Generator.Cli/Commands/Tofile.cs b/src/AsyncAPI.Saunter.Generator.Cli/Commands/Tofile.cs index 9faa30c9..a447ce43 100644 --- a/src/AsyncAPI.Saunter.Generator.Cli/Commands/Tofile.cs +++ b/src/AsyncAPI.Saunter.Generator.Cli/Commands/Tofile.cs @@ -41,6 +41,6 @@ internal static Func, int> Run(string[] args) => nam private static string EscapePath(string path) { - return path.Contains(' ') ? "\"" + path + "\"" : path; + return (path.Contains(' ') || string.IsNullOrWhiteSpace(path)) ? "\"" + path + "\"" : path; } } diff --git a/src/AsyncAPI.Saunter.Generator.Cli/Commands/TofileInternal.cs b/src/AsyncAPI.Saunter.Generator.Cli/Commands/TofileInternal.cs index a3477c7a..74fbaec3 100644 --- a/src/AsyncAPI.Saunter.Generator.Cli/Commands/TofileInternal.cs +++ b/src/AsyncAPI.Saunter.Generator.Cli/Commands/TofileInternal.cs @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +using System.Diagnostics; using LEGO.AsyncAPI.Readers; using Microsoft.Extensions.Options; using Saunter.Serialization; @@ -31,7 +32,7 @@ internal static int Run(IDictionary namedArgs) var startupAssembly = AssemblyLoadContext.Default.LoadFromAssemblyPath(Path.Combine(Directory.GetCurrentDirectory(), namedArgs[StartupAssemblyArgument])); // 2) Build a service container that's based on the startup assembly - var envVars = namedArgs.TryGetValue(EnvOption, out var x) ? x.Split(',').Select(x => x.Trim()) : Array.Empty(); + var envVars = (namedArgs.TryGetValue(EnvOption, out var x) && !string.IsNullOrWhiteSpace(x)) ? x.Split(',').Select(x => x.Trim()) : Array.Empty(); foreach (var envVar in envVars.Select(x => x.Split('=').Select(x => x.Trim()).ToList())) { if (envVar.Count == 2) @@ -50,8 +51,8 @@ internal static int Run(IDictionary namedArgs) var asyncapiOptions = serviceProvider.GetService>().Value; var documentSerializer = serviceProvider.GetRequiredService(); - var documentNames = namedArgs.TryGetValue(DocOption, out var doc) ? [doc] : asyncapiOptions.NamedApis.Keys; - var fileTemplate = namedArgs.TryGetValue(FileNameOption, out var template) ? template : "{document}_asyncapi.{extension}"; + var documentNames = (namedArgs.TryGetValue(DocOption, out var doc) && !string.IsNullOrWhiteSpace(doc)) ? [doc] : asyncapiOptions.NamedApis.Keys; + var fileTemplate = (namedArgs.TryGetValue(FileNameOption, out var template) && !string.IsNullOrWhiteSpace(template)) ? template : "{document}_asyncapi.{extension}"; if (documentNames.Count == 0) { if (asyncapiOptions.AssemblyMarkerTypes.Any()) @@ -86,20 +87,16 @@ internal static int Run(IDictionary namedArgs) } // 4) Serialize to specified output location or stdout - var outputPath = namedArgs.TryGetValue(OutputOption, out var arg1) ? Path.Combine(Directory.GetCurrentDirectory(), arg1) : null; + var outputPath = (namedArgs.TryGetValue(OutputOption, out var path) && !string.IsNullOrWhiteSpace(path)) ? Path.Combine(Directory.GetCurrentDirectory(), path) : null; if (!string.IsNullOrEmpty(outputPath)) { - var directoryPath = Path.GetDirectoryName(outputPath); - if (!string.IsNullOrEmpty(directoryPath) && !Directory.Exists(directoryPath)) - { - Directory.CreateDirectory(directoryPath); - } + Directory.CreateDirectory(outputPath); } var exportJson = true; var exportYml = false; var exportYaml = false; - if (namedArgs.TryGetValue(FormatOption, out var format)) + if (namedArgs.TryGetValue(FormatOption, out var format) && !string.IsNullOrWhiteSpace(format)) { var splitted = format.Split(',').Select(x => x.Trim()).ToList(); exportJson = splitted.Any(x => x.Equals("json", StringComparison.OrdinalIgnoreCase)); diff --git a/src/AsyncAPI.Saunter.Generator.Cli/SwashbuckleImport/CommandRunner.cs b/src/AsyncAPI.Saunter.Generator.Cli/SwashbuckleImport/CommandRunner.cs index c3c8eca0..29c982da 100644 --- a/src/AsyncAPI.Saunter.Generator.Cli/SwashbuckleImport/CommandRunner.cs +++ b/src/AsyncAPI.Saunter.Generator.Cli/SwashbuckleImport/CommandRunner.cs @@ -56,6 +56,7 @@ public int Run(IEnumerable args) if (_subRunners.Any() || !TryParseArgs(args, out IDictionary namedArgs)) { + _output.WriteLine($"Input: {string.Join(' ', args)}"); PrintUsage(); return 1; } From 02ffbcdbb8ddba879b461d18468a4436e7b977a1 Mon Sep 17 00:00:00 2001 From: Senn Geerts Date: Sun, 7 Jul 2024 11:12:13 +0200 Subject: [PATCH 15/23] #197 Produce AsyncAPI documents at build time --- .../AsyncAPI.Saunter.Generator.Build.csproj | 12 +----------- src/AsyncAPI.Saunter.Generator.Build/readme.md | 4 ++-- 2 files changed, 3 insertions(+), 13 deletions(-) diff --git a/src/AsyncAPI.Saunter.Generator.Build/AsyncAPI.Saunter.Generator.Build.csproj b/src/AsyncAPI.Saunter.Generator.Build/AsyncAPI.Saunter.Generator.Build.csproj index e9591e8b..04be28ce 100644 --- a/src/AsyncAPI.Saunter.Generator.Build/AsyncAPI.Saunter.Generator.Build.csproj +++ b/src/AsyncAPI.Saunter.Generator.Build/AsyncAPI.Saunter.Generator.Build.csproj @@ -47,17 +47,7 @@ - - - - - - + diff --git a/src/AsyncAPI.Saunter.Generator.Build/readme.md b/src/AsyncAPI.Saunter.Generator.Build/readme.md index 6b5971d1..3f601640 100644 --- a/src/AsyncAPI.Saunter.Generator.Build/readme.md +++ b/src/AsyncAPI.Saunter.Generator.Build/readme.md @@ -23,5 +23,5 @@ If the ```AsyncAPI.Saunter.Generator.Build``` Nuget package is referenced, the d - AsyncAPIDocumentOutputPath: Output path for the AsyncAPI spec files, relative to the csproj location. (default is the csproj root path: ./) - AsyncAPIDocumentNames: The AsyncAPI documents to generate. (default: generate all known documents) - AsyncAPIDocumentFilename: Template of the AsyncAPI spec files (default: "{document}_asyncapi.{extension}") -- AsyncAPIDocumentEnvVars: Environment variable(s) to set during generation of the AsyncAPI spec files (default: none, Example: "ASPNETCORE_ENVIRONMENT=Development") -None of these properties are mandatory. By only referencing the [AsyncAPI.Saunter.Generator.Build](https://www.nuget.org/packages/AsyncAPI.Saunter.Generator.Build) Nuget package a json AsyncAPI spec file will be generated for all AsyncAPI documents. \ No newline at end of file +- AsyncAPIDocumentEnvVars: Environment variable(s) to set during generation of the AsyncAPI spec files (default: none, Example: "ASPNETCORE_ENVIRONMENT=Development") +None of these properties are mandatory. Only referencing the [AsyncAPI.Saunter.Generator.Build](https://www.nuget.org/packages/AsyncAPI.Saunter.Generator.Build) Nuget package will generate a json AsyncAPI spec file for all AsyncAPI documents. \ No newline at end of file From 1ebb77c984c194947d0c9c00738e9570bb59d3bd Mon Sep 17 00:00:00 2001 From: Senn Geerts Date: Sun, 7 Jul 2024 11:39:54 +0200 Subject: [PATCH 16/23] #196 renamed tool to make up a more logical name, fixed empty parameter handling --- .../AsyncAPI.Saunter.Generator.Cli.csproj | 5 ++-- .../Commands/Tofile.cs | 2 +- .../Commands/TofileInternal.cs | 19 +++++++-------- src/AsyncAPI.Saunter.Generator.Cli/Program.cs | 6 ++--- src/AsyncAPI.Saunter.Generator.Cli/readme.md | 23 +++++++++++++------ ...syncAPI.Saunter.Generator.Cli.Tests.csproj | 6 ----- .../DotnetCliToolTests.cs | 2 +- .../PackAndInstallLocalTests.cs | 10 ++++---- .../asyncapi.cmd | 2 -- 9 files changed, 37 insertions(+), 38 deletions(-) delete mode 100755 test/AsyncAPI.Saunter.Generator.Cli.Tests/asyncapi.cmd diff --git a/src/AsyncAPI.Saunter.Generator.Cli/AsyncAPI.Saunter.Generator.Cli.csproj b/src/AsyncAPI.Saunter.Generator.Cli/AsyncAPI.Saunter.Generator.Cli.csproj index 0400c5ab..472cc32e 100644 --- a/src/AsyncAPI.Saunter.Generator.Cli/AsyncAPI.Saunter.Generator.Cli.csproj +++ b/src/AsyncAPI.Saunter.Generator.Cli/AsyncAPI.Saunter.Generator.Cli.csproj @@ -2,7 +2,7 @@ Exe - net8.0;net6.0 + net6.0;net8.0 enable 12 AsyncAPI.Saunter.Generator.Cli @@ -11,7 +11,7 @@ AsyncAPI Initiative true AsyncAPI.Saunter.Generator.Cli - AsyncAPI.NET + dotnet-asyncapi asyncapi;aspnetcore;openapi;documentation;amqp;generator;cli;tool readme.md logo.png @@ -23,6 +23,7 @@ false true snupkg + 1.0.1 diff --git a/src/AsyncAPI.Saunter.Generator.Cli/Commands/Tofile.cs b/src/AsyncAPI.Saunter.Generator.Cli/Commands/Tofile.cs index 9faa30c9..a447ce43 100644 --- a/src/AsyncAPI.Saunter.Generator.Cli/Commands/Tofile.cs +++ b/src/AsyncAPI.Saunter.Generator.Cli/Commands/Tofile.cs @@ -41,6 +41,6 @@ internal static Func, int> Run(string[] args) => nam private static string EscapePath(string path) { - return path.Contains(' ') ? "\"" + path + "\"" : path; + return (path.Contains(' ') || string.IsNullOrWhiteSpace(path)) ? "\"" + path + "\"" : path; } } diff --git a/src/AsyncAPI.Saunter.Generator.Cli/Commands/TofileInternal.cs b/src/AsyncAPI.Saunter.Generator.Cli/Commands/TofileInternal.cs index a3477c7a..5889e5d2 100644 --- a/src/AsyncAPI.Saunter.Generator.Cli/Commands/TofileInternal.cs +++ b/src/AsyncAPI.Saunter.Generator.Cli/Commands/TofileInternal.cs @@ -18,6 +18,7 @@ using Saunter.AsyncApiSchema.v2; using static Program; using AsyncApiDocument = Saunter.AsyncApiSchema.v2.AsyncApiDocument; +using System.IO; namespace AsyncApi.Saunter.Generator.Cli.Commands; @@ -31,7 +32,7 @@ internal static int Run(IDictionary namedArgs) var startupAssembly = AssemblyLoadContext.Default.LoadFromAssemblyPath(Path.Combine(Directory.GetCurrentDirectory(), namedArgs[StartupAssemblyArgument])); // 2) Build a service container that's based on the startup assembly - var envVars = namedArgs.TryGetValue(EnvOption, out var x) ? x.Split(',').Select(x => x.Trim()) : Array.Empty(); + var envVars = (namedArgs.TryGetValue(EnvOption, out var x) && !string.IsNullOrWhiteSpace(x)) ? x.Split(',').Select(x => x.Trim()) : Array.Empty(); foreach (var envVar in envVars.Select(x => x.Split('=').Select(x => x.Trim()).ToList())) { if (envVar.Count == 2) @@ -50,9 +51,9 @@ internal static int Run(IDictionary namedArgs) var asyncapiOptions = serviceProvider.GetService>().Value; var documentSerializer = serviceProvider.GetRequiredService(); - var documentNames = namedArgs.TryGetValue(DocOption, out var doc) ? [doc] : asyncapiOptions.NamedApis.Keys; - var fileTemplate = namedArgs.TryGetValue(FileNameOption, out var template) ? template : "{document}_asyncapi.{extension}"; - if (documentNames.Count == 0) + var documentNames = (namedArgs.TryGetValue(DocOption, out var doc) && !string.IsNullOrWhiteSpace(doc)) ? [doc] : asyncapiOptions.NamedApis.Keys; + var fileTemplate = (namedArgs.TryGetValue(FileNameOption, out var template) && !string.IsNullOrWhiteSpace(template)) ? template : "{document}_asyncapi.{extension}"; + if (documentNames.Count == 0) { if (asyncapiOptions.AssemblyMarkerTypes.Any()) { @@ -86,20 +87,16 @@ internal static int Run(IDictionary namedArgs) } // 4) Serialize to specified output location or stdout - var outputPath = namedArgs.TryGetValue(OutputOption, out var arg1) ? Path.Combine(Directory.GetCurrentDirectory(), arg1) : null; + var outputPath = (namedArgs.TryGetValue(OutputOption, out var path) && !string.IsNullOrWhiteSpace(path)) ? Path.Combine(Directory.GetCurrentDirectory(), path) : null; if (!string.IsNullOrEmpty(outputPath)) { - var directoryPath = Path.GetDirectoryName(outputPath); - if (!string.IsNullOrEmpty(directoryPath) && !Directory.Exists(directoryPath)) - { - Directory.CreateDirectory(directoryPath); - } + Directory.CreateDirectory(outputPath); } var exportJson = true; var exportYml = false; var exportYaml = false; - if (namedArgs.TryGetValue(FormatOption, out var format)) + if (namedArgs.TryGetValue(FormatOption, out var format) && !string.IsNullOrWhiteSpace(format)) { var splitted = format.Split(',').Select(x => x.Trim()).ToList(); exportJson = splitted.Any(x => x.Equals("json", StringComparison.OrdinalIgnoreCase)); diff --git a/src/AsyncAPI.Saunter.Generator.Cli/Program.cs b/src/AsyncAPI.Saunter.Generator.Cli/Program.cs index 4d174c60..b9facd2b 100644 --- a/src/AsyncAPI.Saunter.Generator.Cli/Program.cs +++ b/src/AsyncAPI.Saunter.Generator.Cli/Program.cs @@ -5,14 +5,14 @@ DependencyResolver.Init(); // Helper to simplify command line parsing etc. -var runner = new CommandRunner("dotnet asyncapi.net", "AsyncAPI Command Line Tools", Console.Out); +var runner = new CommandRunner("dotnet asyncapi", "AsyncAPI Command Line Tools", Console.Out); // NOTE: The "dotnet asyncapi tofile" command does not serve the request directly. Instead, it invokes a corresponding // command (called _tofile) via "dotnet exec" so that the runtime configuration (*.runtimeconfig & *.deps.json) of the // provided startupassembly can be used instead of the tool's. This is neccessary to successfully load the // startupassembly and it's transitive dependencies. See https://github.com/dotnet/coreclr/issues/13277 for more. -// > dotnet asyncapi.net tofile ... +// > dotnet asyncapi tofile ... runner.SubCommand("tofile", "retrieves AsyncAPI from a startup assembly, and writes to file ", c => { c.Argument(StartupAssemblyArgument, "relative path to the application's startup assembly"); @@ -24,7 +24,7 @@ c.OnRun(Tofile.Run(args)); }); -// > dotnet asyncapi.net _tofile ... (* should only be invoked via "dotnet exec") +// > dotnet asyncapi _tofile ... (* should only be invoked via "dotnet exec") runner.SubCommand("_tofile", "", c => { c.Argument(StartupAssemblyArgument, ""); diff --git a/src/AsyncAPI.Saunter.Generator.Cli/readme.md b/src/AsyncAPI.Saunter.Generator.Cli/readme.md index 11d3c9b4..74d5c81b 100644 --- a/src/AsyncAPI.Saunter.Generator.Cli/readme.md +++ b/src/AsyncAPI.Saunter.Generator.Cli/readme.md @@ -1,15 +1,24 @@ # AsyncApi Generator.Cli Tool -A dotnet tool to generate AsyncAPI specification files based of dotnet DLL (The application itself). +A dotnet tool to generate AsyncAPI specification files based of a dotnet DLL (The application itself). ## Tool usage ``` -dotnet asyncapi.net tofile --output [output-path] --format [json,yml,yaml] --doc [asyncapi-document-name] [startup-assembly] +dotnet asyncapi tofile --output [output-path] --format [json,yml,yaml] --doc [asyncapi-document-name] [startup-assembly] ``` startup-assembly: the file path to the entrypoint dotnet DLL that hosts AsyncAPI document(s). ## Tool options ---doc: The name of the AsyncAPI document as defined in the startup class by the ```.ConfigureNamedAsyncApi()```-method. If not specified, all documents will be exported. ---output: relative path where the AsyncAPI will be output [defaults to stdout] ---filename: the template for the outputted file names. Default: "{document}_asyncapi.{extension}" ---format: the output formats to generate, can be a combination of json, yml and/or yaml. File extension is appended to the output path. ---env: define environment variable(s) for the application +- _--doc_: The name of the AsyncAPI document as defined in the startup class by the ```.ConfigureNamedAsyncApi()```-method. If only ```.AddAsyncApiSchemaGeneration()``` is used, the document is unnamed and will always be exported. If not specified, all documents will be exported. +- _--output_: relative path where the AsyncAPI will be output [defaults to stdout] +- _--filename_: the template for the outputted file names. Default: "{document}_asyncapi.{extension}" +- _--format_: the output formats to generate, can be a combination of json, yml and/or yaml. File extension is appended to the output path. +- _--env_: define environment variable(s) for the application + +## Install the Generator.Cli dotnet Tool +``` +dotnet tool install --global AsyncAPI.Saunter.Generator.Cli +``` +After installing the tool globally, it is available using commands: ```dotnet asyncapi``` or ```dotnet-asyncapi``` + +Want to learn more about .NET tools? Or want to install it local using a manifest? +(Check out this Microsoft page on how to manage .NET tools)[https://learn.microsoft.com/en-us/dotnet/core/tools/global-tools] \ No newline at end of file diff --git a/test/AsyncAPI.Saunter.Generator.Cli.Tests/AsyncAPI.Saunter.Generator.Cli.Tests.csproj b/test/AsyncAPI.Saunter.Generator.Cli.Tests/AsyncAPI.Saunter.Generator.Cli.Tests.csproj index 3a1e115b..355fdd59 100644 --- a/test/AsyncAPI.Saunter.Generator.Cli.Tests/AsyncAPI.Saunter.Generator.Cli.Tests.csproj +++ b/test/AsyncAPI.Saunter.Generator.Cli.Tests/AsyncAPI.Saunter.Generator.Cli.Tests.csproj @@ -24,10 +24,4 @@ - - - PreserveNewest - - - diff --git a/test/AsyncAPI.Saunter.Generator.Cli.Tests/DotnetCliToolTests.cs b/test/AsyncAPI.Saunter.Generator.Cli.Tests/DotnetCliToolTests.cs index 3d6c7324..97258c87 100644 --- a/test/AsyncAPI.Saunter.Generator.Cli.Tests/DotnetCliToolTests.cs +++ b/test/AsyncAPI.Saunter.Generator.Cli.Tests/DotnetCliToolTests.cs @@ -35,7 +35,7 @@ public void DefaultCallPrintsCommandInfo() var stdOut = RunTool("", 1); stdOut.ShouldBe(""" - Usage: dotnet asyncapi.net tofile [options] [startupassembly] + Usage: dotnet asyncapi tofile [options] [startupassembly] startupassembly: relative path to the application's startup assembly diff --git a/test/AsyncAPI.Saunter.Generator.Cli.Tests/PackAndInstallLocalTests.cs b/test/AsyncAPI.Saunter.Generator.Cli.Tests/PackAndInstallLocalTests.cs index 34930f30..79d9844d 100644 --- a/test/AsyncAPI.Saunter.Generator.Cli.Tests/PackAndInstallLocalTests.cs +++ b/test/AsyncAPI.Saunter.Generator.Cli.Tests/PackAndInstallLocalTests.cs @@ -38,19 +38,19 @@ public void Pack_Install_Run_Uninstall_Test() stdOut.ShouldContain("Successfully created package"); stdOut = this.Run("dotnet", "tool install --global --add-source ./bin/Release AsyncAPI.Saunter.Generator.Cli", "../../../../../src/AsyncAPI.Saunter.Generator.Cli"); - stdOut.ShouldBeOneOf("You can invoke the tool using the following command: AsyncAPI.NET\r\nTool 'asyncapi.saunter.generator.cli' (version '1.0.0') was successfully installed.", - "Tool 'asyncapi.saunter.generator.cli' was reinstalled with the stable version (version '1.0.0')."); + stdOut.ShouldBeOneOf("You can invoke the tool using the following command: dotnet-asyncapi\r\nTool 'asyncapi.saunter.generator.cli' (version '1.0.1') was successfully installed.", + "Tool 'asyncapi.saunter.generator.cli' was reinstalled with the stable version (version '1.0.1')."); stdOut = this.Run("dotnet", "tool list -g asyncapi.saunter.generator.cli", ""); - stdOut.ShouldContain("AsyncAPI.NET"); + stdOut.ShouldContain("dotnet-asyncapi"); - stdOut = this.Run("asyncapi.cmd", "", "", 1); + stdOut = this.Run("dotnet", "asyncapi", "", 1); stdOut.ShouldContain("tofile: retrieves AsyncAPI from a startup assembly, and writes to file"); stdOut = this.Run("dotnet", "tool uninstall -g asyncapi.saunter.generator.cli", ""); stdOut.ShouldContain(" was successfully uninstalled."); stdOut = this.Run("dotnet", "tool list -g asyncapi.saunter.generator.cli", "", 1); - stdOut.ShouldNotContain("AsyncAPI.NET"); + stdOut.ShouldNotContain("dotnet-asyncapi"); } } diff --git a/test/AsyncAPI.Saunter.Generator.Cli.Tests/asyncapi.cmd b/test/AsyncAPI.Saunter.Generator.Cli.Tests/asyncapi.cmd deleted file mode 100755 index 1f61f620..00000000 --- a/test/AsyncAPI.Saunter.Generator.Cli.Tests/asyncapi.cmd +++ /dev/null @@ -1,2 +0,0 @@ -#!/bin/bash -AsyncAPI.NET \ No newline at end of file From ba1e8566cd3f2c2690d503dda90fa6baa36987c2 Mon Sep 17 00:00:00 2001 From: Senn Geerts Date: Sun, 7 Jul 2024 11:48:39 +0200 Subject: [PATCH 17/23] #196 fix readme error --- src/AsyncAPI.Saunter.Generator.Cli/readme.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/AsyncAPI.Saunter.Generator.Cli/readme.md b/src/AsyncAPI.Saunter.Generator.Cli/readme.md index 74d5c81b..8eb9a503 100644 --- a/src/AsyncAPI.Saunter.Generator.Cli/readme.md +++ b/src/AsyncAPI.Saunter.Generator.Cli/readme.md @@ -21,4 +21,4 @@ dotnet tool install --global AsyncAPI.Saunter.Generator.Cli After installing the tool globally, it is available using commands: ```dotnet asyncapi``` or ```dotnet-asyncapi``` Want to learn more about .NET tools? Or want to install it local using a manifest? -(Check out this Microsoft page on how to manage .NET tools)[https://learn.microsoft.com/en-us/dotnet/core/tools/global-tools] \ No newline at end of file +[Check out this Microsoft page on how to manage .NET tools](https://learn.microsoft.com/en-us/dotnet/core/tools/global-tools) \ No newline at end of file From a2813e2294660c91babc0172cdaf8783f09c7daa Mon Sep 17 00:00:00 2001 From: Senn Geerts Date: Sun, 7 Jul 2024 14:13:01 +0200 Subject: [PATCH 18/23] #197 Produce AsyncAPI documents at build time - test + setup with local nuget source --- .gitignore | 1 + Saunter.sln | 16 ++ .../StreetlightsAPI/StreetlightsAPI.csproj | 22 +++ nuget.config | 11 ++ .../AsyncAPI.Saunter.Generator.Build.csproj | 13 +- .../readme.md | 2 +- .../AsyncAPI.Saunter.Generator.Cli.csproj | 6 + .../Commands/TofileInternal.cs | 3 +- .../SwashbuckleImport/CommandRunner.cs | 2 +- ...ncAPI.Saunter.Generator.Build.Tests.csproj | 28 +++ .../StreetlightsApiBuildTests.cs | 74 ++++++++ ...syncAPI.Saunter.Generator.Cli.Tests.csproj | 26 +++ .../DotnetCliToolTests.cs | 161 +----------------- .../Specs/ExpectedSpecFiles.cs | 12 ++ .../Specs/streetlights_v2.6.json | 94 ++++++++++ .../Specs/streetlights_v2.6.yml | 61 +++++++ 16 files changed, 367 insertions(+), 165 deletions(-) create mode 100644 nuget.config create mode 100644 test/AsyncAPI.Saunter.Generator.Build.Tests/AsyncAPI.Saunter.Generator.Build.Tests.csproj create mode 100644 test/AsyncAPI.Saunter.Generator.Build.Tests/StreetlightsApiBuildTests.cs create mode 100644 test/AsyncAPI.Saunter.Generator.Cli.Tests/Specs/ExpectedSpecFiles.cs create mode 100644 test/AsyncAPI.Saunter.Generator.Cli.Tests/Specs/streetlights_v2.6.json create mode 100644 test/AsyncAPI.Saunter.Generator.Cli.Tests/Specs/streetlights_v2.6.yml diff --git a/.gitignore b/.gitignore index 758b4e30..16515532 100644 --- a/.gitignore +++ b/.gitignore @@ -206,6 +206,7 @@ PublishScripts/ # NuGet v3's project.json files produces more ignorable files *.nuget.props *.nuget.targets +local-nuget-source/ # Microsoft Azure Build Output csx/ diff --git a/Saunter.sln b/Saunter.sln index c746b5ea..40ce7d40 100644 --- a/Saunter.sln +++ b/Saunter.sln @@ -21,6 +21,7 @@ Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Solution Items", "Solution .gitattributes = .gitattributes CHANGELOG.md = CHANGELOG.md .github\workflows\ci.yaml = .github\workflows\ci.yaml + nuget.config = nuget.config README.md = README.md .github\workflows\release.yaml = .github\workflows\release.yaml EndProjectSection @@ -35,6 +36,8 @@ Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "AsyncAPI.Saunter.Generator. EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "AsyncAPI.Saunter.Generator.Build", "src\AsyncAPI.Saunter.Generator.Build\AsyncAPI.Saunter.Generator.Build.csproj", "{A320E670-5CB0-4815-AF67-D8D09FC92A2A}" EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "AsyncAPI.Saunter.Generator.Build.Tests", "test\AsyncAPI.Saunter.Generator.Build.Tests\AsyncAPI.Saunter.Generator.Build.Tests.csproj", "{61142B10-7B49-436E-AE32-2737658BD1E5}" +EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution Debug|Any CPU = Debug|Any CPU @@ -141,6 +144,18 @@ Global {A320E670-5CB0-4815-AF67-D8D09FC92A2A}.Release|x64.Build.0 = Release|Any CPU {A320E670-5CB0-4815-AF67-D8D09FC92A2A}.Release|x86.ActiveCfg = Release|Any CPU {A320E670-5CB0-4815-AF67-D8D09FC92A2A}.Release|x86.Build.0 = Release|Any CPU + {61142B10-7B49-436E-AE32-2737658BD1E5}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {61142B10-7B49-436E-AE32-2737658BD1E5}.Debug|Any CPU.Build.0 = Debug|Any CPU + {61142B10-7B49-436E-AE32-2737658BD1E5}.Debug|x64.ActiveCfg = Debug|Any CPU + {61142B10-7B49-436E-AE32-2737658BD1E5}.Debug|x64.Build.0 = Debug|Any CPU + {61142B10-7B49-436E-AE32-2737658BD1E5}.Debug|x86.ActiveCfg = Debug|Any CPU + {61142B10-7B49-436E-AE32-2737658BD1E5}.Debug|x86.Build.0 = Debug|Any CPU + {61142B10-7B49-436E-AE32-2737658BD1E5}.Release|Any CPU.ActiveCfg = Release|Any CPU + {61142B10-7B49-436E-AE32-2737658BD1E5}.Release|Any CPU.Build.0 = Release|Any CPU + {61142B10-7B49-436E-AE32-2737658BD1E5}.Release|x64.ActiveCfg = Release|Any CPU + {61142B10-7B49-436E-AE32-2737658BD1E5}.Release|x64.Build.0 = Release|Any CPU + {61142B10-7B49-436E-AE32-2737658BD1E5}.Release|x86.ActiveCfg = Release|Any CPU + {61142B10-7B49-436E-AE32-2737658BD1E5}.Release|x86.Build.0 = Release|Any CPU EndGlobalSection GlobalSection(SolutionProperties) = preSolution HideSolutionNode = FALSE @@ -154,6 +169,7 @@ Global {6C102D4D-3DA4-4763-B75E-C15E33E7E94A} = {28D4C365-FDED-49AE-A97D-36202E24A55A} {18AD0249-0436-4A26-9972-B97BA6905A54} = {6491E321-2D02-44AB-9116-D722FE169595} {A320E670-5CB0-4815-AF67-D8D09FC92A2A} = {28D4C365-FDED-49AE-A97D-36202E24A55A} + {61142B10-7B49-436E-AE32-2737658BD1E5} = {6491E321-2D02-44AB-9116-D722FE169595} EndGlobalSection GlobalSection(ExtensibilityGlobals) = postSolution SolutionGuid = {2F85D9DA-DBCF-4F13-8C42-5719F1469B2E} diff --git a/examples/StreetlightsAPI/StreetlightsAPI.csproj b/examples/StreetlightsAPI/StreetlightsAPI.csproj index 3185dffc..dbc65c36 100644 --- a/examples/StreetlightsAPI/StreetlightsAPI.csproj +++ b/examples/StreetlightsAPI/StreetlightsAPI.csproj @@ -3,6 +3,8 @@ net6.0 false + + true json,yml streetlights.{extension} @@ -19,8 +21,28 @@ 1701;1702;1591 + + + + all + runtime; build; native; contentfiles; analyzers; buildtransitive + + + + + + + all + runtime; build; native; contentfiles; analyzers; buildtransitive + + + + + + + diff --git a/nuget.config b/nuget.config new file mode 100644 index 00000000..18e0fc86 --- /dev/null +++ b/nuget.config @@ -0,0 +1,11 @@ + + + + + + + + + + \ No newline at end of file diff --git a/src/AsyncAPI.Saunter.Generator.Build/AsyncAPI.Saunter.Generator.Build.csproj b/src/AsyncAPI.Saunter.Generator.Build/AsyncAPI.Saunter.Generator.Build.csproj index 04be28ce..c7f4b632 100644 --- a/src/AsyncAPI.Saunter.Generator.Build/AsyncAPI.Saunter.Generator.Build.csproj +++ b/src/AsyncAPI.Saunter.Generator.Build/AsyncAPI.Saunter.Generator.Build.csproj @@ -15,13 +15,20 @@ https://github.com/asyncapi/saunter true true - false + true false https://github.com/asyncapi/saunter MIT false - 0.0.24 - tools/$(Configuration) + true + 1.0.0 + bin/ + + + + 0.0.999-debug-$([System.DateTime]::Now.ToString('yyyyMMddHHmm')) + true + ../../local-nuget-source diff --git a/src/AsyncAPI.Saunter.Generator.Build/readme.md b/src/AsyncAPI.Saunter.Generator.Build/readme.md index 3f601640..eca774ac 100644 --- a/src/AsyncAPI.Saunter.Generator.Build/readme.md +++ b/src/AsyncAPI.Saunter.Generator.Build/readme.md @@ -2,7 +2,7 @@ A nuget package to generate AsyncAPI specification files at build time, based on code-first attributes. # Customizations -The AsyncAPI spec generation can be configured through properties in the csproj-file (or .props files): +The AsyncAPI spec generation can be configured through project properties in the csproj-file (or .props files): ``` diff --git a/src/AsyncAPI.Saunter.Generator.Cli/AsyncAPI.Saunter.Generator.Cli.csproj b/src/AsyncAPI.Saunter.Generator.Cli/AsyncAPI.Saunter.Generator.Cli.csproj index 472cc32e..8f079e03 100644 --- a/src/AsyncAPI.Saunter.Generator.Cli/AsyncAPI.Saunter.Generator.Cli.csproj +++ b/src/AsyncAPI.Saunter.Generator.Cli/AsyncAPI.Saunter.Generator.Cli.csproj @@ -26,6 +26,12 @@ 1.0.1 + + 0.0.999-debug-$([System.DateTime]::Now.ToString('yyyyMMddHHmm')) + true + ../../local-nuget-source + + diff --git a/src/AsyncAPI.Saunter.Generator.Cli/Commands/TofileInternal.cs b/src/AsyncAPI.Saunter.Generator.Cli/Commands/TofileInternal.cs index 9ab87b03..56b42dee 100644 --- a/src/AsyncAPI.Saunter.Generator.Cli/Commands/TofileInternal.cs +++ b/src/AsyncAPI.Saunter.Generator.Cli/Commands/TofileInternal.cs @@ -131,7 +131,8 @@ private static void WriteFile(string outputPath, Action writeAction) if (outputPath != null) { - Console.WriteLine($"AsyncAPI {Path.GetExtension(outputPath)[1..]} successfully written to {outputPath}"); + var sanitizedPath = Path.GetFullPath(outputPath); + Console.WriteLine($"AsyncAPI {Path.GetExtension(outputPath)[1..]} successfully written to {sanitizedPath}"); } } diff --git a/src/AsyncAPI.Saunter.Generator.Cli/SwashbuckleImport/CommandRunner.cs b/src/AsyncAPI.Saunter.Generator.Cli/SwashbuckleImport/CommandRunner.cs index 29c982da..5b2d01eb 100644 --- a/src/AsyncAPI.Saunter.Generator.Cli/SwashbuckleImport/CommandRunner.cs +++ b/src/AsyncAPI.Saunter.Generator.Cli/SwashbuckleImport/CommandRunner.cs @@ -56,7 +56,7 @@ public int Run(IEnumerable args) if (_subRunners.Any() || !TryParseArgs(args, out IDictionary namedArgs)) { - _output.WriteLine($"Input: {string.Join(' ', args)}"); + //_output.WriteLine($"Input: {string.Join(' ', args)}"); // Useful for debugging PrintUsage(); return 1; } diff --git a/test/AsyncAPI.Saunter.Generator.Build.Tests/AsyncAPI.Saunter.Generator.Build.Tests.csproj b/test/AsyncAPI.Saunter.Generator.Build.Tests/AsyncAPI.Saunter.Generator.Build.Tests.csproj new file mode 100644 index 00000000..de4f84f2 --- /dev/null +++ b/test/AsyncAPI.Saunter.Generator.Build.Tests/AsyncAPI.Saunter.Generator.Build.Tests.csproj @@ -0,0 +1,28 @@ + + + + net8.0 + enable + + false + true + + + + + + + + + + + + + + + + + + + + diff --git a/test/AsyncAPI.Saunter.Generator.Build.Tests/StreetlightsApiBuildTests.cs b/test/AsyncAPI.Saunter.Generator.Build.Tests/StreetlightsApiBuildTests.cs new file mode 100644 index 00000000..061d4036 --- /dev/null +++ b/test/AsyncAPI.Saunter.Generator.Build.Tests/StreetlightsApiBuildTests.cs @@ -0,0 +1,74 @@ +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information. + +using System.Diagnostics; +using AsyncAPI.Saunter.Generator.Cli.Tests; +using Shouldly; +using Xunit.Abstractions; + +namespace AsyncAPI.Saunter.Generator.Build.Tests; + +public class StreetlightsApiBuildTests(ITestOutputHelper output) +{ + private string Run(string file, string args, string workingDirectory, int expectedExitCode = 0) + { + var process = Process.Start(new ProcessStartInfo(file) + { + Arguments = args, + WorkingDirectory = workingDirectory, + RedirectStandardOutput = true, + RedirectStandardError = true, + UseShellExecute = false, + }); + process.WaitForExit(TimeSpan.FromSeconds(20)); + var stdOut = process.StandardOutput.ReadToEnd().Trim(); + var stdError = process.StandardError.ReadToEnd().Trim(); + output.WriteLine($"### Output of \"{file} {args}\""); + output.WriteLine(stdOut); + output.WriteLine(stdError); + + process.ExitCode.ShouldBe(expectedExitCode); + return stdOut; + } + + private const string csprojPath = "../../../../../examples/StreetlightsAPI/StreetlightsAPI.csproj"; + + [Fact] + public void BuildingCsprojGeneratesSpecFilesTest() + { + var pwd = Directory.GetCurrentDirectory(); + var csproj = Path.GetFullPath(Path.Combine(pwd, csprojPath)); + output.WriteLine($"Current working directory: {pwd}"); + output.WriteLine($"Csproj under test: {csproj}"); + File.Exists(csproj).ShouldBeTrue(); + + var csprojDir = Path.GetDirectoryName(csproj); + var specDir = Path.Combine(csprojDir, "specs"); + + // Spec files should have been generated during the builds of the solution + Directory.GetFiles(specDir).Length.ShouldBe(2, $"#Spec files initial, path: {specDir}"); + File.ReadAllText(Path.Combine(specDir, "streetlights.yml")).ShouldBe(ExpectedSpecFiles.Yml_v2_6, "yml"); + File.ReadAllText(Path.Combine(specDir, "streetlights.json")).ShouldBe(ExpectedSpecFiles.Json_v2_6, "json"); + + // Delete spec files + foreach (var file in Directory.EnumerateFiles(specDir)) + { + File.Delete(file); + } + Directory.GetFiles(specDir).Length.ShouldBe(0, $"#Spec files after deleting them all, path: {specDir}"); + + // Run build + var stdOut = this.Run("dotnet", "build", csprojDir); + stdOut.ShouldContain($"AsyncAPI json successfully written to {Path.Combine(specDir, "streetlights.json")}"); + stdOut.ShouldContain($"AsyncAPI yml successfully written to {Path.Combine(specDir, "streetlights.yml")}"); + stdOut.ShouldContain("Build succeeded."); + stdOut.ShouldContain("0 Warning(s)"); + stdOut.ShouldContain("0 Error(s)"); + + // Check that spec files are actually re-generated + Directory.GetFiles(specDir).Length.ShouldBe(2, $"#Spec files after running build, path: {specDir}"); + File.ReadAllText(Path.Combine(specDir, "streetlights.yml")).ShouldBe(ExpectedSpecFiles.Yml_v2_6, "yml"); + File.ReadAllText(Path.Combine(specDir, "streetlights.json")).ShouldBe(ExpectedSpecFiles.Json_v2_6, "json"); + } +} diff --git a/test/AsyncAPI.Saunter.Generator.Cli.Tests/AsyncAPI.Saunter.Generator.Cli.Tests.csproj b/test/AsyncAPI.Saunter.Generator.Cli.Tests/AsyncAPI.Saunter.Generator.Cli.Tests.csproj index 355fdd59..3a3489ac 100644 --- a/test/AsyncAPI.Saunter.Generator.Cli.Tests/AsyncAPI.Saunter.Generator.Cli.Tests.csproj +++ b/test/AsyncAPI.Saunter.Generator.Cli.Tests/AsyncAPI.Saunter.Generator.Cli.Tests.csproj @@ -8,6 +8,26 @@ true + + + + + + + + + + + PreserveNewest + true + PreserveNewest + + + + + + + @@ -24,4 +44,10 @@ + + + PreserveNewest + + + diff --git a/test/AsyncAPI.Saunter.Generator.Cli.Tests/DotnetCliToolTests.cs b/test/AsyncAPI.Saunter.Generator.Cli.Tests/DotnetCliToolTests.cs index 97258c87..462b2f75 100644 --- a/test/AsyncAPI.Saunter.Generator.Cli.Tests/DotnetCliToolTests.cs +++ b/test/AsyncAPI.Saunter.Generator.Cli.Tests/DotnetCliToolTests.cs @@ -66,169 +66,12 @@ public void StreetlightsAPIExportSpecTest() File.Exists("asyncapi.json").ShouldBeTrue("asyncapi.json"); var yml = File.ReadAllText("asyncapi.yml"); - yml.ShouldBe(""" - asyncapi: 2.6.0 - info: - title: Streetlights API - version: 1.0.0 - description: The Smartylighting Streetlights API allows you to remotely manage the city lights. - license: - name: Apache 2.0 - url: https://www.apache.org/licenses/LICENSE-2.0 - servers: - mosquitto: - url: test.mosquitto.org - protocol: mqtt - webapi: - url: localhost:5000 - protocol: http - defaultContentType: application/json - channels: - publish/light/measured: - servers: - - webapi - publish: - operationId: MeasureLight - summary: Inform about environmental lighting conditions for a particular streetlight. - tags: - - name: Light - message: - $ref: '#/components/messages/lightMeasuredEvent' - subscribe/light/measured: - servers: - - mosquitto - subscribe: - operationId: PublishLightMeasurement - summary: Subscribe to environmental lighting conditions for a particular streetlight. - tags: - - name: Light - message: - payload: - $ref: '#/components/schemas/lightMeasuredEvent' - components: - schemas: - lightMeasuredEvent: - type: object - properties: - id: - type: integer - format: int32 - description: Id of the streetlight. - lumens: - type: integer - format: int32 - description: Light intensity measured in lumens. - sentAt: - type: string - format: date-time - description: Light intensity measured in lumens. - additionalProperties: false - messages: - lightMeasuredEvent: - payload: - $ref: '#/components/schemas/lightMeasuredEvent' - name: lightMeasuredEvent - """, "yaml"); + yml.ShouldBe(ExpectedSpecFiles.Yml_v2_6, "yaml"); var yaml = File.ReadAllText("asyncapi.yaml"); yaml.ShouldBe(yml, "yml"); var json = File.ReadAllText("asyncapi.json"); - json.ShouldBe(""" - { - "asyncapi": "2.6.0", - "info": { - "title": "Streetlights API", - "version": "1.0.0", - "description": "The Smartylighting Streetlights API allows you to remotely manage the city lights.", - "license": { - "name": "Apache 2.0", - "url": "https://www.apache.org/licenses/LICENSE-2.0" - } - }, - "servers": { - "mosquitto": { - "url": "test.mosquitto.org", - "protocol": "mqtt" - }, - "webapi": { - "url": "localhost:5000", - "protocol": "http" - } - }, - "defaultContentType": "application/json", - "channels": { - "publish/light/measured": { - "servers": [ - "webapi" - ], - "publish": { - "operationId": "MeasureLight", - "summary": "Inform about environmental lighting conditions for a particular streetlight.", - "tags": [ - { - "name": "Light" - } - ], - "message": { - "$ref": "#/components/messages/lightMeasuredEvent" - } - } - }, - "subscribe/light/measured": { - "servers": [ - "mosquitto" - ], - "subscribe": { - "operationId": "PublishLightMeasurement", - "summary": "Subscribe to environmental lighting conditions for a particular streetlight.", - "tags": [ - { - "name": "Light" - } - ], - "message": { - "payload": { - "$ref": "#/components/schemas/lightMeasuredEvent" - } - } - } - } - }, - "components": { - "schemas": { - "lightMeasuredEvent": { - "type": "object", - "properties": { - "id": { - "type": "integer", - "format": "int32", - "description": "Id of the streetlight." - }, - "lumens": { - "type": "integer", - "format": "int32", - "description": "Light intensity measured in lumens." - }, - "sentAt": { - "type": "string", - "format": "date-time", - "description": "Light intensity measured in lumens." - } - }, - "additionalProperties": false - } - }, - "messages": { - "lightMeasuredEvent": { - "payload": { - "$ref": "#/components/schemas/lightMeasuredEvent" - }, - "name": "lightMeasuredEvent" - } - } - } - } - """, "json"); + json.ShouldBe(ExpectedSpecFiles.Json_v2_6, "json"); } } diff --git a/test/AsyncAPI.Saunter.Generator.Cli.Tests/Specs/ExpectedSpecFiles.cs b/test/AsyncAPI.Saunter.Generator.Cli.Tests/Specs/ExpectedSpecFiles.cs new file mode 100644 index 00000000..aa6ed033 --- /dev/null +++ b/test/AsyncAPI.Saunter.Generator.Cli.Tests/Specs/ExpectedSpecFiles.cs @@ -0,0 +1,12 @@ +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information. + +namespace AsyncAPI.Saunter.Generator.Cli.Tests; + +public static class ExpectedSpecFiles +{ + public static string Json_v2_6 => File.ReadAllText("Specs/streetlights_v2.6.json"); + + public static string Yml_v2_6 => File.ReadAllText("Specs/streetlights_v2.6.yml"); +} diff --git a/test/AsyncAPI.Saunter.Generator.Cli.Tests/Specs/streetlights_v2.6.json b/test/AsyncAPI.Saunter.Generator.Cli.Tests/Specs/streetlights_v2.6.json new file mode 100644 index 00000000..8a429cbb --- /dev/null +++ b/test/AsyncAPI.Saunter.Generator.Cli.Tests/Specs/streetlights_v2.6.json @@ -0,0 +1,94 @@ +{ + "asyncapi": "2.6.0", + "info": { + "title": "Streetlights API", + "version": "1.0.0", + "description": "The Smartylighting Streetlights API allows you to remotely manage the city lights.", + "license": { + "name": "Apache 2.0", + "url": "https://www.apache.org/licenses/LICENSE-2.0" + } + }, + "servers": { + "mosquitto": { + "url": "test.mosquitto.org", + "protocol": "mqtt" + }, + "webapi": { + "url": "localhost:5000", + "protocol": "http" + } + }, + "defaultContentType": "application/json", + "channels": { + "publish/light/measured": { + "servers": [ + "webapi" + ], + "publish": { + "operationId": "MeasureLight", + "summary": "Inform about environmental lighting conditions for a particular streetlight.", + "tags": [ + { + "name": "Light" + } + ], + "message": { + "$ref": "#/components/messages/lightMeasuredEvent" + } + } + }, + "subscribe/light/measured": { + "servers": [ + "mosquitto" + ], + "subscribe": { + "operationId": "PublishLightMeasurement", + "summary": "Subscribe to environmental lighting conditions for a particular streetlight.", + "tags": [ + { + "name": "Light" + } + ], + "message": { + "payload": { + "$ref": "#/components/schemas/lightMeasuredEvent" + } + } + } + } + }, + "components": { + "schemas": { + "lightMeasuredEvent": { + "type": "object", + "properties": { + "id": { + "type": "integer", + "format": "int32", + "description": "Id of the streetlight." + }, + "lumens": { + "type": "integer", + "format": "int32", + "description": "Light intensity measured in lumens." + }, + "sentAt": { + "type": "string", + "format": "date-time", + "description": "Light intensity measured in lumens." + } + }, + "additionalProperties": false + } + }, + "messages": { + "lightMeasuredEvent": { + "payload": { + "$ref": "#/components/schemas/lightMeasuredEvent" + }, + "name": "lightMeasuredEvent" + } + } + } +} \ No newline at end of file diff --git a/test/AsyncAPI.Saunter.Generator.Cli.Tests/Specs/streetlights_v2.6.yml b/test/AsyncAPI.Saunter.Generator.Cli.Tests/Specs/streetlights_v2.6.yml new file mode 100644 index 00000000..efccd7ed --- /dev/null +++ b/test/AsyncAPI.Saunter.Generator.Cli.Tests/Specs/streetlights_v2.6.yml @@ -0,0 +1,61 @@ +asyncapi: 2.6.0 +info: + title: Streetlights API + version: 1.0.0 + description: The Smartylighting Streetlights API allows you to remotely manage the city lights. + license: + name: Apache 2.0 + url: https://www.apache.org/licenses/LICENSE-2.0 +servers: + mosquitto: + url: test.mosquitto.org + protocol: mqtt + webapi: + url: localhost:5000 + protocol: http +defaultContentType: application/json +channels: + publish/light/measured: + servers: + - webapi + publish: + operationId: MeasureLight + summary: Inform about environmental lighting conditions for a particular streetlight. + tags: + - name: Light + message: + $ref: '#/components/messages/lightMeasuredEvent' + subscribe/light/measured: + servers: + - mosquitto + subscribe: + operationId: PublishLightMeasurement + summary: Subscribe to environmental lighting conditions for a particular streetlight. + tags: + - name: Light + message: + payload: + $ref: '#/components/schemas/lightMeasuredEvent' +components: + schemas: + lightMeasuredEvent: + type: object + properties: + id: + type: integer + format: int32 + description: Id of the streetlight. + lumens: + type: integer + format: int32 + description: Light intensity measured in lumens. + sentAt: + type: string + format: date-time + description: Light intensity measured in lumens. + additionalProperties: false + messages: + lightMeasuredEvent: + payload: + $ref: '#/components/schemas/lightMeasuredEvent' + name: lightMeasuredEvent \ No newline at end of file From a42ab3fd0ce887a9b8944ff85ec593a7122d8052 Mon Sep 17 00:00:00 2001 From: Senn Geerts Date: Sun, 7 Jul 2024 14:18:35 +0200 Subject: [PATCH 19/23] #197 local nuget source folder should exist --- Saunter.sln | 3 ++- local-nuget-source/readme.md | 1 + 2 files changed, 3 insertions(+), 1 deletion(-) create mode 100644 local-nuget-source/readme.md diff --git a/Saunter.sln b/Saunter.sln index 40ce7d40..623bc0e1 100644 --- a/Saunter.sln +++ b/Saunter.sln @@ -19,6 +19,7 @@ Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Solution Items", "Solution ProjectSection(SolutionItems) = preProject .editorconfig = .editorconfig .gitattributes = .gitattributes + .gitignore = .gitignore CHANGELOG.md = CHANGELOG.md .github\workflows\ci.yaml = .github\workflows\ci.yaml nuget.config = nuget.config @@ -36,7 +37,7 @@ Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "AsyncAPI.Saunter.Generator. EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "AsyncAPI.Saunter.Generator.Build", "src\AsyncAPI.Saunter.Generator.Build\AsyncAPI.Saunter.Generator.Build.csproj", "{A320E670-5CB0-4815-AF67-D8D09FC92A2A}" EndProject -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "AsyncAPI.Saunter.Generator.Build.Tests", "test\AsyncAPI.Saunter.Generator.Build.Tests\AsyncAPI.Saunter.Generator.Build.Tests.csproj", "{61142B10-7B49-436E-AE32-2737658BD1E5}" +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "AsyncAPI.Saunter.Generator.Build.Tests", "test\AsyncAPI.Saunter.Generator.Build.Tests\AsyncAPI.Saunter.Generator.Build.Tests.csproj", "{61142B10-7B49-436E-AE32-2737658BD1E5}" EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution diff --git a/local-nuget-source/readme.md b/local-nuget-source/readme.md new file mode 100644 index 00000000..fc5d5494 --- /dev/null +++ b/local-nuget-source/readme.md @@ -0,0 +1 @@ +Place holder, so the local-nuget-source exists. \ No newline at end of file From d3f04727fc0464906b55bd12c68cd6da73708e07 Mon Sep 17 00:00:00 2001 From: Senn Geerts Date: Sun, 7 Jul 2024 14:37:39 +0200 Subject: [PATCH 20/23] #197 update readme's --- .../readme.md | 27 +++++++++++++------ src/AsyncAPI.Saunter.Generator.Cli/readme.md | 7 +++-- 2 files changed, 24 insertions(+), 10 deletions(-) diff --git a/src/AsyncAPI.Saunter.Generator.Build/readme.md b/src/AsyncAPI.Saunter.Generator.Build/readme.md index eca774ac..a8abdddd 100644 --- a/src/AsyncAPI.Saunter.Generator.Build/readme.md +++ b/src/AsyncAPI.Saunter.Generator.Build/readme.md @@ -1,8 +1,19 @@ # AsyncApi Generator.Build Nuget Package A nuget package to generate AsyncAPI specification files at build time, based on code-first attributes. -# Customizations -The AsyncAPI spec generation can be configured through project properties in the csproj-file (or .props files): +This nuget packages can help to better control API changes by commiting the AsyncAPI spec to source control. By always generating spec files at build, it will be clear when the api changes. +Example to include the Generator.Build nuget package only in (local) debug builds: +``` + + + all + runtime; build; native; contentfiles; analyzers; buildtransitive + + +``` + +# Customization Properties +The AsyncAPI spec generation can be configured through project properties in the csproj-file (or included via .props files): ``` @@ -18,10 +29,10 @@ Defaults are the same as the underlying [Generator.Cli tool](https://www.nuget.o If the ```AsyncAPI.Saunter.Generator.Build``` Nuget package is referenced, the default is to generate AsyncAPI spec files at build time. -- AsyncAPIGenerateDocumentsOnBuild: Whether to actually generate AsyncAPI spec files on build (true or false, default: true) -- AsyncAPIDocumentFormats: Format of the expected AsyncAPI spec files (json, yml or yaml, default: json) -- AsyncAPIDocumentOutputPath: Output path for the AsyncAPI spec files, relative to the csproj location. (default is the csproj root path: ./) -- AsyncAPIDocumentNames: The AsyncAPI documents to generate. (default: generate all known documents) -- AsyncAPIDocumentFilename: Template of the AsyncAPI spec files (default: "{document}_asyncapi.{extension}") -- AsyncAPIDocumentEnvVars: Environment variable(s) to set during generation of the AsyncAPI spec files (default: none, Example: "ASPNETCORE_ENVIRONMENT=Development") +- _AsyncAPIGenerateDocumentsOnBuild_: Whether to actually generate AsyncAPI spec files on build (true or false, default: true) +- _AsyncAPIDocumentFormats_: Format of the expected AsyncAPI spec files (json, yml or yaml, default: json) +- _AsyncAPIDocumentOutputPath_: Output path for the AsyncAPI spec files, relative to the csproj location. (default is the csproj root path: ./) +- _AsyncAPIDocumentNames_: The AsyncAPI documents to generate. (default: generate all known documents) +- _AsyncAPIDocumentFilename_: Template of the AsyncAPI spec files (default: "{document}_asyncapi.{extension}") +- _AsyncAPIDocumentEnvVars_: Environment variable(s) to set during generation of the AsyncAPI spec files (default: none, Example: "ASPNETCORE_ENVIRONMENT=Development") None of these properties are mandatory. Only referencing the [AsyncAPI.Saunter.Generator.Build](https://www.nuget.org/packages/AsyncAPI.Saunter.Generator.Build) Nuget package will generate a json AsyncAPI spec file for all AsyncAPI documents. \ No newline at end of file diff --git a/src/AsyncAPI.Saunter.Generator.Cli/readme.md b/src/AsyncAPI.Saunter.Generator.Cli/readme.md index 8eb9a503..72bb6863 100644 --- a/src/AsyncAPI.Saunter.Generator.Cli/readme.md +++ b/src/AsyncAPI.Saunter.Generator.Cli/readme.md @@ -1,11 +1,14 @@ # AsyncApi Generator.Cli Tool -A dotnet tool to generate AsyncAPI specification files based of a dotnet DLL (The application itself). +A dotnet tool to generate AsyncAPI specification files based of a dotnet assembly (The application itself). + +This tool can used to manually generate spec files from a startup assembly or to setup a custom build pipeline. +If you are intressed in always generating spec files at build time, see [AsyncAPI.Saunter.Generator.Build](https://www.nuget.org/packages/AsyncAPI.Saunter.Generator.Build). ## Tool usage ``` dotnet asyncapi tofile --output [output-path] --format [json,yml,yaml] --doc [asyncapi-document-name] [startup-assembly] ``` -startup-assembly: the file path to the entrypoint dotnet DLL that hosts AsyncAPI document(s). +startup-assembly: the file path to the dotnet startup assembly (DLL) that hosts AsyncAPI document(s). ## Tool options - _--doc_: The name of the AsyncAPI document as defined in the startup class by the ```.ConfigureNamedAsyncApi()```-method. If only ```.AddAsyncApiSchemaGeneration()``` is used, the document is unnamed and will always be exported. If not specified, all documents will be exported. From e10112b161658be7e36f84826c517f53597d11f8 Mon Sep 17 00:00:00 2001 From: Senn Geerts Date: Sun, 7 Jul 2024 14:48:38 +0200 Subject: [PATCH 21/23] #197 set streetlights example to depend on the Generator.Build project to populate the local nuget source --- Saunter.sln | 3 +++ 1 file changed, 3 insertions(+) diff --git a/Saunter.sln b/Saunter.sln index 623bc0e1..3bcee188 100644 --- a/Saunter.sln +++ b/Saunter.sln @@ -14,6 +14,9 @@ EndProject Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "examples", "examples", "{6ABD4842-47AF-49A5-B057-0EBA64416789}" EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "StreetlightsAPI", "examples\StreetlightsAPI\StreetlightsAPI.csproj", "{F188D4A7-BBCB-464F-A370-2BD84D18EA79}" + ProjectSection(ProjectDependencies) = postProject + {A320E670-5CB0-4815-AF67-D8D09FC92A2A} = {A320E670-5CB0-4815-AF67-D8D09FC92A2A} + EndProjectSection EndProject Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Solution Items", "Solution Items", "{E0D34C77-924E-4F6B-9289-5A2F07D125A8}" ProjectSection(SolutionItems) = preProject From 4741f5652c76453365fd9c3a67ac860a2cb5936c Mon Sep 17 00:00:00 2001 From: Senn Geerts Date: Sun, 7 Jul 2024 14:54:58 +0200 Subject: [PATCH 22/23] #197 undo streetlights example order, use 2 step build approach --- .github/workflows/ci.yaml | 4 +++- Saunter.sln | 6 +++--- src/Saunter-src.slnf | 10 ++++++++++ 3 files changed, 16 insertions(+), 4 deletions(-) create mode 100644 src/Saunter-src.slnf diff --git a/.github/workflows/ci.yaml b/.github/workflows/ci.yaml index d262e704..5eada2d5 100644 --- a/.github/workflows/ci.yaml +++ b/.github/workflows/ci.yaml @@ -29,7 +29,9 @@ jobs: - name: Run NPM install run: npm ci working-directory: ./src/Saunter.UI - - name: Run dotnet build + - name: Run dotnet build src + run: dotnet build ./src/Saunter-src.slnf --configuration Debug + - name: Run dotnet build all run: dotnet build --configuration Debug - name: Run dotnet test run: dotnet test --no-build diff --git a/Saunter.sln b/Saunter.sln index 3bcee188..5df19524 100644 --- a/Saunter.sln +++ b/Saunter.sln @@ -4,6 +4,9 @@ Microsoft Visual Studio Solution File, Format Version 12.00 VisualStudioVersion = 17.0.31919.166 MinimumVisualStudioVersion = 15.0.26124.0 Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "src", "src", "{28D4C365-FDED-49AE-A97D-36202E24A55A}" + ProjectSection(SolutionItems) = preProject + src\Saunter-src.slnf = src\Saunter-src.slnf + EndProjectSection EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Saunter", "src\Saunter\Saunter.csproj", "{240F263C-4F9B-40E0-8392-1FDB324153F6}" EndProject @@ -14,9 +17,6 @@ EndProject Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "examples", "examples", "{6ABD4842-47AF-49A5-B057-0EBA64416789}" EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "StreetlightsAPI", "examples\StreetlightsAPI\StreetlightsAPI.csproj", "{F188D4A7-BBCB-464F-A370-2BD84D18EA79}" - ProjectSection(ProjectDependencies) = postProject - {A320E670-5CB0-4815-AF67-D8D09FC92A2A} = {A320E670-5CB0-4815-AF67-D8D09FC92A2A} - EndProjectSection EndProject Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Solution Items", "Solution Items", "{E0D34C77-924E-4F6B-9289-5A2F07D125A8}" ProjectSection(SolutionItems) = preProject diff --git a/src/Saunter-src.slnf b/src/Saunter-src.slnf new file mode 100644 index 00000000..c5c27295 --- /dev/null +++ b/src/Saunter-src.slnf @@ -0,0 +1,10 @@ +{ + "solution": { + "path": "..\\Saunter.sln", + "projects": [ + "src\\AsyncAPI.Saunter.Generator.Build\\AsyncAPI.Saunter.Generator.Build.csproj", + "src\\AsyncAPI.Saunter.Generator.Cli\\AsyncAPI.Saunter.Generator.Cli.csproj", + "src\\Saunter\\Saunter.csproj" + ] + } +} \ No newline at end of file From 195dc14fff07a79031357f34dc247ebccab08a4e Mon Sep 17 00:00:00 2001 From: Senn Geerts Date: Sun, 7 Jul 2024 15:14:30 +0200 Subject: [PATCH 23/23] #197 use better path to the dotnet dll in tools and hopefully fix the build pipeline --- .../build/AsyncAPI.Saunter.Generator.Build.targets | 10 +++++++++- 1 file changed, 9 insertions(+), 1 deletion(-) diff --git a/src/AsyncAPI.Saunter.Generator.Build/build/AsyncAPI.Saunter.Generator.Build.targets b/src/AsyncAPI.Saunter.Generator.Build/build/AsyncAPI.Saunter.Generator.Build.targets index 19f35357..c890b89b 100644 --- a/src/AsyncAPI.Saunter.Generator.Build/build/AsyncAPI.Saunter.Generator.Build.targets +++ b/src/AsyncAPI.Saunter.Generator.Build/build/AsyncAPI.Saunter.Generator.Build.targets @@ -2,16 +2,24 @@ + + $([System.IO.Path]::GetDirectoryName($(MSBuildThisFileDirectory))) + $([System.IO.Path]::GetDirectoryName($(AsyncAPIBuildToolBuildDir))) + + + + + - + \ No newline at end of file