Utility.cs 7.2 KB

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