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

Disposable interfaces #964

Merged
merged 4 commits into from
Nov 23, 2020
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
Original file line number Diff line number Diff line change
Expand Up @@ -70,9 +70,12 @@ namespace {{Namespace}}
var func = requestBuilder.BuildRestResultFuncForMethod("{{Name}}", new Type[] { {{ArgumentTypesList}} }{{#MethodTypeParameterList}}, new Type[] { {{.}} }{{/MethodTypeParameterList}});
return ({{ReturnType}})func(Client, arguments);
{{/IsRefitMethod}}
{{^IsRefitMethod}}
{{#IsDispose}}
Client?.Dispose();
{{/IsDispose}}
{{#UnsupportedMethod}}
throw new NotImplementedException("Either this method has no Refit HTTP method attribute or you've used something other than a string literal for the 'path' argument.");
{{/IsRefitMethod}}
{{/UnsupportedMethod}}
}
{{/MethodList}}
{{#HasAnyMethodsWithNullableArguments}}
Expand Down
22 changes: 19 additions & 3 deletions InterfaceStubGenerator.Core/InterfaceStubGenerator.cs
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@

namespace Refit.Generator
{
// * Search for all Interfaces, find the method definitions
// * Search for all Interfaces, find the method definitions
// and make sure there's at least one Refit attribute on one
// * Generate the data we need for the template based on interface method
// defn's
Expand Down Expand Up @@ -70,7 +70,7 @@ public List<InterfaceDeclarationSyntax> FindInterfacesToGenerate(SyntaxTree tree
{
var nodes = tree.GetRoot().DescendantNodes().ToList();

// Make sure this file imports Refit. If not, we're not going to
// Make sure this file imports Refit. If not, we're not going to
// find any Refit interfaces
// NB: This falls down in the tests unless we add an explicit "using Refit;",
// but we can rely on this being there in any other file
Expand Down Expand Up @@ -170,6 +170,20 @@ public ClassTemplateInfo GenerateClassInfoForInterface(InterfaceDeclarationSynta
return mti;
})
.ToList();

if (ret.BaseClasses?.Any(x => x.Name == nameof(IDisposable)) == true)
{
ret.MethodList.Add(new MethodTemplateInfo
{
Name = nameof(IDisposable.Dispose),
ReturnTypeInfo = new TypeInfo {Name = "void"},
ArgumentListInfo = new List<ArgumentInfo>(),
IsRefitMethod = false,
IsDispose = true,
InterfaceName = nameof(IDisposable),
});
}

return ret;
}

Expand Down Expand Up @@ -365,7 +379,7 @@ public void GenerateWarnings(List<InterfaceDeclarationSyntax> interfacesToGenera

public bool HasRefitHttpMethodAttribute(MethodDeclarationSyntax method)
{
// We could also verify that the single argument is a string,
// We could also verify that the single argument is a string,
// but what if somebody is dumb and uses a constant?
// Could be turtles all the way down.
return method.AttributeLists.SelectMany(a => a.Attributes)
Expand Down Expand Up @@ -457,6 +471,8 @@ public class MethodTemplateInfo
public string ArgumentListWithTypes => ArgumentListInfo != null ? string.Join(", ", ArgumentListInfo.Select(y => $"{y.TypeInfo} {y.Name}")) : null;
public string ArgumentTypesList => ArgumentListInfo != null ? string.Join(", ", ArgumentListInfo.Select(y => y.TypeInfo.ToString() is var typeName && typeName.EndsWith("?") ? $"ToNullable(typeof({typeName.Remove(typeName.Length - 1)}))" : $"typeof({typeName})")) : null;
public bool IsRefitMethod { get; set; }
public bool IsDispose { get; set; }
public bool UnsupportedMethod => !IsRefitMethod && !IsDispose;
public string Name { get; set; }
public TypeInfo ReturnTypeInfo { get; set; }
public string ReturnType => ReturnTypeInfo.ToString();
Expand Down
6 changes: 6 additions & 0 deletions Refit.Tests/GitHubApi.cs
Original file line number Diff line number Diff line change
Expand Up @@ -93,6 +93,12 @@ public interface IGitHubApi
Task<ApiResponse<User>> CreateUserWithMetadata(User user);
}

public interface IGitHubApiDisposable : IDisposable
{
[Get("whatever")]
Task RefitMethod();
}

public class TestNested
{
[Headers("User-Agent: Refit Integration Tests")]
Expand Down
25 changes: 22 additions & 3 deletions Refit.Tests/InterfaceStubGenerator.cs
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
using System.Collections.Generic;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
Expand All @@ -9,7 +10,6 @@

using Refit; // InterfaceStubGenerator looks for this
using Refit.Generator;

using Xunit;

using Task = System.Threading.Tasks.Task;
Expand Down Expand Up @@ -41,7 +41,7 @@ public void FindInterfacesSmokeTest()
var fixture = new InterfaceStubGenerator();

var result = fixture.FindInterfacesToGenerate(CSharpSyntaxTree.ParseText(File.ReadAllText(input)));
Assert.Equal(2, result.Count);
Assert.Equal(3, result.Count);
Assert.Contains(result, x => x.Identifier.ValueText == "IGitHubApi");

input = IntegrationTestHelper.GetPath("InterfaceStubGenerator.cs");
Expand Down Expand Up @@ -95,6 +95,25 @@ public void GenerateClassInfoForInterfaceSmokeTest()
Assert.Equal("IGitHubApi", result.GeneratedClassSuffix);
}

[Fact]
public void GenerateClassInfoForDisposableInterfaceSmokeTest()
{
var file = CSharpSyntaxTree.ParseText(File.ReadAllText(IntegrationTestHelper.GetPath("GitHubApi.cs")));
var fixture = new InterfaceStubGenerator();

var input = file.GetRoot().DescendantNodes()
.OfType<InterfaceDeclarationSyntax>()
.First(x => x.Identifier.ValueText == "IGitHubApiDisposable");

var result = fixture.GenerateClassInfoForInterface(input);

Assert.Equal(2, result.MethodList.Count);
Assert.Equal("RefitMethod", result.MethodList[0].Name);
Assert.Equal("Dispose", result.MethodList[1].Name);
Assert.Equal("IGitHubApiDisposable", result.InterfaceName);
Assert.Equal("IGitHubApiDisposable", result.GeneratedClassSuffix);
}

[Fact]
public void GenerateClassInfoForNestedInterfaceSmokeTest()
{
Expand Down
48 changes: 48 additions & 0 deletions Refit.Tests/RefitStubs.Net46.cs
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,7 @@ sealed class PreserveAttribute : Attribute
#pragma warning disable CS8669 // The annotation for nullable reference types should only be used in code within a '#nullable' annotations context. Auto-generated code requires an explicit '#nullable' directive in source.
namespace Refit.Tests
{
using global::System;
using global::System.Collections.Generic;
using global::System.IO;
using global::System.Linq;
Expand Down Expand Up @@ -696,6 +697,7 @@ Task IBodylessApi.Head()

namespace Refit.Tests
{
using global::System;
using global::System.Collections.Generic;
using global::System.IO;
using global::System.Linq;
Expand Down Expand Up @@ -1659,6 +1661,51 @@ Task<ApiResponse<User>> IGitHubApi.CreateUserWithMetadata(User user)
}
}

namespace Refit.Tests
{
using global::System;
using global::System.Collections.Generic;
using global::System.Linq;
using global::System.Net.Http;
using global::System.Text;
using global::System.Threading.Tasks;
using global::Refit;
using static global::System.Math;

/// <inheritdoc />
[global::System.Diagnostics.CodeAnalysis.ExcludeFromCodeCoverage]
[global::System.Diagnostics.DebuggerNonUserCode]
[Preserve]
[global::System.Reflection.Obfuscation(Exclude=true)]
partial class AutoGeneratedIGitHubApiDisposable : IGitHubApiDisposable
{
/// <inheritdoc />
public HttpClient Client { get; protected set; }
readonly IRequestBuilder requestBuilder;

/// <inheritdoc />
public AutoGeneratedIGitHubApiDisposable(HttpClient client, IRequestBuilder requestBuilder)
{
Client = client;
this.requestBuilder = requestBuilder;
}

/// <inheritdoc />
Task IGitHubApiDisposable.RefitMethod()
{
var arguments = new object[] { };
var func = requestBuilder.BuildRestResultFuncForMethod("RefitMethod", new Type[] { });
return (Task)func(Client, arguments);
}

/// <inheritdoc />
void IDisposable.Dispose()
{
Client?.Dispose();
}
}
}

namespace Refit.Tests
{
using global::System;
Expand Down Expand Up @@ -2146,6 +2193,7 @@ Task<ResponseModel> IAmInterfaceF_RequireUsing.Get(List<Guid> guids)

namespace Refit.Tests
{
using global::System;
using global::System.Collections.Generic;
using global::System.IO;
using global::System.Linq;
Expand Down
48 changes: 48 additions & 0 deletions Refit.Tests/RefitStubs.Net5.cs
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,7 @@ sealed class PreserveAttribute : Attribute
#pragma warning disable CS8669 // The annotation for nullable reference types should only be used in code within a '#nullable' annotations context. Auto-generated code requires an explicit '#nullable' directive in source.
namespace Refit.Tests
{
using global::System;
using global::System.Collections.Generic;
using global::System.IO;
using global::System.Linq;
Expand Down Expand Up @@ -696,6 +697,7 @@ Task IBodylessApi.Head()

namespace Refit.Tests
{
using global::System;
using global::System.Collections.Generic;
using global::System.IO;
using global::System.Linq;
Expand Down Expand Up @@ -1659,6 +1661,51 @@ Task<ApiResponse<User>> IGitHubApi.CreateUserWithMetadata(User user)
}
}

namespace Refit.Tests
{
using global::System;
using global::System.Collections.Generic;
using global::System.Linq;
using global::System.Net.Http;
using global::System.Text;
using global::System.Threading.Tasks;
using global::Refit;
using static global::System.Math;

/// <inheritdoc />
[global::System.Diagnostics.CodeAnalysis.ExcludeFromCodeCoverage]
[global::System.Diagnostics.DebuggerNonUserCode]
[Preserve]
[global::System.Reflection.Obfuscation(Exclude=true)]
partial class AutoGeneratedIGitHubApiDisposable : IGitHubApiDisposable
{
/// <inheritdoc />
public HttpClient Client { get; protected set; }
readonly IRequestBuilder requestBuilder;

/// <inheritdoc />
public AutoGeneratedIGitHubApiDisposable(HttpClient client, IRequestBuilder requestBuilder)
{
Client = client;
this.requestBuilder = requestBuilder;
}

/// <inheritdoc />
Task IGitHubApiDisposable.RefitMethod()
{
var arguments = new object[] { };
var func = requestBuilder.BuildRestResultFuncForMethod("RefitMethod", new Type[] { });
return (Task)func(Client, arguments);
}

/// <inheritdoc />
void IDisposable.Dispose()
{
Client?.Dispose();
}
}
}

namespace Refit.Tests
{
using global::System;
Expand Down Expand Up @@ -2146,6 +2193,7 @@ Task<ResponseModel> IAmInterfaceF_RequireUsing.Get(List<Guid> guids)

namespace Refit.Tests
{
using global::System;
using global::System.Collections.Generic;
using global::System.IO;
using global::System.Linq;
Expand Down
48 changes: 48 additions & 0 deletions Refit.Tests/RefitStubs.NetCore2.cs
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,7 @@ sealed class PreserveAttribute : Attribute
#pragma warning disable CS8669 // The annotation for nullable reference types should only be used in code within a '#nullable' annotations context. Auto-generated code requires an explicit '#nullable' directive in source.
namespace Refit.Tests
{
using global::System;
using global::System.Collections.Generic;
using global::System.IO;
using global::System.Linq;
Expand Down Expand Up @@ -696,6 +697,7 @@ Task IBodylessApi.Head()

namespace Refit.Tests
{
using global::System;
using global::System.Collections.Generic;
using global::System.IO;
using global::System.Linq;
Expand Down Expand Up @@ -1659,6 +1661,51 @@ Task<ApiResponse<User>> IGitHubApi.CreateUserWithMetadata(User user)
}
}

namespace Refit.Tests
{
using global::System;
using global::System.Collections.Generic;
using global::System.Linq;
using global::System.Net.Http;
using global::System.Text;
using global::System.Threading.Tasks;
using global::Refit;
using static global::System.Math;

/// <inheritdoc />
[global::System.Diagnostics.CodeAnalysis.ExcludeFromCodeCoverage]
[global::System.Diagnostics.DebuggerNonUserCode]
[Preserve]
[global::System.Reflection.Obfuscation(Exclude=true)]
partial class AutoGeneratedIGitHubApiDisposable : IGitHubApiDisposable
{
/// <inheritdoc />
public HttpClient Client { get; protected set; }
readonly IRequestBuilder requestBuilder;

/// <inheritdoc />
public AutoGeneratedIGitHubApiDisposable(HttpClient client, IRequestBuilder requestBuilder)
{
Client = client;
this.requestBuilder = requestBuilder;
}

/// <inheritdoc />
Task IGitHubApiDisposable.RefitMethod()
{
var arguments = new object[] { };
var func = requestBuilder.BuildRestResultFuncForMethod("RefitMethod", new Type[] { });
return (Task)func(Client, arguments);
}

/// <inheritdoc />
void IDisposable.Dispose()
{
Client?.Dispose();
}
}
}

namespace Refit.Tests
{
using global::System;
Expand Down Expand Up @@ -2146,6 +2193,7 @@ Task<ResponseModel> IAmInterfaceF_RequireUsing.Get(List<Guid> guids)

namespace Refit.Tests
{
using global::System;
using global::System.Collections.Generic;
using global::System.IO;
using global::System.Linq;
Expand Down
Loading