Utility.cs 8.2 KB

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