Utility.cs 8.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283
  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. /// Returns the parent directory of a path, optionally specifying the amount of levels.
  66. /// </summary>
  67. /// <param name="path">The path to get the parent directory of.</param>
  68. /// <param name="levels">The amount of levels to traverse. Defaults to 1</param>
  69. /// <returns>The parent directory.</returns>
  70. public static string ParentDirectory(string path, int levels = 1)
  71. {
  72. for (int i = 0; i < levels; i++)
  73. path = Path.GetDirectoryName(path);
  74. return path;
  75. }
  76. /// <summary>
  77. /// Tries to parse a bool, with a default value if unable to parse.
  78. /// </summary>
  79. /// <param name="input">The string to parse</param>
  80. /// <param name="defaultValue">The value to return if parsing is unsuccessful.</param>
  81. /// <returns>Boolean value of input if able to be parsed, otherwise default value.</returns>
  82. public static bool SafeParseBool(string input, bool defaultValue = false)
  83. {
  84. return Boolean.TryParse(input, out bool result) ? result : defaultValue;
  85. }
  86. /// <summary>
  87. /// Converts a file path into a UnityEngine.WWW format.
  88. /// </summary>
  89. /// <param name="path">The file path to convert.</param>
  90. /// <returns>A converted file path.</returns>
  91. public static string ConvertToWWWFormat(string path)
  92. {
  93. return $"file://{path.Replace('\\', '/')}";
  94. }
  95. /// <summary>
  96. /// Indicates whether a specified string is null, empty, or consists only of white-space characters.
  97. /// </summary>
  98. /// <param name="self">The string to test.</param>
  99. /// <returns>True if the value parameter is null or empty, or if value consists exclusively of white-space characters.</returns>
  100. public static bool IsNullOrWhiteSpace(this string self)
  101. {
  102. return self == null || self.All(Char.IsWhiteSpace);
  103. }
  104. public static IEnumerable<TNode> TopologicalSort<TNode>(IEnumerable<TNode> nodes, Func<TNode, IEnumerable<TNode>> dependencySelector)
  105. {
  106. List<TNode> sorted_list = new List<TNode>();
  107. HashSet<TNode> visited = new HashSet<TNode>();
  108. HashSet<TNode> sorted = new HashSet<TNode>();
  109. foreach (TNode input in nodes)
  110. {
  111. Stack<TNode> currentStack = new Stack<TNode>();
  112. if (!Visit(input, currentStack))
  113. {
  114. throw new Exception("Cyclic Dependency:\r\n" + currentStack.Select(x => $" - {x}") //append dashes
  115. .Aggregate((a, b) => $"{a}\r\n{b}")); //add new lines inbetween
  116. }
  117. }
  118. return sorted_list;
  119. bool Visit(TNode node, Stack<TNode> stack)
  120. {
  121. if (visited.Contains(node))
  122. {
  123. if (!sorted.Contains(node))
  124. {
  125. return false;
  126. }
  127. }
  128. else
  129. {
  130. visited.Add(node);
  131. stack.Push(node);
  132. foreach (var dep in dependencySelector(node))
  133. if (!Visit(dep, stack))
  134. return false;
  135. sorted.Add(node);
  136. sorted_list.Add(node);
  137. stack.Pop();
  138. }
  139. return true;
  140. }
  141. }
  142. /// <summary>
  143. /// Try to resolve and load the given assembly DLL.
  144. /// </summary>
  145. /// <param name="assemblyName">Name of the assembly, of the type <see cref="AssemblyName" />.</param>
  146. /// <param name="directory">Directory to search the assembly from.</param>
  147. /// <param name="assembly">The loaded assembly.</param>
  148. /// <returns>True, if the assembly was found and loaded. Otherwise, false.</returns>
  149. private static bool TryResolveDllAssembly<T>(AssemblyName assemblyName, string directory, Func<string, T> loader, out T assembly) where T : class
  150. {
  151. assembly = null;
  152. var potentialDirectories = new List<string> { directory };
  153. potentialDirectories.AddRange(Directory.GetDirectories(directory, "*", SearchOption.AllDirectories));
  154. foreach (string subDirectory in potentialDirectories)
  155. {
  156. string path = Path.Combine(subDirectory, $"{assemblyName.Name}.dll");
  157. if (!File.Exists(path))
  158. continue;
  159. try
  160. {
  161. assembly = loader(path);
  162. }
  163. catch (Exception)
  164. {
  165. continue;
  166. }
  167. return true;
  168. }
  169. return false;
  170. }
  171. public static bool IsSubtypeOf(this TypeDefinition self, Type td)
  172. {
  173. if (self.FullName == td.FullName)
  174. return true;
  175. return self.FullName != "System.Object" && (self.BaseType?.Resolve()?.IsSubtypeOf(td) ?? false);
  176. }
  177. /// <summary>
  178. /// Try to resolve and load the given assembly DLL.
  179. /// </summary>
  180. /// <param name="assemblyName">Name of the assembly, of the type <see cref="AssemblyName" />.</param>
  181. /// <param name="directory">Directory to search the assembly from.</param>
  182. /// <param name="assembly">The loaded assembly.</param>
  183. /// <returns>True, if the assembly was found and loaded. Otherwise, false.</returns>
  184. public static bool TryResolveDllAssembly(AssemblyName assemblyName, string directory, out Assembly assembly)
  185. {
  186. return TryResolveDllAssembly(assemblyName, directory, Assembly.LoadFile, out assembly);
  187. }
  188. /// <summary>
  189. /// Try to resolve and load the given assembly DLL.
  190. /// </summary>
  191. /// <param name="assemblyName">Name of the assembly, of the type <see cref="AssemblyName" />.</param>
  192. /// <param name="directory">Directory to search the assembly from.</param>
  193. /// <param name="assembly">The loaded assembly.</param>
  194. /// <returns>True, if the assembly was found and loaded. Otherwise, false.</returns>
  195. public static bool TryResolveDllAssembly(AssemblyName assemblyName, string directory, ReaderParameters readerParameters, out AssemblyDefinition assembly)
  196. {
  197. return TryResolveDllAssembly(assemblyName, directory, s => AssemblyDefinition.ReadAssembly(s, readerParameters), out assembly);
  198. }
  199. /// <summary>
  200. /// Tries to create a file with the given name
  201. /// </summary>
  202. /// <param name="path">Path of the file to create</param>
  203. /// <param name="mode">File open mode</param>
  204. /// <param name="fileStream">Resulting filestream</param>
  205. /// <param name="access">File access options</param>
  206. /// <param name="share">File share options</param>
  207. /// <returns></returns>
  208. public static bool TryOpenFileStream(string path, FileMode mode, out FileStream fileStream, FileAccess access = FileAccess.ReadWrite, FileShare share = FileShare.Read)
  209. {
  210. try
  211. {
  212. fileStream = new FileStream(path, mode, access, share);
  213. return true;
  214. }
  215. catch (IOException)
  216. {
  217. fileStream = null;
  218. return false;
  219. }
  220. }
  221. // Adapted from https://github.com/MonoMod/MonoMod.Common/blob/master/Utils/PlatformHelper.cs#L13
  222. private static void CheckPlatform()
  223. {
  224. var pPlatform = typeof(Environment).GetProperty("Platform", BindingFlags.NonPublic | BindingFlags.Static);
  225. string platId = pPlatform != null ? pPlatform.GetValue(null, new object[0]).ToString() : Environment.OSVersion.Platform.ToString();
  226. platId = platId.ToLowerInvariant();
  227. var cur = Platform.Unknown;
  228. if (platId.Contains("win"))
  229. cur = Platform.Windows;
  230. else if (platId.Contains("mac") || platId.Contains("osx"))
  231. cur = Platform.MacOS;
  232. else if (platId.Contains("lin") || platId.Contains("unix"))
  233. cur = Platform.Linux;
  234. CurrentOs = cur;
  235. }
  236. /// <summary>
  237. /// Current OS BepInEx is running on.
  238. /// </summary>
  239. public static Platform CurrentOs { get; private set; }
  240. }
  241. }