Utility.cs 8.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292
  1. using System;
  2. using System.Collections.Generic;
  3. using System.IO;
  4. using System.Linq;
  5. using System.Reflection;
  6. using System.Reflection.Emit;
  7. using Mono.Cecil;
  8. using MonoMod.Utils;
  9. namespace BepInEx
  10. {
  11. /// <summary>
  12. /// Generic helper properties and methods.
  13. /// </summary>
  14. public static class Utility
  15. {
  16. private static bool? sreEnabled;
  17. /// <summary>
  18. /// Whether current Common Language Runtime supports dynamic method generation using <see cref="System.Reflection.Emit"/> namespace.
  19. /// </summary>
  20. public static bool CLRSupportsDynamicAssemblies => CheckSRE();
  21. private static bool CheckSRE()
  22. {
  23. if (sreEnabled.HasValue)
  24. return sreEnabled.Value;
  25. try
  26. {
  27. // ReSharper disable once AssignNullToNotNullAttribute
  28. _ = new CustomAttributeBuilder(null, new object[0]);
  29. }
  30. catch (PlatformNotSupportedException)
  31. {
  32. sreEnabled = false;
  33. return sreEnabled.Value;
  34. }
  35. catch (ArgumentNullException)
  36. {
  37. // Suppress ArgumentNullException
  38. }
  39. sreEnabled = true;
  40. return sreEnabled.Value;
  41. }
  42. static Utility()
  43. {
  44. CheckPlatform();
  45. }
  46. /// <summary>
  47. /// Try to perform an action.
  48. /// </summary>
  49. /// <param name="action">Action to perform.</param>
  50. /// <param name="exception">Possible exception that gets returned.</param>
  51. /// <returns>True, if action succeeded, false if an exception occured.</returns>
  52. public static bool TryDo(Action action, out Exception exception)
  53. {
  54. exception = null;
  55. try
  56. {
  57. action();
  58. return true;
  59. }
  60. catch (Exception e)
  61. {
  62. exception = e;
  63. return false;
  64. }
  65. }
  66. /// <summary>
  67. /// Combines multiple paths together, as the specific method is not available in .NET 3.5.
  68. /// </summary>
  69. /// <param name="parts">The multiple paths to combine together.</param>
  70. /// <returns>A combined path.</returns>
  71. public static string CombinePaths(params string[] parts) => parts.Aggregate(Path.Combine);
  72. /// <summary>
  73. /// Returns the parent directory of a path, optionally specifying the amount of levels.
  74. /// </summary>
  75. /// <param name="path">The path to get the parent directory of.</param>
  76. /// <param name="levels">The amount of levels to traverse. Defaults to 1</param>
  77. /// <returns>The parent directory.</returns>
  78. public static string ParentDirectory(string path, int levels = 1)
  79. {
  80. for (int i = 0; i < levels; i++)
  81. path = Path.GetDirectoryName(path);
  82. return path;
  83. }
  84. /// <summary>
  85. /// Tries to parse a bool, with a default value if unable to parse.
  86. /// </summary>
  87. /// <param name="input">The string to parse</param>
  88. /// <param name="defaultValue">The value to return if parsing is unsuccessful.</param>
  89. /// <returns>Boolean value of input if able to be parsed, otherwise default value.</returns>
  90. public static bool SafeParseBool(string input, bool defaultValue = false)
  91. {
  92. return Boolean.TryParse(input, out bool result) ? result : defaultValue;
  93. }
  94. /// <summary>
  95. /// Converts a file path into a UnityEngine.WWW format.
  96. /// </summary>
  97. /// <param name="path">The file path to convert.</param>
  98. /// <returns>A converted file path.</returns>
  99. public static string ConvertToWWWFormat(string path)
  100. {
  101. return $"file://{path.Replace('\\', '/')}";
  102. }
  103. /// <summary>
  104. /// Indicates whether a specified string is null, empty, or consists only of white-space characters.
  105. /// </summary>
  106. /// <param name="self">The string to test.</param>
  107. /// <returns>True if the value parameter is null or empty, or if value consists exclusively of white-space characters.</returns>
  108. public static bool IsNullOrWhiteSpace(this string self)
  109. {
  110. return self == null || self.All(Char.IsWhiteSpace);
  111. }
  112. public static IEnumerable<TNode> TopologicalSort<TNode>(IEnumerable<TNode> nodes, Func<TNode, IEnumerable<TNode>> dependencySelector)
  113. {
  114. List<TNode> sorted_list = new List<TNode>();
  115. HashSet<TNode> visited = new HashSet<TNode>();
  116. HashSet<TNode> sorted = new HashSet<TNode>();
  117. foreach (TNode input in nodes)
  118. {
  119. Stack<TNode> currentStack = new Stack<TNode>();
  120. if (!Visit(input, currentStack))
  121. {
  122. throw new Exception("Cyclic Dependency:\r\n" + currentStack.Select(x => $" - {x}") //append dashes
  123. .Aggregate((a, b) => $"{a}\r\n{b}")); //add new lines inbetween
  124. }
  125. }
  126. return sorted_list;
  127. bool Visit(TNode node, Stack<TNode> stack)
  128. {
  129. if (visited.Contains(node))
  130. {
  131. if (!sorted.Contains(node))
  132. {
  133. return false;
  134. }
  135. }
  136. else
  137. {
  138. visited.Add(node);
  139. stack.Push(node);
  140. foreach (var dep in dependencySelector(node))
  141. if (!Visit(dep, stack))
  142. return false;
  143. sorted.Add(node);
  144. sorted_list.Add(node);
  145. stack.Pop();
  146. }
  147. return true;
  148. }
  149. }
  150. /// <summary>
  151. /// Try to resolve and load the given assembly DLL.
  152. /// </summary>
  153. /// <param name="assemblyName">Name of the assembly, of the type <see cref="AssemblyName" />.</param>
  154. /// <param name="directory">Directory to search the assembly from.</param>
  155. /// <param name="assembly">The loaded assembly.</param>
  156. /// <returns>True, if the assembly was found and loaded. Otherwise, false.</returns>
  157. private static bool TryResolveDllAssembly<T>(AssemblyName assemblyName, string directory, Func<string, T> loader, out T assembly) where T : class
  158. {
  159. assembly = null;
  160. var potentialDirectories = new List<string> { directory };
  161. potentialDirectories.AddRange(Directory.GetDirectories(directory, "*", SearchOption.AllDirectories));
  162. foreach (string subDirectory in potentialDirectories)
  163. {
  164. string path = Path.Combine(subDirectory, $"{assemblyName.Name}.dll");
  165. if (!File.Exists(path))
  166. continue;
  167. try
  168. {
  169. assembly = loader(path);
  170. }
  171. catch (Exception)
  172. {
  173. continue;
  174. }
  175. return true;
  176. }
  177. return false;
  178. }
  179. public static bool IsSubtypeOf(this TypeDefinition self, Type td)
  180. {
  181. if (self.FullName == td.FullName)
  182. return true;
  183. return self.FullName != "System.Object" && (self.BaseType?.Resolve()?.IsSubtypeOf(td) ?? false);
  184. }
  185. /// <summary>
  186. /// Try to resolve and load the given assembly DLL.
  187. /// </summary>
  188. /// <param name="assemblyName">Name of the assembly, of the type <see cref="AssemblyName" />.</param>
  189. /// <param name="directory">Directory to search the assembly from.</param>
  190. /// <param name="assembly">The loaded assembly.</param>
  191. /// <returns>True, if the assembly was found and loaded. Otherwise, false.</returns>
  192. public static bool TryResolveDllAssembly(AssemblyName assemblyName, string directory, out Assembly assembly)
  193. {
  194. return TryResolveDllAssembly(assemblyName, directory, Assembly.LoadFile, out assembly);
  195. }
  196. /// <summary>
  197. /// Try to resolve and load the given assembly DLL.
  198. /// </summary>
  199. /// <param name="assemblyName">Name of the assembly, of the type <see cref="AssemblyName" />.</param>
  200. /// <param name="directory">Directory to search the assembly from.</param>
  201. /// <param name="assembly">The loaded assembly.</param>
  202. /// <returns>True, if the assembly was found and loaded. Otherwise, false.</returns>
  203. public static bool TryResolveDllAssembly(AssemblyName assemblyName, string directory, ReaderParameters readerParameters, out AssemblyDefinition assembly)
  204. {
  205. return TryResolveDllAssembly(assemblyName, directory, s => AssemblyDefinition.ReadAssembly(s, readerParameters), out assembly);
  206. }
  207. /// <summary>
  208. /// Tries to create a file with the given name
  209. /// </summary>
  210. /// <param name="path">Path of the file to create</param>
  211. /// <param name="mode">File open mode</param>
  212. /// <param name="fileStream">Resulting filestream</param>
  213. /// <param name="access">File access options</param>
  214. /// <param name="share">File share options</param>
  215. /// <returns></returns>
  216. public static bool TryOpenFileStream(string path, FileMode mode, out FileStream fileStream, FileAccess access = FileAccess.ReadWrite, FileShare share = FileShare.Read)
  217. {
  218. try
  219. {
  220. fileStream = new FileStream(path, mode, access, share);
  221. return true;
  222. }
  223. catch (IOException)
  224. {
  225. fileStream = null;
  226. return false;
  227. }
  228. }
  229. // Adapted from https://github.com/MonoMod/MonoMod.Common/blob/master/Utils/PlatformHelper.cs#L13
  230. private static void CheckPlatform()
  231. {
  232. var pPlatform = typeof(Environment).GetProperty("Platform", BindingFlags.NonPublic | BindingFlags.Static);
  233. string platId = pPlatform != null ? pPlatform.GetValue(null, new object[0]).ToString() : Environment.OSVersion.Platform.ToString();
  234. platId = platId.ToLowerInvariant();
  235. var cur = Platform.Unknown;
  236. if (platId.Contains("win"))
  237. cur = Platform.Windows;
  238. else if (platId.Contains("mac") || platId.Contains("osx"))
  239. cur = Platform.MacOS;
  240. else if (platId.Contains("lin") || platId.Contains("unix"))
  241. cur = Platform.Linux;
  242. CurrentOs = cur;
  243. }
  244. /// <summary>
  245. /// Current OS BepInEx is running on.
  246. /// </summary>
  247. public static Platform CurrentOs { get; private set; }
  248. }
  249. }