Skip to content

Commit 025b273

Browse files
dahlbyknulltoken
authored andcommitted
Ensure public extension methods always target interfaces or enums
1 parent 73d7ea7 commit 025b273

File tree

1 file changed

+34
-0
lines changed

1 file changed

+34
-0
lines changed

LibGit2Sharp.Tests/MetaFixture.cs

Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,10 @@
11
using System;
22
using System.Collections.Generic;
33
using System.Diagnostics;
4+
using System.Globalization;
45
using System.Linq;
56
using System.Reflection;
7+
using System.Runtime.CompilerServices;
68
using System.Text;
79
using LibGit2Sharp.Tests.TestHelpers;
810
using Xunit;
@@ -344,6 +346,38 @@ where p.IsOptional
344346

345347
Assert.Equal("", sb.ToString());
346348
}
349+
350+
[Fact]
351+
public void PublicExtensionMethodsShouldonlyTargetInterfacesOrEnums()
352+
{
353+
IEnumerable<string> mis =
354+
from m in GetInvalidPublicExtensionMethods()
355+
select m.DeclaringType + "." + m.Name;
356+
357+
var sb = new StringBuilder();
358+
359+
foreach (var method in mis.Distinct())
360+
{
361+
sb.AppendFormat("'{0}' is a public extension method that doesn't target an interface or an enum.{1}",
362+
method, Environment.NewLine);
363+
}
364+
365+
Assert.Equal("", sb.ToString());
366+
}
367+
368+
// Inspired from http://stackoverflow.com/a/299526
369+
370+
static IEnumerable<MethodInfo> GetInvalidPublicExtensionMethods()
371+
{
372+
var query = from type in (Assembly.GetAssembly(typeof(IRepository))).GetTypes()
373+
where type.IsSealed && !type.IsGenericType && !type.IsNested && type.IsPublic
374+
from method in type.GetMethods(BindingFlags.Static | BindingFlags.Public)
375+
where method.IsDefined(typeof(ExtensionAttribute), false)
376+
let parameterType = method.GetParameters()[0].ParameterType
377+
where parameterType != null && !parameterType.IsInterface && !parameterType.IsEnum
378+
select method;
379+
return query;
380+
}
347381
}
348382

349383
internal static class TypeExtensions

0 commit comments

Comments
 (0)