Skip to content

Commit

Permalink
Add compact formatting
Browse files Browse the repository at this point in the history
  • Loading branch information
Banane9 committed Apr 19, 2024
1 parent eb63ffa commit b1f9a83
Show file tree
Hide file tree
Showing 2 changed files with 67 additions and 1 deletion.
2 changes: 1 addition & 1 deletion MonkeyLoader/MonkeyLoader.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@
<GeneratePackageOnBuild>True</GeneratePackageOnBuild>
<Title>MonkeyLoader</Title>
<Authors>Banane9</Authors>
<Version>0.15.0-beta</Version>
<Version>0.15.1-beta</Version>
<Description>A convenience and extendability focused mod loader using NuGet packages.</Description>
<PackageReadmeFile>README.md</PackageReadmeFile>
<PackageLicenseExpression>LGPL-3.0-or-later</PackageLicenseExpression>
Expand Down
66 changes: 66 additions & 0 deletions MonkeyLoader/ReflectionExtensions.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,66 @@
using HarmonyLib;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;

namespace MonkeyLoader
{
/// <summary>
/// Contains helpful methods to help with reflection.
/// </summary>
public static class ReflectionExtensions
{
/// <summary>
/// Gets a compact, human-readable description of a type.
/// </summary>
/// <param name="type">The type to format.</param>
/// <returns>The human-readable description of the type.</returns>
public static string CompactDescription(this Type type)
{
if (type is null)
return "null";

if (type.IsGenericType)
return $"{type.Name}<{type.GetGenericArguments().Select(CompactDescription).Join()}>";

return type.Name;
}

/// <summary>
/// Gets a compact, human-readable description of any kind of method without assembly details but with generics.
/// </summary>
/// <param name="member">The method to format.</param>
/// <returns>The human-readable description of the method.</returns>
///
public static string CompactDescription(this MethodBase member)
{
if (member is null)
return "null";

var returnType = AccessTools.GetReturnedType(member);

var result = new StringBuilder();
if (member.IsStatic)
result.Append("static ");

if (member.IsAbstract)
result.Append("abstract ");

if (member.IsVirtual)
result.Append("virtual ");

result.Append($"{returnType.CompactDescription()} ");

if (member.DeclaringType is not null)
result.Append($"{member.DeclaringType.CompactDescription()}::");

var parameterString = member.GetParameters().Join(p => $"{p.ParameterType.CompactDescription()} {p.Name}");
result.Append($"{member.Name}({parameterString})");

return result.ToString();
}
}
}

0 comments on commit b1f9a83

Please sign in to comment.