|
1 | 1 | using System;
|
2 | 2 | using System.Collections.Generic;
|
3 | 3 | using System.Diagnostics;
|
| 4 | +using System.Globalization; |
4 | 5 | using System.Linq;
|
5 | 6 | using System.Reflection;
|
| 7 | +using System.Runtime.CompilerServices; |
6 | 8 | using System.Text;
|
7 | 9 | using LibGit2Sharp.Tests.TestHelpers;
|
8 | 10 | using Xunit;
|
@@ -344,6 +346,38 @@ where p.IsOptional
|
344 | 346 |
|
345 | 347 | Assert.Equal("", sb.ToString());
|
346 | 348 | }
|
| 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 | + } |
347 | 381 | }
|
348 | 382 |
|
349 | 383 | internal static class TypeExtensions
|
|
0 commit comments