forked from asyncapi/saunter
-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
asyncapi#207 generate code from spec: json only code generation
- Loading branch information
Senn Geerts
authored and
Senn Geerts
committed
Jul 20, 2024
1 parent
4af2a99
commit 23b8e4c
Showing
12 changed files
with
325 additions
and
36 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
138 changes: 138 additions & 0 deletions
138
src/AsyncAPI.Saunter.Generator.Cli/FromSpec/AsyncApiInterface/AsyncApiGenerator.cs
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,138 @@ | ||
using System.Reflection; | ||
using System.Text; | ||
using CaseConverter; | ||
using LEGO.AsyncAPI.Models; | ||
using LEGO.AsyncAPI.Readers; | ||
|
||
namespace AsyncAPI.Saunter.Generator.Cli.FromSpec.AsyncApiInterface; | ||
|
||
internal interface IAsyncApiGenerator | ||
{ | ||
string GenerateAsyncApiInterfaces(GeneratorOptions options, string text, AsyncApiState state); | ||
|
||
string GenerateAsyncApiInterfaces(GeneratorOptions options, AsyncApiDocument asyncApi, AsyncApiState state); | ||
} | ||
|
||
internal class AsyncApiGenerator : IAsyncApiGenerator | ||
{ | ||
private readonly string _version; | ||
private readonly string _name; | ||
|
||
public AsyncApiGenerator() | ||
{ | ||
var assembly = Assembly.GetExecutingAssembly().GetName(); | ||
|
||
this._version = assembly.Version!.ToString(); | ||
this._name = assembly.Name; | ||
} | ||
|
||
private static string MakeGlobalDocumentTopic(string name) => $"TOPIC_{name.ToSnakeCase().ToUpperInvariant()}"; | ||
|
||
public string GenerateAsyncApiInterfaces(GeneratorOptions options, string text, AsyncApiState state) | ||
{ | ||
var asyncApi = new AsyncApiStringReader().Read(text, out var diagnostic); | ||
return this.GenerateAsyncApiInterfaces(options, asyncApi, state); | ||
} | ||
|
||
public string GenerateAsyncApiInterfaces(GeneratorOptions options, AsyncApiDocument asyncApi, AsyncApiState state) | ||
{ | ||
var sb = new StringBuilder( | ||
$$""" | ||
//---------------------- | ||
// <auto-generated> | ||
// Generated using {{this._name}} v{{this._version}} | ||
// At: {{DateTime.Now:U}} | ||
// </auto-generated> | ||
//---------------------- | ||
|
||
using Saunter.Attributes; | ||
using System.CodeDom.Compiler; | ||
|
||
namespace {{options.Namespace}} | ||
{ | ||
{{this.GetGeneratedCodeAttributeLine()}} | ||
public static partial class {{options.TopicsClassName}} | ||
{ | ||
"""); | ||
|
||
sb.AppendLine(); | ||
sb.AppendLine($" public const string {MakeGlobalDocumentTopic(options.ClassName)} = \"{options.ClassName.ToPascalCase()}\";"); | ||
sb.AppendLine(" }"); | ||
sb.AppendLine(); | ||
|
||
// Commands | ||
this.AddInterface(sb, options, options.ClassName, $"{options.ClassName}Commands", new("SubscribeOperation", "command", x => x.Subscribe), asyncApi.Channels.Where(x => x.Value.Subscribe != null)); | ||
sb.AppendLine(); | ||
|
||
// Events | ||
this.AddInterface(sb, options, options.ClassName, $"{options.ClassName}Events", new("PublishOperation", "evt", x => x.Publish), asyncApi.Channels.Where(x => x.Value.Publish != null)); | ||
|
||
sb.AppendLine("}"); // close namespace | ||
sb.AppendLine(); | ||
|
||
state.Documents.Add(options.ClassName); | ||
var contents = sb.ToString(); | ||
return contents; | ||
} | ||
|
||
private string GetGeneratedCodeAttributeLine() => $" [GeneratedCodeAttribute(\"{this._name}\", \"{this._version}\")]"; | ||
|
||
private void AddInterface(StringBuilder sb, GeneratorOptions genOptions, string specName, string className, OperationOptions options, IEnumerable<KeyValuePair<string, AsyncApiChannel>> channels) | ||
{ | ||
sb.AppendLine($" [AsyncApi({genOptions.TopicsClassName}.{MakeGlobalDocumentTopic(specName)})]"); | ||
sb.AppendLine(this.GetGeneratedCodeAttributeLine()); | ||
sb.AppendLine($" public interface I{className}"); | ||
sb.Append(" {"); | ||
|
||
foreach (var channel in channels) | ||
{ | ||
AddChannelOperation(sb, options, channel); | ||
} | ||
|
||
sb.AppendLine(" }"); | ||
} | ||
|
||
private record OperationOptions(string OperationAttribute, string VarName, Func<AsyncApiChannel, AsyncApiOperation> OperationProvider); | ||
|
||
private static void AddChannelOperation(StringBuilder sb, OperationOptions options, KeyValuePair<string, AsyncApiChannel> channel) | ||
{ | ||
var operation = options.OperationProvider(channel.Value); | ||
|
||
sb.AppendLine(); | ||
sb.AppendLine($" [Channel(\"{channel.Key}\")]"); | ||
var channelParametersSb = new StringBuilder(); | ||
foreach (var channelParameter in channel.Value.Parameters) | ||
{ | ||
var refName = FromReference(channelParameter.Value.Reference.Reference); | ||
var typeName = refName.ToPascalCase(); | ||
if (channelParameter.Value.Schema.Enum.Any()) | ||
{ | ||
typeName += "s"; | ||
} | ||
var varName = refName.ToCamelCase(); | ||
sb.AppendLine($" [ChannelParameter(\"{channelParameter.Key}\", typeof({typeName}), Description = \"{channelParameter.Value.Description}\")]"); | ||
|
||
channelParametersSb.Append(", "); | ||
channelParametersSb.Append(typeName); | ||
channelParametersSb.Append(" "); | ||
channelParametersSb.Append(varName); | ||
} | ||
|
||
var msg = operation.Message.Single(); | ||
var msgTypeName = (msg.Name ?? msg.Payload.Reference.Id).ToPascalCase(); | ||
sb.AppendLine($" [{options.OperationAttribute}(typeof({msgTypeName}), Summary = \"{operation.Summary}\", Description = \"{operation.Description}\")]"); | ||
sb.Append($" void {operation.OperationId}({msgTypeName} {options.VarName}"); | ||
sb.Append(channelParametersSb); | ||
sb.AppendLine(");"); | ||
} | ||
|
||
private static string FromReference(string reference) | ||
{ | ||
var prefix = "#/components/parameters/"; | ||
if (reference.IndexOf(prefix) == 0) | ||
{ | ||
return reference[prefix.Length..]; | ||
} | ||
throw new ArgumentException($"Invalid reference: {reference}"); | ||
} | ||
} |
6 changes: 6 additions & 0 deletions
6
src/AsyncAPI.Saunter.Generator.Cli/FromSpec/AsyncApiInterface/AsyncApiState.cs
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,6 @@ | ||
namespace AsyncAPI.Saunter.Generator.Cli.FromSpec.AsyncApiInterface; | ||
|
||
internal class AsyncApiState | ||
{ | ||
public List<string> Documents { get; } = new(); | ||
} |
41 changes: 41 additions & 0 deletions
41
src/AsyncAPI.Saunter.Generator.Cli/FromSpec/DataTypes/DataTypesGenerator.cs
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,41 @@ | ||
using NJsonSchema; | ||
using NSwag.CodeGeneration.CSharp; | ||
using NSwag; | ||
using NJsonSchema.CodeGeneration.CSharp; | ||
|
||
|
||
namespace AsyncAPI.Saunter.Generator.Cli.FromSpec.DataTypes; | ||
|
||
internal interface IDataTypesGenerator | ||
{ | ||
Task<string> GenerateDataTypesAsync(GeneratorOptions options, string spec, DataTypesGeneratorState state); | ||
} | ||
|
||
internal class NSwagGenerator : IDataTypesGenerator | ||
{ | ||
public async Task<string> GenerateDataTypesAsync(GeneratorOptions options, string spec, DataTypesGeneratorState state) | ||
{ | ||
spec = OpenApiCompatibility.PrepareSpecFile(spec); | ||
|
||
var document = await OpenApiDocument.FromJsonAsync(spec).ConfigureAwait(false); | ||
var settings = new CSharpClientGeneratorSettings | ||
{ | ||
CSharpGeneratorSettings = | ||
{ | ||
Namespace = options.Namespace, | ||
SchemaType = SchemaType.OpenApi3, | ||
ClassStyle = CSharpClassStyle.Record, | ||
ExcludedTypeNames = state.AlreadyGeneratedDataTypes.ToArray(), | ||
}, | ||
GenerateClientClasses = false, | ||
AdditionalNamespaceUsages = state.AlreadyGeneratedNamespaces.ToArray() | ||
}; | ||
|
||
var generator = new CSharpClientGenerator(document, settings); | ||
var contents = generator.GenerateFile(); | ||
state.AlreadyGeneratedDataTypes.AddRange(document.Definitions.Keys); | ||
state.AlreadyGeneratedNamespaces.Add(options.Namespace); | ||
|
||
return contents; | ||
} | ||
} |
8 changes: 8 additions & 0 deletions
8
src/AsyncAPI.Saunter.Generator.Cli/FromSpec/DataTypes/DataTypesGeneratorState.cs
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,8 @@ | ||
namespace AsyncAPI.Saunter.Generator.Cli.FromSpec.DataTypes; | ||
|
||
internal class DataTypesGeneratorState | ||
{ | ||
public List<string> AlreadyGeneratedDataTypes { get; } = new(); | ||
|
||
public List<string> AlreadyGeneratedNamespaces { get; } = new(); | ||
} |
23 changes: 23 additions & 0 deletions
23
src/AsyncAPI.Saunter.Generator.Cli/FromSpec/DataTypes/OpenApiCompatibility.cs
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,23 @@ | ||
using Newtonsoft.Json.Linq; | ||
using Newtonsoft.Json; | ||
|
||
namespace AsyncAPI.Saunter.Generator.Cli.FromSpec.DataTypes; | ||
|
||
internal static class OpenApiCompatibility | ||
{ | ||
internal static string PrepareSpecFile(string spec) | ||
{ | ||
var json = (JObject)JsonConvert.DeserializeObject(spec); | ||
// the type is important for NSwag | ||
if (!json.ContainsKey("openapi")) | ||
{ | ||
json.Add("openapi", "3.0.1"); | ||
} | ||
// NSwag doesn't understand the servers format of AsyncApi, and it is not needed anyway. | ||
if (json.ContainsKey("servers")) | ||
{ | ||
json.Remove("servers"); | ||
} | ||
return JsonConvert.SerializeObject(json); | ||
} | ||
} |
Oops, something went wrong.