Decompiled source of GlobalConfigRedirect v0.2.0

patchers\GlobalConfigRedirect.dll

Decompiled a month ago
using System;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.Versioning;
using System.Text.RegularExpressions;
using BepInEx;
using BepInEx.Configuration;
using BepInEx.Core.Logging.Interpolation;
using BepInEx.Logging;
using BepInEx.Preloader.Core.Patching;
using HarmonyLib;
using Microsoft.CodeAnalysis;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: TargetFramework(".NETCoreApp,Version=v6.0", FrameworkDisplayName = "")]
[assembly: AssemblyCompany("GlobalConfigRedirect")]
[assembly: AssemblyConfiguration("Release")]
[assembly: AssemblyFileVersion("1.0.0.0")]
[assembly: AssemblyInformationalVersion("1.0.0")]
[assembly: AssemblyProduct("GlobalConfigRedirect")]
[assembly: AssemblyTitle("GlobalConfigRedirect")]
[assembly: AssemblyVersion("1.0.0.0")]
namespace Microsoft.CodeAnalysis
{
	[CompilerGenerated]
	[Embedded]
	internal sealed class EmbeddedAttribute : Attribute
	{
	}
}
namespace System.Runtime.CompilerServices
{
	[CompilerGenerated]
	[Embedded]
	[AttributeUsage(AttributeTargets.Class | AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Event | AttributeTargets.Parameter | AttributeTargets.ReturnValue | AttributeTargets.GenericParameter, AllowMultiple = false, Inherited = false)]
	internal sealed class NullableAttribute : Attribute
	{
		public readonly byte[] NullableFlags;

		public NullableAttribute(byte P_0)
		{
			NullableFlags = new byte[1] { P_0 };
		}

		public NullableAttribute(byte[] P_0)
		{
			NullableFlags = P_0;
		}
	}
	[CompilerGenerated]
	[Embedded]
	[AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Method | AttributeTargets.Interface | AttributeTargets.Delegate, AllowMultiple = false, Inherited = false)]
	internal sealed class NullableContextAttribute : Attribute
	{
		public readonly byte Flag;

		public NullableContextAttribute(byte P_0)
		{
			Flag = P_0;
		}
	}
}
namespace GlobalConfigRedirect
{
	[PatcherPluginInfo("io.takina.gtfo.GlobalConfigRedirect", "GlobalConfigRedirect", "0.2.0")]
	public class Patcher : BasePatcher
	{
		public const string NAME = "GlobalConfigRedirect";

		public const string GUID = "io.takina.gtfo.GlobalConfigRedirect";

		public const string VERSION = "0.2.0";

		public const string FolderName = "GTFO.GlobalConfigRedirect";

