57 lines
2.6 KiB
C#
57 lines
2.6 KiB
C#
|
using System.Diagnostics.CodeAnalysis;
|
||
|
using System.Text;
|
||
|
using Cocona;
|
||
|
using NJsonSchema.CodeGeneration.CSharp;
|
||
|
using NSwag;
|
||
|
using NSwag.CodeGeneration.CSharp;
|
||
|
using Terminal.Validation;
|
||
|
|
||
|
namespace Terminal.Commands;
|
||
|
|
||
|
[SuppressMessage("ReSharper", "ClassNeverInstantiated.Global")]
|
||
|
public class GenerateCommands
|
||
|
{
|
||
|
[Command(Aliases = ["generate"], Description = "Generate a client from an OpenAPI document")]
|
||
|
public async Task Gen(
|
||
|
[Option(shortName: 'a', Description = "The address of the OpenAPI document, e.g. 'https://petstore.swagger.io/v2/swagger.json'")]
|
||
|
Uri address,
|
||
|
|
||
|
[Option(shortName: 'd', Description = "The destination file, e.g. 'PetStoreClient.cs'. You can use a relative or absolute path and use any environment variables.")]
|
||
|
[ValidPath]
|
||
|
string destinationFile,
|
||
|
|
||
|
[Option(shortName: 'n', Description = "The namespace of the generated client, e.g. 'MyApp.API.PetStoreClient'")]
|
||
|
string nameSpace = "API_Client",
|
||
|
|
||
|
[Option(shortName: 'c', Description = "The class name of the generated client, e.g. 'PetStoreClient'. You might want to use '{controller}' as a placeholder for the controller name.")]
|
||
|
string className = "{controller}Client",
|
||
|
|
||
|
[Option(shortName: 'b', Description = "Expose the base URL as a property in the generated client? (Default: false)")]
|
||
|
bool exposeBaseUrl = false,
|
||
|
|
||
|
[Option(shortName: 'i', Description = "The base interface of the generated client(s), e.g. 'IPetStoreClient'")]
|
||
|
string? baseInterface = null)
|
||
|
{
|
||
|
using var httpClient = new HttpClient();
|
||
|
var result = await httpClient.GetAsync(address);
|
||
|
var openAPI = await OpenApiDocument.FromJsonAsync(await result.Content.ReadAsStringAsync());
|
||
|
var generator = new CSharpClientGenerator(openAPI, new CSharpClientGeneratorSettings
|
||
|
{
|
||
|
UseBaseUrl = exposeBaseUrl,
|
||
|
ClientBaseInterface = baseInterface,
|
||
|
GenerateClientInterfaces = baseInterface is not null,
|
||
|
ClassName = className,
|
||
|
CSharpGeneratorSettings =
|
||
|
{
|
||
|
Namespace = nameSpace,
|
||
|
JsonLibrary = CSharpJsonLibrary.SystemTextJson,
|
||
|
}
|
||
|
});
|
||
|
|
||
|
var apiClientCode = generator.GenerateFile();
|
||
|
|
||
|
destinationFile = Environment.ExpandEnvironmentVariables(destinationFile);
|
||
|
await File.WriteAllTextAsync(destinationFile, apiClientCode, Encoding.UTF8);
|
||
|
Console.WriteLine($"Generated client(s) for '{address}' and saved it to '{destinationFile}'");
|
||
|
}
|
||
|
}
|