Utility.cs 6.6 KB

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