		public static readonly string DefaultGlobalFolderName = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), "GTFO.GlobalConfigRedirect", "config");

		public override void Initialize()
		{
			//IL_00df: Unknown result type (might be due to invalid IL or missing references)
			//IL_00e6: Expected O, but got Unknown
			//IL_0135: Unknown result type (might be due to invalid IL or missing references)
			//IL_0143: Expected O, but got Unknown
			//IL_016b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0178: Expected O, but got Unknown
			//IL_0184: Unknown result type (might be due to invalid IL or missing references)
			//IL_018b: Expected O, but got Unknown
			string value = ((BasePatcher)this).Config.Bind<string>("General", "Global Folder", "", "Global config folder. Environment variables are expanded. Empty = " + DefaultGlobalFolderName).Value;
			string value2 = ((BasePatcher)this).Config.Bind<string>("General", "Include", "**", "Comma-separated globs matched against the path relative to this profile's config folder. * and ? stay within one folder, ** spans folders. e.g. *.cfg (top level only), Hikaria/**, **").Value;
			string value3 = ((BasePatcher)this).Config.Bind<string>("General", "Exclude", "", "Comma-separated globs; files matching these stay in the profile. Takes priority over Include.").Value;
			bool value4 = ((BasePatcher)this).Config.Bind<bool>("General", "Copy Existing", true, "When a redirected file doesn't exist globally yet, seed it with this profile's copy.").Value;
			((BasePatcher)this).Config.Save();
			value = (string.IsNullOrWhiteSpace(value) ? DefaultGlobalFolderName : Environment.ExpandEnvironmentVariables(value.Trim()));
			Redirect.Setup(((BasePatcher)this).Log, value, value2, value3, value4, ((BasePatcher)this).Config.ConfigFilePath);
			Harmony val = new Harmony("io.takina.gtfo.GlobalConfigRedirect");
			val.Patch((MethodBase)AccessTools.Constructor(typeof(ConfigFile), new Type[3]
			{
				typeof(string),
				typeof(bool),
				typeof(BepInPlugin)
			}, false), new HarmonyMethod(typeof(Redirect), "Prefix__ConfigFile_Ctor", (Type[])null), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
			val.Patch((MethodBase)AccessTools.PropertyGetter(typeof(Paths), "ConfigPath"), (HarmonyMethod)null, new HarmonyMethod(typeof(Redirect), "Postfix__Paths_ConfigPath_Getter", (Type[])null), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
			ManualLogSource log = ((BasePatcher)this).Log;
			bool flag = default(bool);
			BepInExInfoLogInterpolatedStringHandler val2 = new BepInExInfoLogInterpolatedStringHandler(39, 4, ref flag);
			if (flag)
			{
				((BepInExLogInterpolatedStringHandler)val2).AppendLiteral("Redirecting ");
				((BepInExLogInterpolatedStringHandler)val2).AppendFormatted<string>(Redirect.ProfileFolder);
				((BepInExLogInterpolatedStringHandler)val2).AppendLiteral(" -> ");
				((BepInExLogInterpolatedStringHandler)val2).AppendFormatted<string>(Redirect.GlobalFolder);
				((BepInExLogInterpolatedStringHandler)val2).AppendLiteral(" (include: ");
				((BepInExLogInterpolatedStringHandler)val2).AppendFormatted<string>(value2);
				((BepInExLogInterpolatedStringHandler)val2).AppendLiteral("; exclude: ");
				((BepInExLogInterpolatedStringHandler)val2).AppendFormatted<string>(value3);
				((BepInExLogInterpolatedStringHandler)val2).AppendLiteral(")");
			}
			log.LogInfo(val2);
		}
	}
	internal static class Redirect
	{
		private static ManualLogSource _log = null;

		private static Regex[] _include = Array.Empty<Regex>();

		private static Regex[] _exclude = Array.Empty<Regex>();

		private static bool _copyExisting;

		private static string _ownConfigPath = "";

		public static string ProfileFolder { get; private set; } = "";

		public static string GlobalFolder { get; private set; } = "";

		public static void Setup(ManualLogSource log, string globalFolder, string include, string exclude, bool copyExisting, string ownConfigPath)
		{
			_log = log;
			ProfileFolder = WithSeparator(Path.GetFullPath(Paths.ConfigPath));
			GlobalFolder = Path.GetFullPath(globalFolder);
			_include = ParseGlobs(include);
			_exclude = ParseGlobs(exclude);
			_copyExisting = copyExisting;
			_ownConfigPath = Path.GetFullPath(ownConfigPath);
		}

		public static void Prefix__ConfigFile_Ctor(ref string? configPath)
		{
			//IL_0021: Unknown result type (might be due to invalid IL or missing references)
			//IL_0027: Expected O, but got Unknown
			if (configPath == null)
			{
				return;
			}
			try
			{
				if (TryMap(configPath, out string target))
				{
					configPath = target;
				}
			}
			catch (Exception ex)
			{
				ManualLogSource log = _log;
				bool flag = default(bool);
				BepInExErrorLogInterpolatedStringHandler val = new BepInExErrorLogInterpolatedStringHandler(42, 2, ref flag);
				if (flag)
				{
					((BepInExLogInterpolatedStringHandler)val).AppendLiteral("Failed to redirect ");
					((BepInExLogInterpolatedStringHandler)val).AppendFormatted<string>(configPath);
					((BepInExLogInterpolatedStringHandler)val).AppendLiteral(", leaving it in place: ");
					((BepInExLogInterpolatedStringHandler)val).AppendFormatted<Exception>(ex);
				}
				log.LogError(val);
			}
		}

		public static void Postfix__Paths_ConfigPath_Getter(ref string __result)
		{
			//IL_0020: Unknown result type (might be due to invalid IL or missing references)
			//IL_0026: Expected O, but got Unknown
			try
			{
				if (CheckQualification(__result, out string _, directory: true))
				{
					__result = GlobalFolder;
				}
			}
			catch (Exception ex)
			{
				ManualLogSource log = _log;
				bool flag = default(bool);
				BepInExErrorLogInterpolatedStringHandler val = new BepInExErrorLogInterpolatedStringHandler(42, 2, ref flag);
				if (flag)
				{
					((BepInExLogInterpolatedStringHandler)val).AppendLiteral("Failed to redirect ");
					((BepInExLogInterpolatedStringHandler)val).AppendFormatted<string>(__result);
					((BepInExLogInterpolatedStringHandler)val).AppendLiteral(", leaving it in place: ");
					((BepInExLogInterpolatedStringHandler)val).AppendFormatted<Exception>(ex);
				}
				log.LogError(val);
			}
		}

		private static bool TryMap(string configPath, out string target)
		{
			//IL_00fa: Unknown result type (might be due to invalid IL or missing references)
			//IL_0101: Expected O, but got Unknown
			//IL_00c0: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c6: Expected O, but got Unknown
			target = "";
			if (!CheckQualification(configPath, out string full))
			{
				return false;
			}
			string rel = full.Substring(ProfileFolder.Length).Replace('\\', '/');
			if (!_include.Any((Regex r) => r.IsMatch(rel)) || _exclude.Any((Regex r) => r.IsMatch(rel)))
			{
				return false;
			}
			target = Path.Combine(GlobalFolder, rel.Replace('/', Path.DirectorySeparatorChar));
			bool flag = default(bool);
			if (_copyExisting && !File.Exists(target) && File.Exists(full))
			{
				Directory.CreateDirectory(Path.GetDirectoryName(target));
				File.Copy(full, target);
				ManualLogSource log = _log;
				BepInExInfoLogInterpolatedStringHandler val = new BepInExInfoLogInterpolatedStringHandler(27, 1, ref flag);
				if (flag)
				{
					((BepInExLogInterpolatedStringHandler)val).AppendLiteral("Seeded global ");
					((BepInExLogInterpolatedStringHandler)val).AppendFormatted<string>(rel);
					((BepInExLogInterpolatedStringHandler)val).AppendLiteral(" from profile");
				}
				log.LogInfo(val);
			}
			ManualLogSource log2 = _log;
			BepInExDebugLogInterpolatedStringHandler val2 = new BepInExDebugLogInterpolatedStringHandler(4, 2, ref flag);
			if (flag)
			{
				((BepInExLogInterpolatedStringHandler)val2).AppendFormatted<string>(rel);
				((BepInExLogInterpolatedStringHandler)val2).AppendLiteral(" -> ");
				((BepInExLogInterpolatedStringHandler)val2).AppendFormatted<string>(target);
			}
			log2.LogDebug(val2);
			return true;
		}

		private static bool CheckQualification(string path, out string full, bool directory = false)
		{
			full = Path.GetFullPath(path);
			if (directory)
			{
				full = WithSeparator(full);
			}
			if (!full.StartsWith(ProfileFolder, StringComparison.OrdinalIgnoreCase))
			{
				return false;
			}
			if (string.Equals(full, _ownConfigPath, StringComparison.OrdinalIgnoreCase) || string.Equals(full, Path.GetFullPath(Paths.BepInExConfigPath), StringComparison.OrdinalIgnoreCase))
			{
				return false;
			}
			return true;
		}

		private static Regex[] ParseGlobs(string globs)
		{
			return (from g in globs.Split(',', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries)
				select new Regex(GlobToRegex(g), RegexOptions.IgnoreCase | RegexOptions.CultureInvariant)).ToArray();
		}

		internal static string GlobToRegex(string glob)
		{
			return "^" + Regex.Escape(glob.Replace('\\', '/')).Replace("\\*\\*/", "(?:.*/)?").Replace("\\*\\*", ".*")
				.Replace("\\*", "[^/]*")
				.Replace("\\?", "[^/]") + "$";
		}

		private static string WithSeparator(string dir)
		{
			if (!dir.EndsWith(Path.DirectorySeparatorChar))
			{
				return dir + Path.DirectorySeparatorChar;
			}
			return dir;
		}
	}
}