From 948c800a98f00b1bdcfd05ee6228e3423f9eb465 Mon Sep 17 00:00:00 2001 From: Jesse Plamondon-Willard Date: Fri, 30 Jul 2021 00:54:15 -0400 Subject: migrate to the new Harmony patch pattern used in my mods That improves validation and error-handling. --- src/SMAPI.Internal.Patching/BasePatcher.cs | 54 ++++++++++++++++++++++++++++++ 1 file changed, 54 insertions(+) create mode 100644 src/SMAPI.Internal.Patching/BasePatcher.cs (limited to 'src/SMAPI.Internal.Patching/BasePatcher.cs') diff --git a/src/SMAPI.Internal.Patching/BasePatcher.cs b/src/SMAPI.Internal.Patching/BasePatcher.cs new file mode 100644 index 00000000..87155d7f --- /dev/null +++ b/src/SMAPI.Internal.Patching/BasePatcher.cs @@ -0,0 +1,54 @@ +using System; +using System.Reflection; +using HarmonyLib; + +namespace StardewModdingAPI.Internal.Patching +{ + /// Provides base implementation logic for instances. + internal abstract class BasePatcher : IPatcher + { + /********* + ** Public methods + *********/ + /// + public abstract void Apply(Harmony harmony, IMonitor monitor); + + + /********* + ** Protected methods + *********/ + /// Get a method and assert that it was found. + /// The type containing the method. + /// The method parameter types, or null if it's not overloaded. + protected ConstructorInfo RequireConstructor(params Type[] parameters) + { + return PatchHelper.RequireConstructor(parameters); + } + + /// Get a method and assert that it was found. + /// The type containing the method. + /// The method name. + /// The method parameter types, or null if it's not overloaded. + /// The method generic types, or null if it's not generic. + protected MethodInfo RequireMethod(string name, Type[] parameters = null, Type[] generics = null) + { + return PatchHelper.RequireMethod(name, parameters, generics); + } + + /// Get a Harmony patch method on the current patcher instance. + /// The method name. + /// The patch priority to apply, usually specified using Harmony's enum, or null to keep the default value. + protected HarmonyMethod GetHarmonyMethod(string name, int? priority = null) + { + var method = new HarmonyMethod( + AccessTools.Method(this.GetType(), name) + ?? throw new InvalidOperationException($"Can't find patcher method {PatchHelper.GetMethodString(this.GetType(), name)}.") + ); + + if (priority.HasValue) + method.priority = priority.Value; + + return method; + } + } +} -- cgit