Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Additonal Namespaces for generated Types #80

Merged
merged 4 commits into from
Jun 21, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 10 additions & 0 deletions src/Refitter.Core/RefitGenerator.cs
Original file line number Diff line number Diff line change
Expand Up @@ -55,6 +55,16 @@ private string GenerateClient(RefitInterfaceGenerator interfaceGenerator)
code.AppendLine(RefitInterfaceImports.GenerateNamespaceImports(settings))
.AppendLine();

if (settings.AdditionalNamespaces.Any())
{
foreach (var ns in settings.AdditionalNamespaces)
{
code.AppendLine($"using {ns};");
}

code.AppendLine();
}

code.AppendLine($$"""
namespace {{settings.Namespace}}
{
Expand Down
5 changes: 4 additions & 1 deletion src/Refitter.Core/RefitGeneratorSettings.cs
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
using System.Diagnostics.CodeAnalysis;
using System;
using System.Diagnostics.CodeAnalysis;

namespace Refitter.Core;

Expand Down Expand Up @@ -26,6 +27,8 @@ public class RefitGeneratorSettings
public bool UseCancellationTokens { get; set; }

public bool UseIsoDateFormat { get; set; }

public string[] AdditionalNamespaces { get; set; } = Array.Empty<string>();
}

[ExcludeFromCodeCoverage]
Expand Down
109 changes: 109 additions & 0 deletions src/Refitter.Tests/Examples/AdditionalNamespacesTests.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,109 @@
using FluentAssertions;
using Refitter.Core;
using Refitter.Tests.Build;
using Xunit;

namespace Refitter.Tests.Examples;

public class AdditionalNamespacesTests
{
private const string OpenApiSpec = @"
{
""openapi"" : ""3.0.1"",
""paths"" : {
""/api/v1/{id}/foo"" : {
""get"" : {
""tags"" : [ ""foo"" ],
""operationId"" : ""get-/api/v1/{id}/foo_getAll"",
""parameters"" : [ {
""name"" : ""id"",
""in"" : ""path"",
""required"" : true,
""style"" : ""simple"",
""explode"" : false,
""schema"" : {
""type"" : ""integer"",
""format"" : ""int32""
}
} ],
""responses"" : {
""200"" : {
""description"" : ""successful operation""
}
}
}
},
""/api/v1/{id}/bar"" : {
""get"" : {
""tags"" : [ ""bar"" ],
""operationId"" : ""get-/api/v1/{id}/bar_getAll"",
""parameters"" : [ {
""name"" : ""id"",
""in"" : ""path"",
""required"" : true,
""style"" : ""simple"",
""explode"" : false,
""schema"" : {
""type"" : ""integer"",
""format"" : ""int32""
}
} ],
""responses"" : {
""200"" : {
""description"" : ""successful operation""
}
}
}
}
}
}
";

[Fact]
public async Task Can_Generate_Code()
{
string generateCode = await GenerateCode();
generateCode.Should().NotBeNullOrWhiteSpace();
}

[Fact]
public async Task Can_Build_Generated_Code()
{
string generateCode = await GenerateCode();
BuildHelper
.BuildCSharp(generateCode)
.Should()
.BeTrue();
}

[Fact]
public async Task Generated_Types_Contains_Additional_Namespaces()
{
string generateCode = await GenerateCode();
generateCode.Should().Contain("using System.Diagnostics.CodeAnalysis;");
}

private static async Task<string> GenerateCode()
{
var swaggerFile = await CreateSwaggerFile(OpenApiSpec);
var foo = new RefitGeneratorSettings
{
OpenApiPath = swaggerFile,
AdditionalNamespaces = new[] { "System.Text.Json", "System.Diagnostics.CodeAnalysis" },
};

var sut = await RefitGenerator.CreateAsync(foo);
var generateCode = sut.Generate();
return generateCode;
}

private static async Task<string> CreateSwaggerFile(string contents)
{
var filename = $"{Guid.NewGuid()}.yml";
var folder = Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString());
Directory.CreateDirectory(folder);
var swaggerFile = Path.Combine(folder, filename);
await File.WriteAllTextAsync(swaggerFile, contents);
return swaggerFile;
}
}
11 changes: 6 additions & 5 deletions src/Refitter/GenerateCommand.cs
Original file line number Diff line number Diff line change
Expand Up @@ -33,29 +33,30 @@ public override async Task<int> ExecuteAsync(CommandContext context, Settings se
UseIsoDateFormat = settings.UseIsoDateFormat,
TypeAccessibility = settings.InternalTypeAccessibility
? TypeAccessibility.Internal
: TypeAccessibility.Public
: TypeAccessibility.Public,
AdditionalNamespaces = settings.AdditionalNamespaces!,
};

var crlf = Environment.NewLine;
try
{
AnsiConsole.MarkupLine($"[green]Support key: {SupportInformation.GetSupportKey()}[/]");

var generator = await RefitGenerator.CreateAsync(refitGeneratorSettings);
var code = generator.Generate().ReplaceLineEndings();
AnsiConsole.MarkupLine($"[green]Length: {code.Length} bytes[/]");

if (!string.IsNullOrWhiteSpace(settings.OutputPath))
{
var directory = Path.GetDirectoryName(settings.OutputPath);
if (!string.IsNullOrWhiteSpace(directory) && !Directory.Exists(directory))
Directory.CreateDirectory(directory);
}

var outputPath = settings.OutputPath ?? "Output.cs";
AnsiConsole.MarkupLine($"[green]Output: {Path.GetFullPath(outputPath)}{crlf}[/]");
await File.WriteAllTextAsync(outputPath, code);

await Analytics.LogFeatureUsage(settings);
return 0;
}
Expand Down
10 changes: 10 additions & 0 deletions src/Refitter/Program.cs
Original file line number Diff line number Diff line change
Expand Up @@ -88,6 +88,16 @@
"./openapi.json",
"--use-iso-date-format"
});
configuration
.AddExample(
new[]
{
"./openapi.json",
"--additional-namespace",
"\"Your.Additional.Namespace\"",
"--additional-namespace",
"\"Your.Other.Additional.Namespace\"",
});
});

return app.Run(args);
7 changes: 6 additions & 1 deletion src/Refitter/Settings.cs
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
using System.ComponentModel;
using Spectre.Console.Cli;
using System.ComponentModel;

namespace Refitter;

Expand Down Expand Up @@ -58,4 +58,9 @@ public sealed class Settings : CommandSettings
[CommandOption("--use-iso-date-format")]
[DefaultValue(false)]
public bool UseIsoDateFormat { get; set; }

[Description("Add additional namespace to generated types")]
[CommandOption("--additional-namespace")]
[DefaultValue(new string[0])]
public string[]? AdditionalNamespaces { get; set; }
}